import { useState } from "react";
import { WallpaperHistoryEntry, WallpaperData } from "@/types/wallpaper";
import { useWallpaperGeneration, useWallpaperHistory, useLastWallpaper } from "@/ui/hooks";
import { clsx } from "clsx";
import { FaShare } from "react-icons/fa6";
import { ShareModal } from "@/ui/components/ShareModal";

export default function HistoryPage() {
  const [processingWallpaper, setProcessingWallpaper] = useState<string | null>(null);
  const [shareModalOpen, setShareModalOpen] = useState(false);

  // Use the wallpaper generation hook - now with integrated status updates
  const { handleSetWallpaper, isUpscaling } = useWallpaperGeneration();

  // Use the wallpaper history hook
  const { wallpapers, error } = useWallpaperHistory();

  // Use the last wallpaper hook to set wallpaper for sharing
  const { setLastWallpaper } = useLastWallpaper();

  const handleSetHistoryWallpaper = async (wallpaper: WallpaperHistoryEntry) => {
    // Don't allow setting a new wallpaper if we're already upscaling another
    if (isUpscaling || processingWallpaper) return;

    try {
      setProcessingWallpaper(wallpaper.key);

      const wallpaperData: WallpaperData = {
        objectKey: wallpaper.key,
        originalImageUrl: wallpaper.originalImageUrl,
        upscaledImageUrl: wallpaper.upscaledImageUrl,
        // Prefer actual style from metadata, else Unknown
        style: wallpaper.metadata?.style || "Unknown",
        generatedAt: wallpaper.setAt || new Date().toISOString(),
        metadata: wallpaper.metadata,
      };

      // The hook's handleSetWallpaper will update the electron store history
      // and the IPC event listener will handle the refreshing on completion
      await handleSetWallpaper(wallpaperData);
    } catch (err) {
      console.error("Failed to set wallpaper:", err);
      // Refresh anyway in case of error
    } finally {
      setProcessingWallpaper(null);
    }
  };

  const handleShareWallpaper = (wallpaper: WallpaperHistoryEntry, event: React.MouseEvent) => {
    event.stopPropagation(); // Prevent triggering the set wallpaper action

    // Set the wallpaper data for sharing
    const wallpaperData: WallpaperData = {
      objectKey: wallpaper.key,
      originalImageUrl: wallpaper.originalImageUrl,
      upscaledImageUrl: wallpaper.upscaledImageUrl,
      style: wallpaper.metadata?.style || "Unknown",
      generatedAt: wallpaper.setAt || new Date().toISOString(),
      metadata: wallpaper.metadata,
    };

    setLastWallpaper(wallpaperData);
    setShareModalOpen(true);
  };

  const handleCloseShareModal = () => {
    setShareModalOpen(false);
  };

  if (error && wallpapers.length === 0) {
    return (
      <section className='size-full bg-gray-900 flex items-center justify-center'>
        <p className='text-white'>{error}</p>
      </section>
    );
  }

  return (
    <>
      <section id='historyPage' className='size-full bg-gray-900 py-2 px-4 flex flex-col gap-2'>
        <div className='flex justify-between items-center'>
          <h1 className='text-xl text-white font-medium'>History</h1>
        </div>
        <div id='wallpaperHistoryGrid' className='w-full overflow-auto grid grid-cols-3 gap-2'>
          {wallpapers.map((wallpaper, idx) => (
            <div
              key={wallpaper.key}
              className={clsx(
                isUpscaling || processingWallpaper ? "pointer-events-none opacity-50" : "",
                "h-32 history-item flex flex-col",
              )}
            >
              {wallpaper.originalImageUrl ? (
                <div className='flex flex-col h-full'>
                  {/* Image container */}
                  <div
                    className='relative flex-1 group cursor-pointer'
                    onClick={() => handleSetHistoryWallpaper(wallpaper)}
                    onKeyDown={(e) => {
                      if (e.key === "Enter" || e.key === " ") {
                        e.preventDefault();
                        handleSetHistoryWallpaper(wallpaper);
                      }
                    }}
                    role='button'
                    tabIndex={0}
                    aria-label={`Set wallpaper ${idx + 1} as current wallpaper`}
                  >
                    <img
                      src={wallpaper.originalImageUrl}
                      alt={`Wallpaper ${idx + 1}`}
                      className='w-full h-full object-cover rounded-t'
                    />
                    {wallpaper.setAt && (
                      <div className='absolute bottom-1 left-1 bg-black bg-opacity-50 text-white text-[9px] px-1 rounded'>
                        {new Date(wallpaper.setAt).toLocaleDateString()}
                      </div>
                    )}
                    {/* Overlay for set wallpaper action */}
                    <div className='absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-30 transition-all duration-200 flex items-center justify-center opacity-0 group-hover:opacity-100'>
                      <button
                        className='bg-purple-300 w-20 bg-opacity-30 text-white text-xs px-2 py-1 rounded cursor-pointer'
                        disabled={isUpscaling || processingWallpaper !== null}
                      >
                        {processingWallpaper === wallpaper.key || isUpscaling ? "Setting..." : "Set as wallpaper"}
                      </button>
                    </div>
                  </div>

                  {/* Share button below image */}
                  <button
                    onClick={(e) => handleShareWallpaper(wallpaper, e)}
                    className='w-full bg-gray-700 hover:bg-indigo-600 text-white text-xs py-1 rounded-b transition-colors flex items-center justify-center gap-1'
                    title='Share wallpaper'
                    disabled={isUpscaling || processingWallpaper !== null}
                  >
                    <FaShare size={10} />
                    Share
                  </button>
                </div>
              ) : (
                <div className='w-full h-full bg-gray-700 animate-pulse rounded'></div>
              )}
            </div>
          ))}

          {wallpapers.length === 0 && (
            <div className='col-span-3 text-center py-8 text-white'>No wallpapers found. Generate some first!</div>
          )}
        </div>
      </section>

      {/* Share Modal */}
      <ShareModal isOpen={shareModalOpen} onClose={handleCloseShareModal} />
    </>
  );
}
