"use client";

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

export function PropertyGallery({ photos, title }: { photos: { id: number; url: string }[]; title: string }) {
  const [openIndex, setOpenIndex] = useState<number | null>(null);

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

  useEffect(() => {
    if (openIndex === null) return;
    function onKeyDown(e: KeyboardEvent) {
      if (e.key === "Escape") close();
      if (e.key === "ArrowLeft") showPrev();
      if (e.key === "ArrowRight") showNext();
    }
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [openIndex, close, showPrev, showNext]);

  if (photos.length === 0) {
    return (
      <div className="flex h-64 items-center justify-center rounded bg-brand-tint text-sm font-medium text-brand-deep">
        No photos uploaded yet
      </div>
    );
  }

  // Split gallery: one large image on the left, a 2x2 thumbnail grid on the right.
  const thumbs = photos.slice(1, 5);
  const remaining = photos.length - 5;

  return (
    <>
      <div className="grid gap-4 md:h-[430px] md:grid-cols-2">
        <button
          type="button"
          onClick={() => setOpenIndex(0)}
          className="relative aspect-[16/10] w-full overflow-hidden rounded bg-stone-100 md:aspect-auto md:h-full"
        >
          <Image src={photos[0].url} alt={title} fill className="object-cover" priority sizes="(max-width: 768px) 100vw, 50vw" />
        </button>

        {thumbs.length > 0 && (
          <div className="grid grid-cols-2 gap-4 md:h-full">
            {thumbs.map((p, i) => {
              const index = i + 1;
              const isLast = i === thumbs.length - 1 && remaining > 0;
              return (
                <button
                  key={p.id}
                  type="button"
                  onClick={() => setOpenIndex(index)}
                  className="relative aspect-[16/10] overflow-hidden rounded bg-stone-100 md:aspect-auto md:h-full"
                >
                  <Image src={p.url} alt={`${title} photo ${index + 1}`} fill className="object-cover" sizes="25vw" />
                  {isLast && (
                    <span className="absolute inset-0 flex items-center justify-center bg-black/55 text-lg font-semibold text-white">
                      +{remaining} more
                    </span>
                  )}
                </button>
              );
            })}
          </div>
        )}
      </div>

      {openIndex !== null && (
        <div
          className="fixed inset-0 z-100 flex items-center justify-center bg-black/90 p-4"
          onClick={close}
          role="dialog"
          aria-modal="true"
          aria-label={`${title} photo ${openIndex + 1} of ${photos.length}`}
        >
          <button
            type="button"
            onClick={close}
            aria-label="Close"
            className="absolute top-4 right-4 flex h-10 w-10 items-center justify-center rounded-full bg-white/10 text-xl text-white hover:bg-white/20"
          >
            ✕
          </button>

          {photos.length > 1 && (
            <button
              type="button"
              onClick={(e) => {
                e.stopPropagation();
                showPrev();
              }}
              aria-label="Previous photo"
              className="absolute left-2 flex h-12 w-12 items-center justify-center rounded-full bg-white/10 text-2xl text-white hover:bg-white/20 sm:left-6"
            >
              ‹
            </button>
          )}

          <div className="relative h-[80vh] w-full max-w-5xl" onClick={(e) => e.stopPropagation()}>
            <Image src={photos[openIndex].url} alt={`${title} photo ${openIndex + 1}`} fill className="object-contain" sizes="100vw" />
          </div>

          {photos.length > 1 && (
            <button
              type="button"
              onClick={(e) => {
                e.stopPropagation();
                showNext();
              }}
              aria-label="Next photo"
              className="absolute right-2 flex h-12 w-12 items-center justify-center rounded-full bg-white/10 text-2xl text-white hover:bg-white/20 sm:right-6"
            >
              ›
            </button>
          )}

          <div className="absolute bottom-5 left-1/2 -translate-x-1/2 rounded-full bg-black/50 px-3 py-1 text-xs font-medium text-white tabular-nums">
            {openIndex + 1} / {photos.length}
          </div>
        </div>
      )}
    </>
  );
}
