"use client";

import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { Grid2X2, MapPin, Navigation, Calendar, MessageSquare, ChevronDown, X } from "lucide-react";
import { FadeInUp } from "@/components/ui/motion";
import { EmptyState } from "@/components/ui/EmptyState";

interface GalleryData {
  id: number;
  title: string | null;
  imageUrl: string;
  category: string | null;
  isFeatured?: boolean;
}

const ALL_CATEGORY = "Semua Galeri";

const categories = [
  { id: ALL_CATEGORY, icon: Grid2X2 },
  { id: "Destinasi Wisata", icon: MapPin },
  { id: "Kegiatan Tour", icon: Navigation },
  { id: "Event & Gathering", icon: Calendar },
  { id: "Testimoni Pelanggan", icon: MessageSquare },
];

export function GalleryListingClient({ galleries }: { galleries: GalleryData[] }) {
  const [activeCategory, setActiveCategory] = useState(ALL_CATEGORY);
  const [selected, setSelected] = useState<GalleryData | null>(null);

  const filteredGalleries =
    activeCategory === ALL_CATEGORY
      ? galleries
      : galleries.filter((g) => g.category === activeCategory);

  useEffect(() => {
    if (!selected) return;
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") setSelected(null);
    };
    document.addEventListener("keydown", handleKeyDown);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", handleKeyDown);
      document.body.style.overflow = "auto";
    };
  }, [selected]);

  return (
    <div className="max-w-[1300px] mx-auto w-full px-4 sm:px-6">
      {/* 1. Category Tabs & Sort */}
      <FadeInUp className="mb-10 relative z-20 flex flex-col lg:flex-row items-center justify-between gap-6">
        {/* Horizontal Scrollable Pills */}
        <div className="overflow-x-auto no-scrollbar w-full lg:w-auto pb-2 lg:pb-0">
          <div className="flex items-center gap-3 w-max">
            {categories.map((cat) => {
              const isActive = activeCategory === cat.id;
              const Icon = cat.icon;
              return (
                <button
                  key={cat.id}
                  onClick={() => setActiveCategory(cat.id)}
                  className={`flex items-center gap-2 px-5 py-2.5 rounded-full text-[13px] font-bold border transition-all shrink-0 ${
                    isActive
                      ? "bg-[#d32f2f] border-[#d32f2f] text-white shadow-md"
                      : "bg-white border-gray-200 text-gray-600 hover:border-gray-300 hover:bg-gray-50 shadow-sm"
                  }`}
                >
                  <Icon className={`w-4 h-4 ${isActive ? "text-white" : "text-gray-400"}`} />
                  {cat.id}
                </button>
              );
            })}
          </div>
        </div>

        {/* Sort Dropdown */}
        <button className="flex items-center justify-between gap-4 px-5 py-2.5 rounded-full bg-white border border-gray-200 text-gray-600 font-bold text-[13px] hover:bg-gray-50 shadow-sm shrink-0 w-full lg:w-auto">
          <div className="flex items-center gap-2">
            <Calendar className="w-4 h-4 text-gray-400" />
            Terbaru
          </div>
          <ChevronDown className="w-4 h-4 text-gray-400" />
        </button>
      </FadeInUp>

      {/* 2. Masonry Gallery Grid */}
      {filteredGalleries.length === 0 ? (
        <EmptyState message="Belum ada foto galeri." />
      ) : (
        <div className="columns-1 sm:columns-2 lg:columns-3 gap-4 mb-16 [column-fill:_balance]">
          {filteredGalleries.map((item) => (
            <button
              key={item.id}
              type="button"
              onClick={() => setSelected(item)}
              className="group relative block w-full mb-4 break-inside-avoid rounded-2xl overflow-hidden shadow-sm cursor-zoom-in"
            >
              <img
                src={item.imageUrl}
                alt={item.title || "Galeri"}
                className="w-full h-auto object-cover transition-transform duration-500 group-hover:scale-105"
                loading="lazy"
              />
              <div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors duration-300" />
            </button>
          ))}
        </div>
      )}

      {/* 3. Lightbox — rendered via portal so it always sits above the fixed navbar */}
      {selected &&
        typeof document !== "undefined" &&
        createPortal(
          <div
            className="fixed inset-0 z-[1000] flex items-center justify-center bg-black/90 backdrop-blur-sm p-4 sm:p-8"
            onClick={() => setSelected(null)}
          >
            <button
              type="button"
              onClick={() => setSelected(null)}
              className="fixed top-4 right-4 sm:top-6 sm:right-6 z-[1001] flex h-10 w-10 items-center justify-center rounded-full bg-white/10 text-white hover:bg-white/20 transition-colors"
              aria-label="Tutup"
            >
              <X className="h-5 w-5" />
            </button>
            <img
              src={selected.imageUrl}
              alt={selected.title || "Galeri"}
              className="max-h-full max-w-full object-contain rounded-lg"
              onClick={(e) => e.stopPropagation()}
            />
          </div>,
          document.body
        )}
    </div>
  );
}
