"use client";

import Image from "next/image";
import { useCallback, useEffect, useId, useState } from "react";

export type GalleryPhoto = {
  src: string;
  alt: string;
};

type PhotoGalleryProps = {
  photos: GalleryPhoto[];
  columns?: "dense" | "wide";
  limit?: number;
};

export function PhotoGallery({
  photos,
  columns = "dense",
  limit,
}: PhotoGalleryProps) {
  const titleId = useId();
  const items = limit ? photos.slice(0, limit) : photos;
  const [activeIndex, setActiveIndex] = useState<number | null>(null);
  const isOpen = activeIndex !== null;
  const activePhoto = isOpen ? photos[activeIndex] : null;

  const close = useCallback(() => setActiveIndex(null), []);
  const showPrev = useCallback(() => {
    setActiveIndex((current) =>
      current === null ? current : (current - 1 + photos.length) % photos.length,
    );
  }, [photos.length]);
  const showNext = useCallback(() => {
    setActiveIndex((current) =>
      current === null ? current : (current + 1) % photos.length,
    );
  }, [photos.length]);

  useEffect(() => {
    if (!isOpen) return;

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") close();
      if (event.key === "ArrowLeft") showPrev();
      if (event.key === "ArrowRight") showNext();
    };

    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKeyDown);

    return () => {
      document.body.style.overflow = previousOverflow;
      window.removeEventListener("keydown", onKeyDown);
    };
  }, [close, isOpen, showNext, showPrev]);

  return (
    <>
      <div className={`photo-grid ${columns}`}>
        {items.map((photo, index) => (
          <button
            className="photo-tile"
            key={photo.src}
            type="button"
            onClick={() => setActiveIndex(index)}
            aria-label={`View full display: ${photo.alt}`}
          >
            <Image src={photo.src} alt={photo.alt} width={720} height={540} />
            <span className="photo-tile-hint">Click to view full display</span>
          </button>
        ))}
      </div>

      {isOpen && activePhoto ? (
        <div
          className="lightbox"
          role="dialog"
          aria-modal="true"
          aria-labelledby={titleId}
          onClick={close}
        >
          <div
            className="lightbox-panel"
            onClick={(event) => event.stopPropagation()}
          >
            <div className="lightbox-toolbar">
              <p id={titleId}>{activePhoto.alt}</p>
              <div className="lightbox-actions">
                <span>
                  {(activeIndex ?? 0) + 1} / {photos.length}
                </span>
                <button type="button" onClick={close} aria-label="Close">
                  Close
                </button>
              </div>
            </div>
            <div className="lightbox-stage">
              <button
                className="lightbox-nav prev"
                type="button"
                onClick={showPrev}
                aria-label="Previous photo"
              >
                ‹
              </button>
              <Image
                src={activePhoto.src}
                alt={activePhoto.alt}
                width={1600}
                height={1200}
                className="lightbox-image"
                priority
              />
              <button
                className="lightbox-nav next"
                type="button"
                onClick={showNext}
                aria-label="Next photo"
              >
                ›
              </button>
            </div>
          </div>
        </div>
      ) : null}
    </>
  );
}
