"use client";

import Image from "next/image";
import { ChevronLeft, ChevronRight, X } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";

type GalleryImage = { src: string; alt: string };

export function GalleryLightbox({ images }: { images: GalleryImage[] }) {
  const [active, setActive] = useState<number | null>(null);
  const closeRef = useRef<HTMLButtonElement | null>(null);
  const lastFocusedRef = useRef<HTMLElement | null>(null);
  const touchStartXRef = useRef<number | null>(null);

  const close = useCallback(() => {
    setActive(null);
    requestAnimationFrame(() => lastFocusedRef.current?.focus());
  }, []);

  const showPrevious = useCallback(() => {
    setActive((value) => (value === null ? value : (value - 1 + images.length) % images.length));
  }, [images.length]);

  const showNext = useCallback(() => {
    setActive((value) => (value === null ? value : (value + 1) % images.length));
  }, [images.length]);

  useEffect(() => {
    if (active === null) return;
    const body = document.body;
    const previousOverflow = body.style.overflow;
    const previousPaddingRight = body.style.paddingRight;
    const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
    body.style.overflow = "hidden";
    if (scrollbarWidth > 0) body.style.paddingRight = `${scrollbarWidth}px`;
    closeRef.current?.focus();
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") close();
      if (event.key === "ArrowRight") showNext();
      if (event.key === "ArrowLeft") showPrevious();
    };
    window.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("keydown", onKey);
      body.style.overflow = previousOverflow;
      body.style.paddingRight = previousPaddingRight;
    };
  }, [active, close, showNext, showPrevious]);

  return (
    <>
      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
        {images.map((image, index) => (
          <button key={image.src} className="group relative aspect-[4/3] overflow-hidden rounded-lg bg-kiln-iron text-left" onClick={(event) => { lastFocusedRef.current = event.currentTarget; setActive(index); }}>
            <Image src={image.src} alt={image.alt} fill priority={index === 0} sizes="(min-width: 1024px) 33vw, 50vw" className="object-cover transition duration-300 group-hover:brightness-110 group-hover:saturate-110" />
          <span className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-3 text-sm">{image.alt}</span>
          </button>
        ))}
      </div>
      {active !== null ? (
        <div className="fixed inset-0 z-50 bg-black" role="dialog" aria-modal="true" aria-label="Просмотр фотографии" onClick={close} onTouchStart={(event) => { touchStartXRef.current = event.changedTouches[0]?.clientX ?? null; }} onTouchEnd={(event) => { const start = touchStartXRef.current; const end = event.changedTouches[0]?.clientX; touchStartXRef.current = null; if (start === null || end === undefined || Math.abs(end - start) < 48) return; if (end > start) showPrevious(); else showNext(); }}>
          <div className="pointer-events-none absolute inset-x-0 top-0 z-10 bg-gradient-to-b from-black/90 via-black/55 to-transparent px-[max(1rem,env(safe-area-inset-left))] pb-12 pt-[calc(1.25rem+env(safe-area-inset-top))] md:px-8 md:pt-7">
            <h2 className="mx-auto max-w-5xl text-center text-2xl text-kiln-flame md:text-4xl">{images[active].alt}</h2>
          </div>
          <button ref={closeRef} className="gallery-close button button-secondary z-20 px-3" aria-label="Закрыть" onClick={(event) => { event.stopPropagation(); close(); }}>
            <X size={20} />
          </button>
          <button type="button" className="group absolute inset-y-0 left-0 z-20 flex w-16 items-center justify-center text-white/70 transition hover:bg-black/20 hover:text-white md:w-24" aria-label="Предыдущее фото" onClick={(event) => { event.stopPropagation(); showPrevious(); }}>
            <ChevronLeft className="transition-transform group-hover:-translate-x-1" size={34} strokeWidth={1.5} />
          </button>
          <button type="button" className="group absolute inset-y-0 right-0 z-20 flex w-16 items-center justify-center text-white/70 transition hover:bg-black/20 hover:text-white md:w-24" aria-label="Следующее фото" onClick={(event) => { event.stopPropagation(); showNext(); }}>
            <ChevronRight className="transition-transform group-hover:translate-x-1" size={34} strokeWidth={1.5} />
          </button>
          <div className="absolute inset-0 flex items-center justify-center px-3 pb-28 pt-20 md:px-8 md:pb-32 md:pt-24" onClick={(event) => event.stopPropagation()}>
            <div className="relative h-full w-full">
              <Image src={images[active].src} alt={images[active].alt} fill sizes="100vw" className="object-contain" />
            </div>
          </div>
          <div className="absolute inset-x-0 bottom-0 z-10 overflow-x-auto bg-gradient-to-t from-black/95 via-black/80 to-transparent px-4 pb-5 pt-12 md:px-8 md:pb-7" onClick={(event) => event.stopPropagation()}>
            <div className="mx-auto flex w-max gap-2">
              {images.map((image, index) => (
                <button key={image.src} type="button" className={`relative h-16 w-20 shrink-0 overflow-hidden rounded border transition md:h-20 md:w-28 ${index === active ? "border-kiln-flame ring-1 ring-kiln-flame" : "border-white/20 opacity-65 hover:opacity-100"}`} aria-label={`Открыть фото: ${image.alt}`} aria-current={index === active ? "true" : undefined} onClick={() => setActive(index)}>
                  <Image src={image.src} alt="" fill sizes="112px" className="object-cover" />
                </button>
              ))}
            </div>
          </div>
        </div>
      ) : null}
    </>
  );
}
