"use client";

/* eslint-disable @next/next/no-img-element -- Product media URLs are not verified for next/image remote patterns yet. */

import { useState } from "react";
import { ChevronLeft, ChevronRight, ImageOff, ZoomIn } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogTitle,
} from "@/components/ui/dialog";
import { cn } from "@/lib/utils";

interface GalleryImage {
  id: number;
  url: string;
  thumb: string;
  medium: string;
  large: string;
  order: number;
}

interface ItemGalleryProps {
  images: GalleryImage[];
  alt: string;
}

export function ItemGallery({ images, alt }: ItemGalleryProps) {
  const [activeIndex, setActiveIndex] = useState(0);
  const [lightboxOpen, setLightboxOpen] = useState(false);

  if (images.length === 0) {
    return (
      <div
        className="aspect-square rounded border border-dashed border-slate-200 bg-slate-50 flex items-center justify-center overflow-hidden"
        role="img"
        aria-label={`${alt} product photo unavailable`}
      >
        <div className="flex max-w-xs flex-col items-center gap-3 px-6 text-center">
          <div className="rounded-full border border-slate-200 bg-white p-4 shadow-sm">
            <ImageOff className="h-8 w-8 text-slate-300" aria-hidden="true" />
          </div>
          <div className="space-y-1">
            <p className="text-sm font-medium text-slate-700">Photo unavailable</p>
            <p className="text-xs text-slate-500">
              The seller has not added product photos yet.
            </p>
          </div>
        </div>
      </div>
    );
  }

  const sorted = [...images].sort((a, b) => a.order - b.order);
  const selectedIndex = Math.min(activeIndex, sorted.length - 1);
  const activeImage = sorted[selectedIndex];
  const hasMultipleImages = sorted.length > 1;
  const galleryLabel = hasMultipleImages
    ? `${alt} product images`
    : `${alt} product image`;
  const activeImageAlt = hasMultipleImages
    ? `${alt}, image ${selectedIndex + 1} of ${sorted.length}`
    : alt;

  const showPrev = () => {
    setActiveIndex((i) => (i - 1 + sorted.length) % sorted.length);
  };

  const showNext = () => {
    setActiveIndex((i) => (i + 1) % sorted.length);
  };

  const onLightboxKeyDown = (event: React.KeyboardEvent) => {
    if (!hasMultipleImages) return;
    if (event.key === "ArrowLeft") {
      event.preventDefault();
      showPrev();
    } else if (event.key === "ArrowRight") {
      event.preventDefault();
      showNext();
    }
  };

  return (
    <div className="flex flex-col-reverse gap-3 md:flex-row" role="group" aria-label={galleryLabel}>
      {/* Thumbnails */}
      {hasMultipleImages && (
        <div
          className="flex gap-2 overflow-x-auto pb-1 md:flex-col md:gap-2 md:overflow-x-visible md:pb-0"
          role="group"
          aria-label={`${alt} image thumbnails`}
        >
          {sorted.map((img, i) => (
            <button
              key={img.id}
              type="button"
              onClick={() => setActiveIndex(i)}
              className={cn(
                "w-16 h-16 rounded overflow-hidden border-2 shrink-0 transition-colors",
                i === selectedIndex
                  ? "border-forest-600"
                  : "border-transparent hover:border-slate-300"
              )}
              aria-current={i === selectedIndex ? "true" : undefined}
              aria-label={`Show ${alt} image ${i + 1} of ${sorted.length}`}
              aria-pressed={i === selectedIndex}
            >
              <img
                src={img.thumb}
                alt=""
                aria-hidden="true"
                className="w-full h-full object-cover"
              />
            </button>
          ))}
        </div>
      )}

      {/* Main image — click to zoom */}
      <button
        type="button"
        onClick={() => setLightboxOpen(true)}
        className="group relative flex-1 aspect-square rounded bg-slate-100 overflow-hidden cursor-zoom-in focus:outline-none focus-visible:ring-2 focus-visible:ring-forest-600 focus-visible:ring-offset-2"
        aria-label={`Zoom ${activeImageAlt}`}
      >
        <img
          src={activeImage.large}
          alt={activeImageAlt}
          className="w-full h-full object-cover"
        />
        <span
          className="absolute right-3 top-3 flex items-center gap-1 rounded-full bg-black/55 px-2.5 py-1 text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100"
          aria-hidden="true"
        >
          <ZoomIn className="h-3.5 w-3.5" />
          Zoom
        </span>
      </button>

      <Dialog open={lightboxOpen} onOpenChange={setLightboxOpen}>
        <DialogContent
          onKeyDown={onLightboxKeyDown}
          className="w-[95vw] max-w-4xl border-0 bg-transparent p-0 shadow-none"
        >
          <DialogTitle className="sr-only">{activeImageAlt}</DialogTitle>
          <div className="relative flex items-center justify-center">
            <img
              src={activeImage.large}
              alt={activeImageAlt}
              className="max-h-[85vh] w-auto max-w-full rounded object-contain"
            />

            {hasMultipleImages && (
              <>
                <button
                  type="button"
                  onClick={showPrev}
                  className="absolute left-2 top-1/2 -translate-y-1/2 rounded-full bg-black/55 p-2 text-white transition-colors hover:bg-black/75 focus:outline-none focus-visible:ring-2 focus-visible:ring-white"
                  aria-label="Previous image"
                >
                  <ChevronLeft className="h-6 w-6" />
                </button>
                <button
                  type="button"
                  onClick={showNext}
                  className="absolute right-2 top-1/2 -translate-y-1/2 rounded-full bg-black/55 p-2 text-white transition-colors hover:bg-black/75 focus:outline-none focus-visible:ring-2 focus-visible:ring-white"
                  aria-label="Next image"
                >
                  <ChevronRight className="h-6 w-6" />
                </button>
                <span
                  className="absolute bottom-3 left-1/2 -translate-x-1/2 rounded-full bg-black/55 px-3 py-1 text-xs font-medium text-white"
                  aria-live="polite"
                >
                  {selectedIndex + 1} / {sorted.length}
                </span>
              </>
            )}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
