import { useState, useEffect, useCallback, useRef, type MouseEvent } from "react";
import type { ImageResult } from "@/lib/api";
import { trackClick } from "@/lib/api";
import { X, ChevronLeft, ChevronRight, Bookmark, BookmarkCheck } from "lucide-react";

function formatSize(w: number, h: number): string {
  return `${w} × ${h}`;
}

interface ImageResultsProps {
  results: ImageResult[];
  query?: string;
  category?: string;
  bookmarkedUrls?: Set<string>;
  onToggleBookmark?: (result: ImageResult) => void;
}

export function ImageResults({ results, query = "", category = "images", bookmarkedUrls, onToggleBookmark }: ImageResultsProps) {
  const [selectedIndex, setSelectedIndex] = useState<number | null>(null);
  // Track detected dimensions per result index
  const [dims, setDims] = useState<Record<number, { w: number; h: number }>>({});
  // Track full-size image dimensions detected in lightbox
  const [fullDims, setFullDims] = useState<Record<number, { w: number; h: number }>>({});

  const selected = selectedIndex !== null ? results[selectedIndex] : null;

  // Reset dims when results change
  const prevResultsRef = useRef(results);
  useEffect(() => {
    if (prevResultsRef.current !== results) {
      setDims({});
      setFullDims({});
      prevResultsRef.current = results;
    }
  }, [results]);

  const handleThumbLoad = (i: number, el: HTMLImageElement) => {
    // Prefer backend-reported dimensions, fallback to natural size of thumbnail
    const r = results[i];
    if (r.width > 0 && r.height > 0) {
      setDims((prev) => ({ ...prev, [i]: { w: r.width, h: r.height } }));
    } else if (el.naturalWidth > 0 && el.naturalHeight > 0) {
      setDims((prev) => ({ ...prev, [i]: { w: el.naturalWidth, h: el.naturalHeight } }));
    }
  };

  const handleFullLoad = (el: HTMLImageElement) => {
    if (selectedIndex !== null && el.naturalWidth > 0 && el.naturalHeight > 0) {
      setFullDims((prev) => ({ ...prev, [selectedIndex]: { w: el.naturalWidth, h: el.naturalHeight } }));
    }
  };

  // Best known size for an image: full-size > backend > thumbnail
  const getSize = (i: number): { w: number; h: number } | null => {
    if (fullDims[i]) return fullDims[i];
    const r = results[i];
    if (r.width > 0 && r.height > 0) return { w: r.width, h: r.height };
    if (dims[i]) return dims[i];
    return null;
  };

  const goPrev = useCallback(() => {
    setSelectedIndex((i) => (i !== null && i > 0 ? i - 1 : i));
  }, []);

  const goNext = useCallback(() => {
    setSelectedIndex((i) => (i !== null && i < results.length - 1 ? i + 1 : i));
  }, [results.length]);

  const close = useCallback(() => setSelectedIndex(null), []);

  // Keyboard navigation
  useEffect(() => {
    if (selectedIndex === null) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "ArrowLeft") { e.preventDefault(); goPrev(); }
      else if (e.key === "ArrowRight") { e.preventDefault(); goNext(); }
      else if (e.key === "Escape") { close(); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [selectedIndex, goPrev, goNext, close]);

  // Open lightbox on click, but allow Cmd/Ctrl-click to open link natively
  const handleCardClick = (e: MouseEvent, i: number) => {
    if (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) return; // let browser handle
    e.preventDefault();
    setSelectedIndex(i);
  };

  if (results.length === 0) return null;

  return (
    <>
      {/* Masonry grid using CSS columns */}
      <div className="columns-2 gap-3 sm:columns-3 md:columns-4 lg:columns-5" role="list">
        {results.map((img, i) => (
          <a
            key={`${img.img_src}-${i}`}
            href={img.url}
            target="_blank"
            rel="noopener noreferrer"
            role="listitem"
            onClick={(e) => { handleCardClick(e, i); trackClick({ query, category, position: i + 1, url: img.url, title: img.title, engine: img.engine }); }}
            className="group relative mb-3 inline-block w-full overflow-hidden rounded-lg border bg-muted break-inside-avoid hover:ring-2 hover:ring-ring focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none transition-shadow"
          >
            <img
              src={img.thumbnail_src || img.img_src}
              alt={img.title}
              loading="lazy"
              referrerPolicy="no-referrer"
              className="w-full object-cover transition-transform group-hover:scale-[1.03]"
              onLoad={(e) => handleThumbLoad(i, e.target as HTMLImageElement)}
              onError={(e) => {
                const el = e.target as HTMLImageElement;
                el.src =
                  "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='150'%3E%3Crect fill='%23eee' width='200' height='150'/%3E%3Ctext x='100' y='80' text-anchor='middle' fill='%23999' font-size='12'%3ENo image%3C/text%3E%3C/svg%3E";
              }}
            />
            {/* Hover overlay with title + size */}
            <div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/70 to-transparent p-2 opacity-0 transition-opacity group-hover:opacity-100">
              <div className="flex items-center gap-1">
                <p className="truncate text-xs text-white flex-1">{img.title}</p>
                {onToggleBookmark && (
                  <button
                    onClick={(e) => { e.preventDefault(); e.stopPropagation(); onToggleBookmark(img); }}
                    aria-label={bookmarkedUrls?.has(img.url) ? "Remove bookmark" : "Add bookmark"}
                    className="shrink-0 rounded p-0.5 hover:bg-white/20 transition-colors"
                  >
                    {bookmarkedUrls?.has(img.url) ? (
                      <BookmarkCheck className="h-4 w-4 text-yellow-400" />
                    ) : (
                      <Bookmark className="h-4 w-4 text-white/70" />
                    )}
                  </button>
                )}
              </div>
              <div className="flex items-center gap-1">
                <p className="truncate text-[10px] text-white/60">{img.source}</p>
                {getSize(i) && (
                  <span className="ml-auto shrink-0 text-[10px] tabular-nums text-white/60">
                    {formatSize(getSize(i)!.w, getSize(i)!.h)}
                  </span>
                )}
              </div>
            </div>
          </a>
        ))}
      </div>

      {/* Lightbox */}
      {selected && selectedIndex !== null && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4"
          role="dialog"
          aria-label={`Image viewer: ${selected.title}`}
          aria-modal="true"
          onClick={close}
        >
          {/* Prev button */}
          <button
            onClick={(e) => { e.stopPropagation(); goPrev(); }}
            disabled={selectedIndex <= 0}
            aria-label="Previous image"
            className="absolute left-2 top-1/2 z-10 -translate-y-1/2 rounded-full bg-background/80 p-2 text-foreground shadow-lg hover:bg-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:pointer-events-none disabled:opacity-30 sm:left-4"
          >
            <ChevronLeft className="h-6 w-6" />
          </button>

          {/* Next button */}
          <button
            onClick={(e) => { e.stopPropagation(); goNext(); }}
            disabled={selectedIndex >= results.length - 1}
            aria-label="Next image"
            className="absolute right-2 top-1/2 z-10 -translate-y-1/2 rounded-full bg-background/80 p-2 text-foreground shadow-lg hover:bg-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:pointer-events-none disabled:opacity-30 sm:right-4"
          >
            <ChevronRight className="h-6 w-6" />
          </button>

          <div
            className="relative max-h-[90vh] max-w-4xl overflow-auto rounded-lg bg-card p-4 shadow-2xl"
            onClick={(e) => e.stopPropagation()}
          >
            <button
              onClick={close}
              aria-label="Close lightbox"
              className="absolute right-2 top-2 z-10 rounded-full bg-background/80 p-1.5 hover:bg-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
            >
              <X className="h-5 w-5" />
            </button>
            <img
              src={selected.img_src}
              alt={selected.title}
              referrerPolicy="no-referrer"
              className="max-h-[70vh] w-auto rounded object-contain"
              onLoad={(e) => handleFullLoad(e.target as HTMLImageElement)}
            />
            <div className="mt-3">
              <h3 className="font-medium">{selected.title}</h3>
              <p className="mt-1 text-sm text-muted-foreground">
                Source: {selected.source} • Engine: {selected.engine}
                {getSize(selectedIndex) && (
                  <> • {formatSize(getSize(selectedIndex)!.w, getSize(selectedIndex)!.h)}</>
                )}
                {selected.published_date && (
                  <> • <span className="tabular-nums">{selected.published_date}</span></>
                )}
                <span className="ml-2 tabular-nums opacity-60">
                  {selectedIndex + 1} / {results.length}
                </span>
              </p>
              <a
                href={selected.url}
                target="_blank"
                rel="noopener noreferrer"
                onClick={() => trackClick({ query, category, position: selectedIndex + 1, url: selected.url, title: selected.title, engine: selected.engine })}
                className="mt-2 inline-block text-sm text-blue-600 hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none dark:text-blue-400"
              >
                Visit page →
              </a>
              {onToggleBookmark && (
                <button
                  onClick={() => onToggleBookmark(selected)}
                  aria-label={bookmarkedUrls?.has(selected.url) ? "Remove bookmark" : "Add bookmark"}
                  className="ml-3 inline-flex items-center gap-1 rounded px-2 py-1 text-sm hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none transition-colors"
                >
                  {bookmarkedUrls?.has(selected.url) ? (
                    <><BookmarkCheck className="h-4 w-4 text-primary" /> Bookmarked</>
                  ) : (
                    <><Bookmark className="h-4 w-4" /> Bookmark</>
                  )}
                </button>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}
