import React, { useState, useEffect, useMemo } from "react";
import Swal from "sweetalert2";
import { useUpload } from "../../context/UploadContext";
import ViewToggle from "../shared/ViewToggle";
import FilterBar from "../shared/FilterBar";
import SelectionToolbar from "../shared/SelectionToolbar";
import ImagePreviewModal from "../shared/ImagePreviewModal";
import { useGenerator } from "../../context/GeneratorContext";
import OpenAIGenerator from "../features/openai/OpenAIGenerator";
import GeminiGenerator from "../features/gemini/GeminiGenerator";
import PexelsGallery from "../features/pexels/PexelsGallery";
import PixabayGallery from "../features/pixabay/PixabayGallery";
import UnsplashGallery from "../features/unsplash/UnsplashGallery";
import OpenverseGallery from "../features/openverse/OpenverseGallery";
import WikimediaGallery from "../features/wikimedia/WikimediaGallery";
import GiphyGallery from "../features/giphy/GiphyGallery";
import FavoritesGallery from "../features/favorites/FavoritesGallery";
import GlobalGallery from "../features/global/GlobalGallery";

const PhotoIcon = ({ className = "w-5 h-5" }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
  </svg>
);
const ImageIcon = ({ className = "w-5 h-5" }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
  </svg>
);
const CameraIcon = ({ className = "w-5 h-5" }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
    <path strokeLinecap="round" strokeLinejoin="round" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
    <path strokeLinecap="round" strokeLinejoin="round" d="M19 13v4a2 2 0 01-2 2H7a2 2 0 01-2-2v-4M14 12v.01" />
  </svg>
);
const GlobeIcon = ({ className = "w-5 h-5" }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
  </svg>
);
const GifIcon = ({ className = "w-5 h-5" }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
    <path strokeLinecap="round" strokeLinejoin="round" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
  </svg>
);
const SparklesIcon = ({ className = "w-5 h-5" }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z" />
  </svg>
);

const StarsIcon = ({ className = "w-5 h-5" }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" />
  </svg>
);

const HeartIconSmall = ({ className = "w-5 h-5" }) => (
  <svg className={className} fill="currentColor" viewBox="0 0 24 24">
    <path d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
  </svg>
);

const SearchIconTab = ({ className = "w-5 h-5" }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
  </svg>
);

const PROVIDER_META = {
  global: { icon: SearchIconTab, color: "indigo", description: "Search across all enabled providers at once" },
  favorites: { icon: HeartIconSmall, color: "pink", description: "Your saved favorites" },
  pexels: { icon: PhotoIcon, color: "blue", description: "High-quality stock photos" },
  pixabay: { icon: ImageIcon, color: "green", description: "Free images and videos" },
  unsplash: { icon: CameraIcon, color: "purple", description: "Beautiful free images" },
  openverse: { icon: GlobeIcon, color: "orange", description: "Open-licensed content" },
  wikimedia: { icon: GlobeIcon, color: "cyan", description: "Wikimedia Commons images", badge: "NEW" },
  giphy: { icon: GifIcon, color: "pink", description: "Animated GIFs", badge: "NEW" },
  openai: { icon: SparklesIcon, color: "indigo", description: "AI-generated images" },
  gemini: { icon: StarsIcon, color: "blue", description: "Google Gemini AI images", badge: "NEW" },
};

const GLOBAL_TAB = { id: "global", label: "Global Search", component: GlobalGallery };
const FAVORITES_TAB = { id: "favorites", label: "Favorites", component: FavoritesGallery };

const TABS_BY_ID = {
  pexels: { id: "pexels", label: "Pexels", component: PexelsGallery },
  pixabay: { id: "pixabay", label: "Pixabay", component: PixabayGallery },
  unsplash: { id: "unsplash", label: "Unsplash", component: UnsplashGallery },
  openverse: { id: "openverse", label: "Openverse", component: OpenverseGallery },
  wikimedia: { id: "wikimedia", label: "Wikimedia", component: WikimediaGallery, badge: "NEW" },
  giphy: { id: "giphy", label: "Giphy", component: GiphyGallery, badge: "NEW" },
  openai: { id: "openai", label: "OpenAI", component: OpenAIGenerator },
  gemini: { id: "gemini", label: "Gemini", component: GeminiGenerator, badge: "NEW" },
};

