"use client";

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

interface TripImage {
  id: string;
  url: string;
  caption: string | null;
}

export function ImageGallery({ images }: { images: TripImage[] }) {
  const [activeIndex, setActiveIndex] = useState(0);
  const [lightboxOpen, setLightboxOpen] = useState(false);
  const hasMultiple = images.length > 1;

  function showPrev() {
    setActiveIndex((i) => (i - 1 + images.length) % images.length);
  }
  function showNext() {
    setActiveIndex((i) => (i + 1) % images.length);
  }

  // Saat lightbox terbuka: kunci scroll body + dukung keyboard (Esc tutup,
  // panah kiri/kanan untuk ganti foto).
  useEffect(() => {
    if (!lightboxOpen) return;
    function onKey(e: KeyboardEvent) {
      // Logika prev/next di-inline (bukan panggil showPrev/showNext) supaya
      // effect tidak bergantung pada fungsi yang dibuat ulang tiap render.
      if (e.key === "Escape") setLightboxOpen(false);
      else if (e.key === "ArrowLeft") {
        setActiveIndex((i) => (i - 1 + images.length) % images.length);
      } else if (e.key === "ArrowRight") {
        setActiveIndex((i) => (i + 1) % images.length);
      }
    }
    document.addEventListener("keydown", onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [lightboxOpen, images.length]);

  if (images.length === 0) {
    return (
      <div className="flex h-44 items-center justify-center bg-neutral-100 sm:h-56 lg:h-72">
        <Mountain
          size={56}
          strokeWidth={1.5}
          aria-hidden
          className="text-neutral-300"
        />
      </div>
    );
  }

  const activeImage = images[activeIndex];

  return (
    <div>
      {/* Main Image — klik untuk lihat ukuran penuh */}
      <button
        type="button"
        onClick={() => setLightboxOpen(true)}
        aria-label="Lihat foto ukuran penuh"
        className="group relative block h-44 w-full cursor-zoom-in bg-neutral-900 sm:h-56 lg:h-72"
      >
        <Image
          src={activeImage.url}
          alt={activeImage.caption || "Foto trip"}
          fill
          // `object-contain` — tampilkan gambar utuh tanpa terpotong; rasio
          // foto bebas, sisi yang tak terisi jadi bar gelap (bg-neutral-900).
          className="object-contain"
          sizes="(max-width: 768px) 100vw, 768px"
          priority
        />
        {activeImage.caption && (
          <div className="absolute bottom-0 left-0 right-0 bg-linear-to-t from-black/60 to-transparent px-3 pb-2.5 pt-6 text-left sm:px-4 sm:pb-3 sm:pt-8">
            <p className="text-xs font-medium text-white sm:text-sm">
              {activeImage.caption}
            </p>
          </div>
        )}
        {/* Counter */}
        <div className="absolute right-2 top-2 rounded-full bg-black/50 px-2 py-0.5 text-[10px] font-medium text-white backdrop-blur-sm sm:right-3 sm:top-3 sm:px-2.5 sm:py-1 sm:text-xs">
          {activeIndex + 1} / {images.length}
        </div>
        {/* Petunjuk perbesar */}
        <span className="absolute left-2 top-2 inline-flex items-center gap-1 rounded-full bg-black/50 px-2 py-0.5 text-[10px] font-medium text-white backdrop-blur-sm transition-colors group-hover:bg-black/70 sm:left-3 sm:top-3 sm:px-2.5 sm:py-1 sm:text-xs">
          <Maximize2 size={11} strokeWidth={2} aria-hidden />
          Lihat penuh
        </span>
      </button>

      {/* Thumbnails */}
      {hasMultiple && (
        <div className="flex gap-1 overflow-x-auto bg-neutral-100 p-1.5 sm:gap-1.5 sm:p-2">
          {images.map((img, i) => (
            <button
              key={img.id}
              type="button"
              onClick={() => setActiveIndex(i)}
              className={`relative h-11 w-16 shrink-0 overflow-hidden rounded-md transition-all sm:h-14 sm:w-20 sm:rounded-lg ${
                i === activeIndex
                  ? "ring-2 ring-primary-500 ring-offset-1"
                  : "opacity-60 hover:opacity-100"
              }`}
            >
              <Image
                src={img.url}
                alt={img.caption || `Foto ${i + 1}`}
                fill
                className="object-cover"
                sizes="80px"
              />
            </button>
          ))}
        </div>
      )}

      {/* Lightbox — penampil foto ukuran penuh */}
      {lightboxOpen && (
        <div
          role="dialog"
          aria-modal="true"
          aria-label="Penampil foto trip"
          className="fixed inset-0 z-50 flex flex-col bg-black/95"
        >
          {/* Top bar */}
          <div className="flex items-center justify-between px-4 py-3 text-white">
            <span className="text-sm font-medium tabular-nums">
              {activeIndex + 1} / {images.length}
            </span>
            <button
              type="button"
              onClick={() => setLightboxOpen(false)}
              aria-label="Tutup"
              className="flex h-9 w-9 items-center justify-center rounded-full bg-white/10 transition-colors hover:bg-white/20"
            >
              <X size={20} strokeWidth={2} aria-hidden />
            </button>
          </div>

          {/* Area gambar — klik latar untuk menutup */}
          <div
            className="relative flex-1"
            onClick={() => setLightboxOpen(false)}
          >
            <div
              className="relative h-full w-full"
              onClick={(e) => e.stopPropagation()}
            >
              <Image
                src={activeImage.url}
                alt={activeImage.caption || "Foto trip"}
                fill
                className="object-contain"
                sizes="100vw"
                quality={90}
              />
            </div>

            {hasMultiple && (
              <>
                <button
                  type="button"
                  onClick={(e) => {
                    e.stopPropagation();
                    showPrev();
                  }}
                  aria-label="Foto sebelumnya"
                  className="absolute left-2 top-1/2 flex h-11 w-11 -translate-y-1/2 items-center justify-center rounded-full bg-white/10 text-white transition-colors hover:bg-white/25 sm:left-4"
                >
                  <ChevronLeft size={24} strokeWidth={2} aria-hidden />
                </button>
                <button
                  type="button"
                  onClick={(e) => {
                    e.stopPropagation();
                    showNext();
                  }}
                  aria-label="Foto berikutnya"
                  className="absolute right-2 top-1/2 flex h-11 w-11 -translate-y-1/2 items-center justify-center rounded-full bg-white/10 text-white transition-colors hover:bg-white/25 sm:right-4"
                >
                  <ChevronRight size={24} strokeWidth={2} aria-hidden />
                </button>
              </>
            )}
          </div>

          {activeImage.caption && (
            <p className="px-4 py-3 text-center text-sm text-white/80">
              {activeImage.caption}
            </p>
          )}

          {/* Thumbnail strip di dalam lightbox */}
          {hasMultiple && (
            <div className="flex justify-center gap-1.5 overflow-x-auto px-4 pb-4">
              {images.map((img, i) => (
                <button
                  key={img.id}
                  type="button"
                  onClick={() => setActiveIndex(i)}
                  aria-label={`Lihat foto ${i + 1}`}
                  className={`relative h-12 w-16 shrink-0 overflow-hidden rounded-md transition-all ${
                    i === activeIndex
                      ? "ring-2 ring-primary-400 ring-offset-1 ring-offset-black"
                      : "opacity-50 hover:opacity-100"
                  }`}
                >
                  <Image
                    src={img.url}
                    alt=""
                    fill
                    className="object-cover"
                    sizes="64px"
                  />
                </button>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
