"use client";

import { useEffect, useRef, useState } from "react";
import { ChevronLeft, ChevronRight, X } from "lucide-react";
import { gallery } from "../data";

export function GalleryExperience() {
  const [activeIndex, setActiveIndex] = useState<number | null>(null);
  const sliderRef = useRef<HTMLDivElement>(null);
  const activeItem = activeIndex === null ? null : gallery[activeIndex];

  useEffect(() => {
    if (activeIndex === null) return;

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") setActiveIndex(null);
      if (event.key === "ArrowLeft") {
        setActiveIndex((index) =>
          index === null ? null : (index - 1 + gallery.length) % gallery.length
        );
      }
      if (event.key === "ArrowRight") {
        setActiveIndex((index) =>
          index === null ? null : (index + 1) % gallery.length
        );
      }
    };

    document.body.classList.add("lightbox-open");
    window.addEventListener("keydown", onKeyDown);
    return () => {
      document.body.classList.remove("lightbox-open");
      window.removeEventListener("keydown", onKeyDown);
    };
  }, [activeIndex]);

  const moveSlider = (direction: number) => {
    sliderRef.current?.scrollBy({
      left: direction * Math.min(sliderRef.current.clientWidth * 0.82, 760),
      behavior: "smooth",
    });
  };

  const moveLightbox = (direction: number) => {
    setActiveIndex((index) =>
      index === null ? null : (index + direction + gallery.length) % gallery.length
    );
  };

  return (
    <>
      <div className="gallery-feature-pair reveal">
        {gallery.slice(0, 2).map((item, index) => (
          <button
            className="gallery-feature-button"
            type="button"
            key={item.title}
            onClick={() => setActiveIndex(index)}
            aria-label={`View ${item.title}`}
          >
            <img src={item.image} alt={item.title} />
            <span className="gallery-image-copy">
              <small>{item.tag}</small>
              <strong>{item.title}</strong>
              <em>View image</em>
            </span>
          </button>
        ))}
      </div>

      <div className="gallery-slider-head reveal">
        <div>
          <span className="eyebrow">More Views</span>
          <h3>Explore the resort</h3>
        </div>
        <div className="gallery-slider-controls">
          <button type="button" onClick={() => moveSlider(-1)} aria-label="Previous images">
            <ChevronLeft />
          </button>
          <button type="button" onClick={() => moveSlider(1)} aria-label="Next images">
            <ChevronRight />
          </button>
        </div>
      </div>

      <div className="gallery-page-slider reveal" ref={sliderRef}>
        {gallery.slice(2).map((item, index) => (
          <button
            className="gallery-slide"
            type="button"
            key={item.title}
            onClick={() => setActiveIndex(index + 2)}
            aria-label={`View ${item.title}`}
          >
            <img src={item.image} alt={item.title} />
            <span>
              <small>{item.tag}</small>
              <strong>{item.title}</strong>
            </span>
          </button>
        ))}
      </div>

      {activeItem ? (
        <div
          className="gallery-lightbox"
          role="dialog"
          aria-modal="true"
          aria-label={`${activeItem.title} image preview`}
          onClick={() => setActiveIndex(null)}
        >
          <button
            className="gallery-lightbox-close"
            type="button"
            onClick={() => setActiveIndex(null)}
            aria-label="Close image preview"
          >
            <X />
          </button>
          <button
            className="gallery-lightbox-arrow previous"
            type="button"
            onClick={(event) => {
              event.stopPropagation();
              moveLightbox(-1);
            }}
            aria-label="Previous image"
          >
            <ChevronLeft />
          </button>
          <figure onClick={(event) => event.stopPropagation()}>
            <img src={activeItem.image} alt={activeItem.title} />
            <figcaption>
              <span>{activeItem.tag}</span>
              {activeItem.title}
            </figcaption>
          </figure>
          <button
            className="gallery-lightbox-arrow next"
            type="button"
            onClick={(event) => {
              event.stopPropagation();
              moveLightbox(1);
            }}
            aria-label="Next image"
          >
            <ChevronRight />
          </button>
        </div>
      ) : null}
    </>
  );
}
