import { useRef, useEffect, useState, useCallback, memo } from "react";
import { Tab, TabList, TabPanel, Tabs } from "react-tabs";
import "react-tabs/style/react-tabs.css";
import { clsx } from "clsx";

import { availableModes } from "@/types/wallpaperModes";
import { RandomModePanel } from "@/ui/components/ModePanels/RandomModePanel";
import { CustomModePanel } from "@/ui/components/ModePanels/CustomModePanel";
import { LocationModePanel } from "@/ui/components/ModePanels/LocationModePanel";
import { MoodModePanel } from "@/ui/components/ModePanels/MoodModePanel";
import { useCurrentWallpaperMode } from "ui/hooks/useCurrentWallpaperMode";
import { useLicense } from "@/ui/hooks/useLicense";
import { FaLock, FaCrown } from "react-icons/fa6";

// Re-import UpgradeModal
import { UpgradeModal } from "../components/UpgradeModal";

// Define which modes are premium
const PREMIUM_MODES = ["CustomStyle", "Location", "Mood"];

const ModeButton = memo(function ModeButton({
  mode,
  index,
  selectedTabIndex,
  onSelect,
  isLocked,
  needsApiKey,
}: {
  mode: (typeof availableModes)[0];
  index: number;
  selectedTabIndex: number;
  onSelect: (index: number) => void;
  isLocked: boolean;
  needsApiKey: boolean;
}) {
  return (
    <div
      key={mode.id}
      onClick={() => onSelect(index)}
      onKeyDown={(e) => {
        if (e.key === "Enter" || e.key === " ") {
          onSelect(index);
        }
      }}
      className={clsx(
        "relative overflow-hidden cursor-pointer rounded-md p-3 transition-all duration-300",
        "border-2 flex items-center",
        (isLocked || needsApiKey) && "opacity-70",
        index === selectedTabIndex
          ? "border-purple-500 shadow-[0_0_10px_rgba(147,51,234,0.5)]"
          : "border-gray-700 hover:border-purple-400/50",
      )}
      role='radio'
      aria-checked={index === selectedTabIndex}
      tabIndex={0}
      aria-label={`${mode.name} mode: ${mode.description}${isLocked ? " (Premium)" : needsApiKey ? " (API Key Required)" : ""}`}
    >
      <div
        className={clsx(
          "absolute inset-0 bg-gradient-to-r from-gray-800 via-gray-700 to-gray-800",
          "opacity-30 z-0",
          index === selectedTabIndex ? "animate-gradient-x" : "",
        )}
        aria-hidden='true'
      />

      {/* Premium badge for locked modes */}
      {isLocked && (
        <div className='absolute top-1 right-1 z-20'>
          <FaCrown className='text-yellow-400' size={12} />
        </div>
      )}

      {/* API Key badge for premium users without API key */}
      {needsApiKey && (
        <div className='absolute top-1 right-1 z-20'>
          <div className='bg-purple-500 text-white text-xs px-1 py-0.5 rounded text-[8px] font-bold'>API</div>
        </div>
      )}

      {/* Lock icon for locked modes */}
      {isLocked && (
        <div className='absolute top-1 left-1 z-20'>
          <div className='flex items-center justify-center w-4 h-4 bg-amber-500 rounded-full'>
            <FaLock className='text-black' size={8} />
          </div>
        </div>
      )}

      {/* Key icon for API key required modes */}
      {needsApiKey && (
        <div className='absolute top-1 left-1 z-20'>
          <div className='flex items-center justify-center w-4 h-4 bg-purple-500 rounded-full'>
            <div className='text-white text-[8px]'>🔑</div>
          </div>
        </div>
      )}

      <div className='flex items-center gap-2 relative z-10'>
        <span
          className={clsx(
            "p-1.5 rounded-full text-white flex items-center justify-center",
            index === selectedTabIndex ? "bg-purple-600" : "bg-gray-700",
            (isLocked || needsApiKey) && "opacity-70",
          )}
        >
          {mode.icon}
        </span>
        <div>
          <h3 className={clsx("text-white text-xs font-medium", (isLocked || needsApiKey) && "opacity-70")}>
            {mode.name}
            {isLocked && <span className='text-yellow-400 ml-1'>🔒</span>}
            {needsApiKey && <span className='text-purple-400 ml-1'>🔑</span>}
          </h3>
        </div>
      </div>
    </div>
  );
});