const DEFAULT_ORDER = ["pexels", "pixabay", "openverse", "wikimedia", "unsplash", "giphy", "openai", "gemini"];

function getEnabledTabs() {
  const config = typeof AI_IMAGE_AdminConfig !== "undefined" ? AI_IMAGE_AdminConfig : {};
  const enabled = config.provider_enabled || {};
  const order = Array.isArray(config.provider_order) && config.provider_order.length > 0
    ? config.provider_order
    : DEFAULT_ORDER;
  // Ensure all known provider IDs are in the order list
  const fullOrder = [...order];
  DEFAULT_ORDER.forEach((id) => {
    if (!fullOrder.includes(id)) fullOrder.push(id);
  });
  const providerTabs = fullOrder
    .filter((id) => TABS_BY_ID[id] && enabled[id] !== false)
    .map((id) => TABS_BY_ID[id]);
  // Global Search tab is conditionally shown based on setting (default: enabled)
  const globalEnabled = enabled.global !== false;
  const tabs = [];
  if (globalEnabled) tabs.push(GLOBAL_TAB);
  tabs.push(FAVORITES_TAB);
  tabs.push(...providerTabs);
  return tabs;
}

function getDefaultTabId() {
  const config = typeof AI_IMAGE_AdminConfig !== "undefined" ? AI_IMAGE_AdminConfig : {};
  const TABS = getEnabledTabs();
  const defaultId = config.general_settings?.default_provider || "global";
  const exists = TABS.some((t) => t.id === defaultId);
  return exists ? defaultId : TABS[0]?.id || "global";
}

