import React, { useEffect, useCallback, memo } from "react";
import Author from "./Author";
import { useGenerator } from "../../context/GeneratorContext";

const DownloadIcon = () => (
  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M4 15v2a3 3 0 003 3h10a3 3 0 003-3v-2m-8 1V4m0 12-4-4m4 4 4-4" />
  </svg>
);

function ImagePreviewModal() {
  const { previewImage, setPreviewImage, toggleFavorite, isFavorite } = useGenerator();

  const close = useCallback(() => {
    setPreviewImage(null);
  }, [setPreviewImage]);

  // Navigation via custom event
  const navigate = useCallback((direction) => {
    if (!previewImage) return;
    const event = new CustomEvent("previewNavigate", { detail: { direction, currentIndex: previewImage.index } });
    window.dispatchEvent(event);
  }, [previewImage]);

  useEffect(() => {
    const handleKeyDown = (e) => {
      if (e.key === "Escape") close();
      if (e.key === "ArrowLeft") navigate("prev");
      if (e.key === "ArrowRight") navigate("next");
    };
    if (previewImage) {
      window.addEventListener("keydown", handleKeyDown);
      document.body.style.overflow = "hidden";
    }
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
      document.body.style.overflow = "";
    };
  }, [previewImage, close, navigate]);

  if (!previewImage) return null;

  const {
    imageSrc,
    imageAlt = "Image",
    previewUrl,
    author = {},
    importUrl,
    downloadOptions = [],
    providerId,
    imageId,
    providerBadge,
    gifAnimatedUrl,
  } = previewImage;

  // Use the full original image for the modal (imageSrc is already original URL)
  const displayImageSrc = imageSrc || gifAnimatedUrl;

  const handleBackdropClick = (e) => {
    if (e.target === e.currentTarget) close();
  };

  const handleFavorite = () => {
    if (providerId && imageId) toggleFavorite(providerId, imageId, { imageSrc, imageAlt, author, importUrl, previewUrl });
  };

  const fav = providerId && imageId && isFavorite(providerId, imageId);

  return (
    <div
      className="fixed inset-0 flex items-center justify-center bg-black/80"
      style={{ zIndex: 999999 }}
      onClick={handleBackdropClick}
      role="dialog"
      aria-modal="true"
      aria-label="Image preview"
    >
      <div className="relative flex max-h-[95vh] w-full max-w-7xl mx-4 sm:mx-6 flex-col md:flex-row overflow-hidden rounded-xl bg-white">
        <button
          type="button"
          onClick={close}
          className="absolute top-3 right-3 md:hidden flex h-9 w-9 items-center justify-center rounded-full bg-black/40 text-white hover:bg-black/60 focus:outline-none transition-colors z-10"
          aria-label="Close"
        >
          <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>

        <div className="relative flex flex-1 items-center justify-center overflow-hidden bg-gray-50 min-h-[280px] md:min-h-[500px]">
          <img
            src={displayImageSrc}
            alt={imageAlt}
            className="max-h-[55vh] md:max-h-[90vh] w-auto max-w-full object-contain"
          />
          <button
            type="button"
            onClick={(e) => { e.stopPropagation(); navigate("prev"); }}
            className="absolute left-2 top-1/2 -translate-y-1/2 flex h-9 w-9 items-center justify-center rounded-full border border-white/20 bg-black/30 text-white hover:bg-black/50 focus:outline-none transition-colors"
            aria-label="Previous image"
          >
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
            </svg>
          </button>
          <button
            type="button"
            onClick={(e) => { e.stopPropagation(); navigate("next"); }}
            className="absolute right-2 top-1/2 -translate-y-1/2 flex h-9 w-9 items-center justify-center rounded-full border border-white/20 bg-black/30 text-white hover:bg-black/50 focus:outline-none transition-colors"
            aria-label="Next image"
          >
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
            </svg>
          </button>
        </div>

        <div className="flex w-full md:w-[280px] lg:w-[320px] shrink-0 flex-col border-t md:border-t-0 md:border-l border-gray-100 bg-white max-h-[40vh] md:max-h-none overflow-y-auto">
          <div className="hidden md:flex items-center justify-end px-4 pt-3">
            <button
              type="button"
              onClick={close}
              className="flex h-8 w-8 items-center justify-center rounded-full border border-gray-200 bg-gray-50 text-gray-500 hover:bg-gray-100 hover:text-gray-700 focus:outline-none transition-colors"
              aria-label="Close"
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          <div className="px-4 pt-2 md:pt-0 pb-3 border-b border-gray-100">
            <div className="flex flex-wrap items-center gap-1.5 mb-2">
              {providerBadge && (
                <span className="inline-flex items-center rounded bg-gray-100 px-2 py-0.5 text-[11px] font-medium text-gray-700">
                  {providerBadge}
                </span>
              )}
              {gifAnimatedUrl && (
                <span className="inline-flex items-center gap-1 rounded bg-gray-100 px-2 py-0.5 text-[11px] font-medium text-gray-700">
                  <svg className="w-3 h-3" 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>
                  GIF
                </span>
              )}
            </div>
            <h2 className="text-sm font-semibold text-gray-900 leading-snug line-clamp-3">{imageAlt}</h2>
          </div>

          <div className="px-4 py-3 border-b border-gray-100">
            <p className="text-[10px] font-medium text-gray-400 uppercase tracking-wider mb-2">Author</p>
            <Author
              url={author?.url}
              avatar={author?.avatar}
              name={author?.name || "—"}
              variant="list"
            />
          </div>

          <div className="px-4 py-3 mt-auto">
            <p className="text-[10px] font-medium text-gray-400 uppercase tracking-wider mb-2">Actions</p>
            <div className="flex flex-col gap-2">
              {importUrl && (
                <button
                  type="button"
                  className="bdt-aimg-download-btn flex items-center justify-center gap-2 w-full h-9 rounded-md border border-gray-800 bg-gray-800 text-white text-sm font-medium hover:bg-gray-900 transition-colors"
                  data-url={importUrl}
                  data-title={imageAlt || ""}
                  data-author={author?.name || ""}
                >
                  <DownloadIcon />
                  Import to Media Library
                </button>
              )}

              {downloadOptions?.map((opt) => (
                <button
                  key={opt.label}
                  type="button"
                  className="bdt-aimg-download-btn flex items-center justify-center gap-2 w-full h-9 rounded-md border border-gray-200 bg-white text-gray-700 text-sm font-medium hover:bg-gray-50 transition-colors"
                  data-url={opt.url}
                  data-type={opt.type}
                  data-title={imageAlt || ""}
                  data-author={author?.name || ""}
                >
                  <DownloadIcon />
                  Import {opt.label}
                </button>
              ))}

              {providerId && imageId && (
                <button
                  type="button"
                  onClick={handleFavorite}
                  className={`flex items-center justify-center gap-2 w-full h-9 rounded-md border text-sm font-medium transition-colors ${
                    fav
                      ? "border-red-200 bg-red-50 text-red-600 hover:bg-red-100"
                      : "border-gray-200 bg-white text-gray-700 hover:bg-gray-50"
                  }`}
                >
                  <svg className="w-4 h-4" fill={fav ? "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>
                  {fav ? "Favorited" : "Add to Favorites"}
                </button>
              )}

              {previewUrl && (
                <a
                  href={previewUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center justify-center gap-2 w-full h-9 rounded-md border border-gray-800 bg-gray-800 text-sm font-medium text-white hover:bg-gray-900 transition-colors"
                >
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                  </svg>
                  View Original
                </a>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default memo(ImagePreviewModal);
