import React, { memo, useState, useEffect, useRef } from "react";
import Author from "./Author";
import ImportButton from "./ImportButton";
import DownloadDropdown from "./DownloadDropdown";
import PreviewButton from "./PreviewButton";
import { useGenerator } from "../../context/GeneratorContext";

const EyeIcon = ({ 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="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
    <path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
  </svg>
);

const HeartIcon = ({ filled, className = "w-5 h-5" }) => (
  <svg className={className} fill={filled ? "currentColor" : "none"} viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
    <path strokeLinecap="round" strokeLinejoin="round" 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>
);

function ImageCard({
  imageSrc,
  imageAlt = "Image",
  previewUrl,
  author = {},
  importUrl,
  downloadOptions = [],
  loading = "lazy",
  providerId,
  imageId,
  imageData = {},
  providerBadge,
  variant = "grid",
  index = 0,
  gifStillUrl, // Still version of GIF (for Giphy)
  gifAnimatedUrl, // Animated version of GIF (for Giphy)
}) {
  const { url: authorUrl, avatar, name } = author;
  const generator = useGenerator();
  const selectionMode = generator?.selectionMode ?? false;
  const isSelected = generator?.isSelected(providerId, imageId) ?? false;
  const isFavorite = generator?.isFavorite(providerId, imageId) ?? false;
  const toggleSelection = generator?.toggleSelection;
  const toggleFavorite = generator?.toggleFavorite;
  const setPreviewImage = generator?.setPreviewImage;
  
  const [imageLoaded, setImageLoaded] = useState(false);
  const [imageError, setImageError] = useState(false);
  const [isHovered, setIsHovered] = useState(false);
  
  // Determine which image source to use (animated on hover for GIFs, otherwise normal)
  const currentImageSrc = (gifStillUrl && gifAnimatedUrl) 
    ? (isHovered ? gifAnimatedUrl : gifStillUrl)
    : imageSrc;

  const previewImageList = generator?.previewImageList;
  const setPreviewImageList = generator?.setPreviewImageList;

  // Register this card's data in the preview list on mount/update
  const cardData = useRef(null);
  cardData.current = { imageSrc, imageAlt, previewUrl, author, importUrl, downloadOptions, providerId, imageId, gifStillUrl, gifAnimatedUrl, providerBadge, index };

  useEffect(() => {
    const handleNav = (e) => {
      const { direction, currentIndex } = e.detail;
      const list = generator?.previewImageList;
      if (!list || list.length === 0) return;
      let nextIdx;
      if (direction === "next") nextIdx = currentIndex + 1 >= list.length ? 0 : currentIndex + 1;
      else nextIdx = currentIndex - 1 < 0 ? list.length - 1 : currentIndex - 1;
      const nextImage = list[nextIdx];
      if (nextImage && generator?.setPreviewImage) generator.setPreviewImage({ ...nextImage, index: nextIdx });
    };
    window.addEventListener("previewNavigate", handleNav);
    return () => window.removeEventListener("previewNavigate", handleNav);
  }, [generator]);

  const handleQuickPreview = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (!setPreviewImage) return;
    // Use data from previewImageList (which has full-size URLs) if available
    const list = generator?.previewImageList;
    if (list && list.length > 0 && index != null) {
      const listItem = list[index];
      if (listItem) {
        setPreviewImage({ ...listItem, index });
        return;
      }
    }
    // Fallback to card props
    setPreviewImage({ imageSrc, imageAlt, previewUrl, author, importUrl, downloadOptions, providerId, imageId, gifStillUrl, gifAnimatedUrl, providerBadge, index });
  };

  const handleFavorite = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (toggleFavorite) toggleFavorite(providerId, imageId, { imageSrc, imageAlt, author, importUrl, downloadOptions, previewUrl });
  };

  const handleToggleSelect = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (toggleSelection) toggleSelection(providerId, imageId, { importUrl, imageSrc, imageAlt, author, previewUrl });
  };

  const thumbnail = (
    <div 
      className="relative overflow-hidden rounded-xl bg-gray-100"
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {/* Loading Skeleton */}
      {!imageLoaded && !imageError && (
        <div className="absolute inset-0 animate-pulse bg-gradient-to-r from-gray-200 via-gray-300 to-gray-200 bg-[length:200%_100%]" style={{ animation: 'shimmer 1.5s infinite' }} />
      )}
      
      {/* Actual Image */}
      <img
        src={currentImageSrc}
        alt={imageAlt}
        loading={loading}
        onLoad={() => setImageLoaded(true)}
        onError={() => setImageError(true)}
        className={`w-full h-full object-cover rounded-xl transition-all duration-500 group-hover:scale-105 ${
          imageLoaded ? 'opacity-100' : 'opacity-0'
        }`}
      />
      
      {/* Error State */}
      {imageError && (
        <div className="absolute inset-0 flex items-center justify-center bg-gray-100">
          <svg className="w-12 h-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 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>
        </div>
      )}
      
      {/* GIF Badge - show when it's an animated GIF */}
      {gifStillUrl && gifAnimatedUrl && (
        <div className="absolute bottom-3 left-3 z-10">
          <span className="inline-flex items-center gap-1 px-2 py-1 rounded-md bg-black/80 text-white text-xs font-semibold shadow-sm">
            <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
              <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>
            GIF
          </span>
        </div>
      )}
      
      <div className="absolute inset-0 rounded-xl opacity-0 group-hover:opacity-100 transition-opacity duration-300 bg-black/40" />
      {setPreviewImage && (
        <button
          type="button"
          onClick={handleQuickPreview}
          className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 scale-75 opacity-0 transition-all duration-300 ease-out group-hover:opacity-100 group-hover:scale-100 flex items-center justify-center w-12 h-12 rounded-full bg-white/95 text-gray-800 border-0 cursor-pointer hover:bg-white shadow-lg z-20 focus:outline-none focus:ring-2 focus:ring-gray-600"
          aria-label="Quick preview"
        >
          <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
            <path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
          </svg>
        </button>
      )}
      {selectionMode && toggleSelection && providerId != null && imageId != null && (
        <button
          type="button"
          onClick={handleToggleSelect}
          className="absolute top-3 left-3 z-10 flex h-8 w-8 items-center justify-center rounded-md border-2 bg-white/90 shadow-sm transition-transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-gray-600"
          aria-label={isSelected ? "Deselect" : "Select"}
          aria-checked={isSelected}
        >
          {isSelected ? (
            <svg className="w-5 h-5 text-gray-800" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
            </svg>
          ) : (
            <span className="block h-4 w-4 rounded border-2 border-gray-400" />
          )}
        </button>
      )}
      {toggleFavorite && providerId != null && imageId != null && (
        <button
          type="button"
          onClick={handleFavorite}
          className={`absolute top-3 right-3 z-10 flex h-8 w-8 items-center justify-center rounded-md bg-white/90 shadow-sm transition-all hover:scale-105 focus:outline-none focus:ring-2 focus:ring-gray-600 ${isFavorite ? "text-red-500" : "text-gray-500 hover:text-red-400"}`}
          aria-label={isFavorite ? "Remove from favorites" : "Add to favorites"}
        >
          <HeartIcon filled={isFavorite} className="w-5 h-5" />
        </button>
      )}
      {providerBadge && !selectionMode && (
        <span className="absolute top-3 left-3 z-10 rounded-full bg-black/70 px-2.5 py-1 text-xs font-semibold text-white shadow-sm">
          {providerBadge}
        </span>
      )}
    </div>
  );

  if (variant === "list") {
    return (
      <div
        role="listitem"
        className={`flex items-center gap-3 rounded-md border bg-white py-2.5 px-3 transition-colors group ${
          isSelected ? "border-gray-800 ring-1 ring-gray-800/20" : "border-gray-100 hover:border-gray-200 hover:bg-gray-50/50"
        }`}
      >
        {selectionMode && toggleSelection && providerId != null && imageId != null && (
          <button
            type="button"
            onClick={handleToggleSelect}
            className="flex h-5 w-5 shrink-0 items-center justify-center rounded border border-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-400"
            aria-checked={isSelected}
          >
            {isSelected ? (
              <svg className="w-3 h-3 text-gray-800" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
              </svg>
            ) : null}
          </button>
        )}
        <div className="h-14 w-20 shrink-0 overflow-hidden rounded bg-gray-100">
          <img src={imageSrc} alt={imageAlt} loading={loading} className="h-full w-full object-cover" />
        </div>
        <div className="min-w-0 flex-1">
          <p className="truncate text-sm font-medium text-gray-800">{imageAlt}</p>
          <Author url={authorUrl} avatar={avatar} name={name || "—"} variant="list" />
        </div>
        <div className="flex items-center gap-1 shrink-0">
          {setPreviewImage && (
            <button type="button" onClick={handleQuickPreview} className="p-1.5 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-100 transition-colors" aria-label="Quick preview">
              <EyeIcon className="w-4 h-4" />
            </button>
          )}
          {toggleFavorite && providerId != null && imageId != null && (
            <button
              type="button"
              onClick={handleFavorite}
              className={`p-1.5 rounded transition-colors ${isFavorite ? "text-red-500 hover:bg-red-50" : "text-gray-400 hover:text-red-400 hover:bg-gray-100"}`}
              aria-label={isFavorite ? "Remove from favorites" : "Add to favorites"}
            >
              <HeartIcon filled={isFavorite} className="w-4 h-4" />
            </button>
          )}
          {importUrl && <ImportButton url={importUrl} title={imageAlt} author={name} />}
          {downloadOptions.length > 0 && <DownloadDropdown options={downloadOptions} title={imageAlt} author={name} />}
        </div>
      </div>
    );
  }

  return (
    <div
      className={`relative p-0 bg-white border border-gray-200 rounded-xl mb-6 break-inside-avoid transition-all duration-300 ease-in-out group hover:shadow-lg ${isSelected ? "ring-2 ring-gray-600" : ""}`}
      role="listitem"
    >
      {thumbnail}
      {/* Action bar is outside overflow-hidden so the dropdown popup is never clipped */}
      <div className="absolute bottom-0 left-0 right-0 p-3 pb-4 opacity-0 translate-y-2 group-hover:opacity-100 group-hover:translate-y-0 transition-all duration-200 ease-out bg-gradient-to-t from-black/60 via-black/40 to-transparent pointer-events-none z-30 rounded-b-xl">
        <div className="flex items-end justify-between gap-2 pointer-events-auto">
          <div className="min-w-0 flex-1">
            <Author url={authorUrl} avatar={avatar} name={name || "—"} />
          </div>
          <div className="flex items-center gap-1.5 shrink-0">
            {importUrl && <ImportButton url={importUrl} title={imageAlt} author={name} />}
            {downloadOptions.length > 0 && <DownloadDropdown options={downloadOptions} title={imageAlt} author={name} />}
          </div>
        </div>
      </div>
    </div>
  );
}

export default memo(ImageCard);