export default function Dashboard() {
  // Force re-computation of tabs when settings are updated
  const [tabVersion, setTabVersion] = useState(0);
  const TABS = useMemo(() => getEnabledTabs(), [tabVersion]);

  // Listen for settings updates to re-compute tab order and visibility
  useEffect(() => {
    const handleSettingsUpdate = (event) => {
      const detail = event.detail;
      if (typeof AI_IMAGE_AdminConfig !== "undefined") {
        if (detail?.provider_order) {
          AI_IMAGE_AdminConfig.provider_order = detail.provider_order;
        }
        if (detail?.provider_enabled) {
          AI_IMAGE_AdminConfig.provider_enabled = { ...detail.provider_enabled };
        }
        if (detail?.default_provider) {
          AI_IMAGE_AdminConfig.general_settings = AI_IMAGE_AdminConfig.general_settings || {};
          AI_IMAGE_AdminConfig.general_settings.default_provider = detail.default_provider;
        }
      }
      setTabVersion((v) => v + 1);
      
      // Update active tab if default provider changed
      if (detail?.default_provider) {
        setActiveTab(detail.default_provider);
      }
    };
    window.addEventListener("aiImageSettingsUpdated", handleSettingsUpdate);
    return () => window.removeEventListener("aiImageSettingsUpdated", handleSettingsUpdate);
  }, []);

  // Get initial tab from settings default provider
  const getInitialTab = () => {
    return getDefaultTabId();
  };
  
  const [activeTab, setActiveTab] = useState(getInitialTab);
  const { uploadImage } = useUpload();
  const { selectionMode, setSelectionMode, clearSelection, isGenerating } = useGenerator();

  const currentTabValid = TABS.some((t) => t.id === activeTab);
  const effectiveTab = currentTabValid ? activeTab : TABS[0]?.id;
  const effectiveTabs = TABS;

  // Clear selection when changing tabs
  useEffect(() => {
    clearSelection();
  }, [effectiveTab, clearSelection]);

  useEffect(() => {
    const handleGlobalClick = (event) => {
      const btn = event.target.closest(".bdt-aimg-download-btn");
      if (btn) {
        const imageUrl = btn.getAttribute("data-url");
        const imageTitle = btn.getAttribute("data-title") || "";
        const imageAuthor = btn.getAttribute("data-author") || "";
        if (imageUrl) {
          uploadImage(imageUrl, imageTitle, imageAuthor);
        }
      }
    };

    document.addEventListener("click", handleGlobalClick);

    if (!Swal.showToast) {
      Swal.showToast = Swal.mixin({
        toast: true,
        position: "top-end",
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true,
      });
    }

    return () => document.removeEventListener("click", handleGlobalClick);
  }, [uploadImage]);

  const ActiveComponent = effectiveTabs.find((t) => t.id === effectiveTab)?.component;

  if (effectiveTabs.length === 0) {
    return (
      <div className="flex flex-col p-6 bg-white rounded-md border border-gray-200">
        <p className="text-gray-600">
          No image sources enabled. Enable at least one source in{" "}
          <a href={typeof AI_IMAGE_AdminConfig !== "undefined" ? AI_IMAGE_AdminConfig.settings_url : "#"} className="text-gray-800 hover:underline">
            Dashboard → Image sources
          </a>
          .
        </p>
      </div>
    );
  }

  const activeMeta = PROVIDER_META[effectiveTab] || {};

  return (
    <div className="flex flex-col gap-0 min-h-[calc(100vh-5rem)]" role="region" aria-label="Image generator">
      {/* Header card */}
      <div className="bg-white rounded-xl border border-gray-100 overflow-hidden mb-6">
        {/* Branding row */}
        <div className="flex items-center gap-2.5 px-6 py-4 border-b border-gray-100 ai-image-branding">
            <svg class="w-8 h-8" xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100" fill="none"><path d="M0 50C0 13.64 13.64 0 50 0C86.36 0 100 13.64 100 50C100 86.36 86.36 100 50 100C13.64 100 0 86.36 0 50Z" fill="#131D29"></path><path d="M36.5401 48.6601C39.9801 48.6601 42.7701 45.8501 42.7601 42.4101C42.7601 38.9701 39.9501 36.1801 36.5101 36.1901L36.4301 36.1401C33.0101 36.1901 30.2701 38.9901 30.2901 42.4101V42.4401C30.2901 45.8801 33.1001 48.6701 36.5401 48.6601Z" fill="white"></path><path d="M33.9801 60.9101C33.9101 60.7801 33.8401 60.6601 33.7601 60.5301C31.9301 57.5801 28.0501 56.6701 25.1001 58.5001C22.1501 60.3301 21.2401 64.2101 23.0701 67.1601L25.0901 70.7201C25.0901 70.7201 25.0901 70.7201 25.0901 70.7301C26.8101 73.7301 30.6501 74.7701 33.6501 73.0501C33.6701 73.0401 33.6901 73.0301 33.7101 73.0101C36.7101 71.2601 37.7201 67.4101 35.9801 64.4101L33.9601 60.9001L33.9801 60.9101Z" fill="white"></path><path d="M50.2001 52.7201C48.3801 50.1801 44.9601 49.3601 42.1901 50.8101C39.1101 52.4101 37.9101 56.2101 39.5201 59.2901L46.5801 70.6601C48.4101 73.6101 52.2801 74.5201 55.2301 72.7001C58.1401 70.8801 59.0501 67.0501 57.2701 64.1201L50.2101 52.7301L50.2001 52.7201Z" fill="white"></path><path d="M68.0903 46.2301L55.1203 24.6801C55.1203 24.6801 55.0903 24.6301 55.0803 24.6101C53.2703 21.6601 49.4103 20.7401 46.4603 22.5501C43.5003 24.3401 42.5403 28.2001 44.3303 31.1701L57.3403 52.7301V52.8001C59.1503 55.7701 63.0303 56.7101 66.0003 54.8901C68.9703 53.0801 69.9103 49.2001 68.0903 46.2301Z" fill="white"></path><path d="M72.9099 73.7301C76.3562 73.7301 79.1499 70.9364 79.1499 67.4901C79.1499 64.0439 76.3562 61.2501 72.9099 61.2501C69.4637 61.2501 66.6699 64.0439 66.6699 67.4901C66.6699 70.9364 69.4637 73.7301 72.9099 73.7301Z" fill="white"></path></svg>
          <div className="flex items-baseline gap-2 min-w-0">
            <span className="text-base font-semibold text-gray-900 truncate">Instant Image Generator</span>
            <span className="text-[13px] text-gray-400 shrink-0">v{typeof AI_IMAGE_AdminConfig !== "undefined" ? AI_IMAGE_AdminConfig.version : "1.5.11"}</span>
          </div>
        </div>

        {/* Tabs */}
        <div
          role="tablist"
          aria-label="Image sources"
          className="flex border-b border-gray-100 overflow-x-auto scrollbar-thin scrollbar-thumb-gray-200 scrollbar-track-gray-50 gap-6 px-6"
          style={{ WebkitOverflowScrolling: "touch" }}
        >
          {effectiveTabs.map((tab) => {
            const meta = PROVIDER_META[tab.id] || {};
            const Icon = meta.icon;
            const isActive = effectiveTab === tab.id;
            return (
              <button
                key={tab.id}
                type="button"
                role="tab"
                aria-selected={isActive}
                aria-controls={`panel-${tab.id}`}
                id={`tab-${tab.id}`}
                onClick={() => !isGenerating && setActiveTab(tab.id)}
                disabled={isGenerating}
                className={`flex items-center gap-2 font-medium px-0 py-4 text-xs sm:text-sm min-w-0 shrink-0 border-b-2 transition-colors ${
                  isActive
                    ? "text-gray-900 border-gray-800 bg-white"
                    : "text-gray-500 border-transparent hover:text-gray-700 hover:bg-gray-50/50"
                } ${isGenerating ? "opacity-50 cursor-not-allowed" : "cursor-pointer"}`}
              >
                {Icon && <Icon className="w-4 h-4 shrink-0" />}
                <span className="truncate whitespace-nowrap">{tab.label}</span>
                {(tab.badge || meta.badge) && (
                  <span className="px-1.5 py-0.5 text-[10px] font-medium rounded bg-amber-100 text-amber-800 shrink-0">
                    {tab.badge || meta.badge}
                  </span>
                )}
              </button>
            );
          })}
        </div>

        {/* Controls */}
        <div className="">
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-3 px-6 py-4">
            {effectiveTab !== "gemini" && effectiveTab !== "openai" && (
              <div className="flex flex-wrap items-center gap-2">
                <ViewToggle />
                <button
                  type="button"
                  onClick={() => setSelectionMode(!selectionMode)}
                  className={`rounded-md border px-3 sm:px-4 h-9 text-xs sm:text-sm font-medium transition-colors ${
                    selectionMode
                      ? "border-gray-800 bg-gray-800 text-white hover:bg-gray-900"
                      : "border-gray-200 bg-white text-gray-700 hover:bg-gray-50 hover:border-gray-300"
                  }`}
                  aria-pressed={selectionMode}
                >
                  <div className="flex items-center gap-1.5 sm:gap-2">
                    <svg className="w-3.5 h-3.5 sm:w-4 sm:h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <span className="hidden sm:inline">{selectionMode ? "Cancel Selection" : "Select"}</span>
                    <span className="sm:hidden">{selectionMode ? "Cancel" : "Select"}</span>
                  </div>
                </button>
                {selectionMode && (
                  <button
                    type="button"
                    onClick={() => {
                      const event = new CustomEvent("bulkSelectAll", { detail: { providerId: effectiveTab } });
                      window.dispatchEvent(event);
                    }}
                    className="rounded-md border border-gray-300 bg-white px-3 sm:px-4 h-9 text-xs sm:text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
                  >
                    <div className="flex items-center gap-1.5 sm:gap-2">
                      <svg className="w-3.5 h-3.5 sm:w-4 sm:h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
                      </svg>
                      <span className="hidden sm:inline">Select All</span>
                      <span className="sm:hidden">All</span>
                    </div>
                  </button>
                )}
              </div>
            )}
            <div className="w-full lg:w-auto overflow-x-auto">
              <FilterBar providerId={effectiveTab} />
            </div>
          </div>

          {effectiveTab !== "gemini" && effectiveTab !== "openai" && (
            <SelectionToolbar providerId={effectiveTab} inline={true} />
          )}

          {/* {activeMeta.description && (
            <div className="p-6 border-t border-gray-100">
              <p className="text-xs text-gray-500 flex items-center gap-2 leading-relaxed">
                <span className="flex items-center justify-center w-5 h-5 rounded-full bg-gray-100 text-gray-400 shrink-0" aria-hidden>
                  <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                </span>
                {activeMeta.description}
              </p>
            </div>
          )} */}
        </div>
      </div>

      <div
        
        role="tabpanel"
        id={`panel-${effectiveTab}`}
        aria-labelledby={`tab-${effectiveTab}`}
        aria-describedby="tab-description"
        className="p-6 bg-white rounded-xl border border-gray-100"
      >
        {ActiveComponent && <ActiveComponent />}
      </div>

      <ImagePreviewModal />
    </div>
  );
}