const ModesPage = memo(function ModesPage() {
  const { currentMode: currentModeId, setCurrentMode } = useCurrentWallpaperMode();
  const { isPremium } = useLicense();
  const [selectedTabIndex, setSelectedTabIndex] = useState(0);
  const [upgradeModalOpen, setUpgradeModalOpen] = useState(false);
  const [lockedModeClicked, setLockedModeClicked] = useState<string | null>(null);
  const scrollContainerRef = useRef<HTMLDivElement>(null);

  // TODO: Add API key check - for now assuming no API key
  const hasApiKey = false;

  useEffect(() => {
    const modeIndex = availableModes.findIndex((mode) => mode.id === currentModeId);
    if (modeIndex !== -1) {
      setSelectedTabIndex(modeIndex);
    }
  }, [currentModeId]);

  const handleModeSelection = useCallback(
    (index: number) => {
      const selectedMode = availableModes[index];

      // Check if the mode is locked for free users
      if (!isPremium && PREMIUM_MODES.includes(selectedMode.id)) {
        setLockedModeClicked(selectedMode.name);
        setUpgradeModalOpen(true);
        return;
      }

      // Check if the mode requires API key (for premium users)
      if (isPremium && PREMIUM_MODES.includes(selectedMode.id) && !hasApiKey) {
        // TODO: Show API key setup modal/toast
        console.log(`${selectedMode.name} mode requires API key`);
        return;
      }

      setSelectedTabIndex(index);
      setCurrentMode(availableModes[index].id);
    },
    [setCurrentMode, isPremium, hasApiKey],
  );

  const handleTabSelect = useCallback(
    (index: number) => {
      const selectedMode = availableModes[index];

      // Prevent tab selection for locked modes
      if (!isPremium && PREMIUM_MODES.includes(selectedMode.id)) {
        return;
      }

      // Prevent tab selection for premium users without API key
      if (isPremium && PREMIUM_MODES.includes(selectedMode.id) && !hasApiKey) {
        return;
      }

      setSelectedTabIndex(index);
      setCurrentMode(availableModes[index].id);
    },
    [setCurrentMode, isPremium, hasApiKey],
  );

  return (
    <section className='size-full flex flex-col py-2 px-4 bg-gray-900 overflow-y-auto' ref={scrollContainerRef}>
      <div className='flex justify-between items-center mb-2'>
        <h1 className='text-xl text-white font-medium'>Modes</h1>
      </div>

      <div className='mb-4'>
        <div className='grid grid-cols-2 gap-2' role='radiogroup' aria-label='Select wallpaper generation mode'>
          {availableModes.map((mode, index) => (
            <ModeButton
              key={mode.id}
              mode={mode}
              index={index}
              selectedTabIndex={selectedTabIndex}
              onSelect={handleModeSelection}
              isLocked={!isPremium && PREMIUM_MODES.includes(mode.id)}
              needsApiKey={isPremium && PREMIUM_MODES.includes(mode.id) && !hasApiKey}
            />
          ))}
        </div>
      </div>

      <Tabs selectedIndex={selectedTabIndex} onSelect={handleTabSelect} className='mb-2'>
        <TabList className='hidden'>
          {availableModes.map((mode) => (
            <Tab key={mode.id}>{mode.name}</Tab>
          ))}
        </TabList>
        <TabPanel>
          <RandomModePanel />
        </TabPanel>
        <TabPanel>
          {!isPremium ? (
            <div className='bg-gray-800 p-4 rounded-md text-center'>
              <FaLock className='mx-auto text-amber-400 mb-2' size={24} />
              <h3 className='text-white font-medium mb-2'>Premium Feature</h3>
              <p className='text-gray-400 text-sm mb-3'>
                Custom Style mode allows you to generate wallpapers using your own style prompts.
              </p>
              <button
                onClick={() => setUpgradeModalOpen(true)}
                className='px-4 py-2 bg-amber-600 hover:bg-amber-700 text-white rounded-lg text-sm transition-colors'
              >
                Upgrade to Premium
              </button>
            </div>
          ) : !hasApiKey ? (
            <div className='bg-gray-800 p-4 rounded-md text-center'>
              <div className='text-purple-400 mb-2 text-3xl'>🔑</div>
              <h3 className='text-white font-medium mb-2'>API Key Required</h3>
              <p className='text-gray-400 text-sm mb-3'>
                You have premium access! Now add your Replicate API key to use Custom Style mode with unlimited
                generations.
              </p>
              <button className='px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg text-sm transition-colors'>
                Set Up API Key
              </button>
            </div>
          ) : (
            <CustomModePanel />
          )}
        </TabPanel>
        <TabPanel>
          {!isPremium ? (
            <div className='bg-gray-800 p-4 rounded-md text-center'>
              <FaLock className='mx-auto text-amber-400 mb-2' size={24} />
              <h3 className='text-white font-medium mb-2'>Premium Feature</h3>
              <p className='text-gray-400 text-sm mb-3'>
                Location mode generates wallpapers based on your location, time, and weather.
              </p>
              <button
                onClick={() => setUpgradeModalOpen(true)}
                className='px-4 py-2 bg-amber-600 hover:bg-amber-700 text-white rounded-lg text-sm transition-colors'
              >
                Upgrade to Premium
              </button>
            </div>
          ) : !hasApiKey ? (
            <div className='bg-gray-800 p-4 rounded-md text-center'>
              <div className='text-purple-400 mb-2 text-3xl'>🔑</div>
              <h3 className='text-white font-medium mb-2'>API Key Required</h3>
              <p className='text-gray-400 text-sm mb-3'>
                You have premium access! Now add your Replicate API key to use Location mode with your own location
                data.
              </p>
              <button className='px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg text-sm transition-colors'>
                Set Up API Key
              </button>
            </div>
          ) : (
            <LocationModePanel />
          )}
        </TabPanel>
        <TabPanel>
          {!isPremium ? (
            <div className='bg-gray-800 p-4 rounded-md text-center'>
              <FaLock className='mx-auto text-amber-400 mb-2' size={24} />
              <h3 className='text-white font-medium mb-2'>Premium Feature</h3>
              <p className='text-gray-400 text-sm mb-3'>
                Mood mode generates wallpapers based on your selected mood or desired feeling.
              </p>
              <button
                onClick={() => setUpgradeModalOpen(true)}
                className='px-4 py-2 bg-amber-600 hover:bg-amber-700 text-white rounded-lg text-sm transition-colors'
              >
                Upgrade to Premium
              </button>
            </div>
          ) : !hasApiKey ? (
            <div className='bg-gray-800 p-4 rounded-md text-center'>
              <div className='text-purple-400 mb-2 text-3xl'>🔑</div>
              <h3 className='text-white font-medium mb-2'>API Key Required</h3>
              <p className='text-gray-400 text-sm mb-3'>
                You have premium access! Now add your Replicate API key to use Mood mode with advanced AI processing.
              </p>
              <button className='px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg text-sm transition-colors'>
                Set Up API Key
              </button>
            </div>
          ) : (
            <MoodModePanel />
          )}
        </TabPanel>
      </Tabs>

      {/* Upgrade Modal */}
      <UpgradeModal
        isOpen={upgradeModalOpen}
        onClose={() => {
          setUpgradeModalOpen(false);
          setLockedModeClicked(null);
        }}
        lockedStyle={lockedModeClicked}
        message={lockedModeClicked ? `${lockedModeClicked} mode requires premium access` : undefined}
      />
    </section>
  );
});

export default ModesPage;
