"use client";

import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import ReactLenis from "lenis/react";
import React, { useState, useEffect } from "react";
import Image from "next/image";
import clsx from "clsx";

import CardStack from '@/components/cardStack/CardStack';
import NavbarLayoutFloatingOverlay from '@/components/navbar/NavbarLayoutFloatingOverlay/NavbarLayoutFloatingOverlay';
import FooterBase from '@/components/sections/footer/FooterBase';

import { X, ChevronLeft, ChevronRight } from "lucide-react";

const galleryImagesData = [
  { id: '1', src: "http://img.b2bpic.net/free-photo/bachelorette-flower-arrnagement_23-2149340496.jpg", alt: "Mariage élégant avec fleurs", category: "Mariages" },
  { id: '2', src: "http://img.b2bpic.net/free-photo/navratri-highly-detailed-interior-decoration_23-2151193720.jpg", alt: "Décoration de fiançailles", category: "Fiançailles" },
  { id: '3', src: "http://img.b2bpic.net/free-photo/group-young-people-celebrating-new-year-friends-drinks-champagne_1157-44311.jpg", alt: "Fête d'anniversaire joyeuse", category: "Anniversaires" },
  { id: '4', src: "http://img.b2bpic.net/free-photo/best-friends-getting-something-from-food-truck_23-2148914602.jpg", alt: "Réception extérieure animée", category: "Réceptions" },
  { id: '5', src: "http://img.b2bpic.net/free-photo/room-interior-design_23-2148899436.jpg", alt: "Intérieur moderne et spacieux", category: "Intérieur" },
  { id: '6', src: "http://img.b2bpic.net/free-photo/young-adult-having-fun-white-party_23-2149575121.jpg", alt: "Réception en extérieur", category: "Extérieur" },
  { id: '7', src: "http://img.b2bpic.net/free-photo/catering-restaurant-service_624325-930.jpg", alt: "Table de mariage", category: "Mariages" },
  { id: '8', src: "http://img.b2bpic.net/free-photo/white-daisies-purple-hydrangeas-glass-transparent-tall-green-bottles-decorative-bouquets-vases_1304-3993.jpg", alt: "Fleurs de fiançailles", category: "Fiançailles" },
  { id: '9', src: "http://img.b2bpic.net/free-photo/young-man-playing-acoustic-guitar-with-friends-party_1157-44247.jpg", alt: "Musique d'anniversaire", category: "Anniversaires" },
  { id: '10', src: "http://img.b2bpic.net/free-photo/business-classroom-daytime-with-many-black-chairs-ready-students_146671-16246.jpg", alt: "Salle de conférence", category: "Réceptions" },
  { id: '11', src: "http://img.b2bpic.net/free-photo/classic-style-interior-design_23-2148899440.jpg", alt: "Détail intérieur", category: "Intérieur" },
  { id: '12', src: "http://img.b2bpic.net/free-photo/couple-walking-with-umbrella-rain_23-2149162002.jpg", alt: "Couple extérieur", category: "Extérieur" },
  { id: '13', src: "http://img.b2bpic.net/free-photo/woman-having-date-with-her-boyfriend-valentine-s-day_23-2149162010.jpg", alt: "Mariage intime", category: "Mariages" },
  { id: '14', src: "http://img.b2bpic.net/free-photo/happy-young-people-holding-sparklers-celebrating_1157-44238.jpg", alt: "Ambiance anniversaire", category: "Anniversaires" },
  { id: '15', src: "http://img.b2bpic.net/free-photo/modern-style-interior-design_23-2148899433.jpg", alt: "Espace intérieur", category: "Intérieur" },
  { id: '16', src: "http://img.b2bpic.net/free-photo/flower-vase-modern-interior_23-2151928932.jpg", alt: "Décoration florale", category: "Fiançailles" },
  { id: '17', src: "http://img.b2bpic.net/free-photo/beautiful-wedding-composition-with-roses_23-2149340504.jpg", alt: "Composition florale de mariage", category: "Mariages" },
  { id: '18', src: "http://img.b2bpic.net/free-photo/empty-table-restaurant_23-2149479383.jpg", alt: "Réception vide", category: "Réceptions" },
  { id: '19', src: "http://img.b2bpic.net/free-photo/stylish-wedding-table-decoration-with-flowers-candies_23-2149340499.jpg", alt: "Table de mariage stylée", category: "Mariages" },
  { id: '20', src: "http://img.b2bpic.net/free-photo/luxurious-room-with-large-round-glass-table-with-fresh-flowers_1145-66.jpg", alt: "Intérieur luxueux", category: "Intérieur" },
  { id: '21', src: "http://img.b2bpic.net/free-photo/young-attractive-couple-outdoors_1157-44246.jpg", alt: "Couple en extérieur", category: "Extérieur" },
  { id: '22', src: "http://img.b2bpic.net/free-photo/young-man-party_1157-44235.jpg", alt: "Fête entre amis", category: "Anniversaires" }
];

const categories = ["Tous", "Mariages", "Fiançailles", "Anniversaires", "Réceptions", "Extérieur", "Intérieur"];

export default function GalleryPage() {
  const [activeCategory, setActiveCategory] = useState("Tous");
  const [filteredImages, setFilteredImages] = useState(galleryImagesData);
  const [lightboxOpen, setLightboxOpen] = useState(false);
  const [selectedImageIndex, setSelectedImageIndex] = useState(0);

  useEffect(() => {
    if (activeCategory === "Tous") {
      setFilteredImages(galleryImagesData);
    } else {
      setFilteredImages(galleryImagesData.filter((img) => img.category === activeCategory));
    }
  }, [activeCategory]);

  const openLightbox = (index: number) => {
    setSelectedImageIndex(index);
    setLightboxOpen(true);
  };

  const closeLightbox = () => {
    setLightboxOpen(false);
  };

  const showNextImage = () => {
    setSelectedImageIndex((prevIndex) => (prevIndex + 1) % filteredImages.length);
  };

  const showPrevImage = () => {
    setSelectedImageIndex((prevIndex) => (prevIndex - 1 + filteredImages.length) % filteredImages.length);
  };

  const currentLightboxImage = filteredImages[selectedImageIndex];

  // Shared navigation for Navbar and Footer to ensure consistency
  const navItems = [
    { name: "Accueil", href: "/" },
    { name: "À Propos", href: "/#about" },
    { name: "Services", href: "/#services" },
    { name: "Galerie", href: "/gallery" },
    { name: "Témoignages", href: "/#testimonials" },
    { name: "FAQ", href: "/#faq" },
    { name: "Contact", href: "/#contact" }
  ];

  const footerColumns = [
    {
      title: "Découvrir",      items: [
        { label: "Accueil", href: "/" },
        { label: "À Propos", href: "/#about" },
        { label: "Services", href: "/#services" },
        { label: "Galerie", href: "/gallery" }
      ]
    },
    {
      title: "Assistance",      items: [
        { label: "FAQ", href: "/#faq" },
        { label: "Contact", href: "/#contact" },
        { label: "Politique de Confidentialité", href: "#" },
        { label: "Conditions Générales", href: "#" }
      ]
    },
    {
      title: "Nous Suivre",      items: [
        { label: "Facebook", href: "#" },
        { label: "Instagram", href: "#" },
        { label: "LinkedIn", href: "#" }
      ]
    }
  ];


  return (
    <ThemeProvider
      defaultButtonVariant="shift-hover"
      defaultTextAnimation="entrance-slide"
      borderRadius="rounded"
      contentWidth="mediumSmall"
      sizing="large"
      background="circleGradient"
      cardStyle="subtle-shadow"
      primaryButtonStyle="double-inset"
      secondaryButtonStyle="glass"
      headingFontWeight="extrabold"
    >
      <ReactLenis root>
        <div id="nav" data-section="nav">
          <NavbarLayoutFloatingOverlay
            navItems={navItems}
            brandName="Salle Évasion"
            button={{
              text: "Demander un devis",              href: "/#contact"
            }}
          />
        </div>

        <div className="container mx-auto py-20 px-4">
          <h1 className="text-5xl font-extrabold text-center mb-10">Notre Galerie</h1>
          <p className="text-lg text-center max-w-2xl mx-auto mb-12 text-foreground-secondary">Explorez nos plus belles réalisations, classées par catégorie. Laissez-vous inspirer pour votre prochain événement à la Salle Évasion.</p>

          <div className="flex flex-wrap justify-center gap-4 mb-12">
            {categories.map((category) => (
              <button
                key={category}
                onClick={() => setActiveCategory(category)}
                className={clsx(
                  "px-6 py-2 rounded-full text-sm font-medium transition-all duration-300",                  activeCategory === category
                    ? "bg-primary-cta text-white shadow-lg"
                    : "bg-card text-foreground-secondary hover:bg-card-hover hover:text-foreground"
                )}
              >
                {category}
              </button>
            ))}
          </div>

          <CardStack
            title=""
            description=""
            animationType="slide-up"
            textboxLayout="default"
            gridVariant="two-columns-alternating-heights"
            uniformGridCustomHeightClasses="min-h-72 lg:min-h-96"
            className="w-full"
            containerClassName="py-0 px-0"
            gridClassName="gap-4"
          >
            {filteredImages.map((image, index) => (
              <div
                key={image.id}
                onClick={() => openLightbox(index)}
                className="relative group cursor-pointer overflow-hidden rounded-lg shadow-lg aspect-square"
              >
                <Image
                  src={image.src}
                  alt={image.alt}
                  fill
                  sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                  className="object-cover transition-transform duration-500 group-hover:scale-105"
                  priority={index < 6}
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex items-end p-4">
                  <span className="text-white text-sm font-semibold">{image.category}</span>
                </div>
              </div>
            ))}
          </CardStack>
        </div>

        {lightboxOpen && currentLightboxImage && (
          <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/90 backdrop-blur-md">
            <button
              onClick={closeLightbox}
              className="absolute top-4 right-4 p-2 rounded-full bg-white/20 text-white hover:bg-white/30 transition-colors"
              aria-label="Fermer la galerie"
            >
              <X size={24} />
            </button>
            <button
              onClick={showPrevImage}
              className="absolute left-4 p-3 rounded-full bg-white/20 text-white hover:bg-white/30 transition-colors hidden md:block"
              aria-label="Image précédente"
            >
              <ChevronLeft size={32} />
            </button>
            <div className="relative w-full h-full max-w-4xl max-h-4xl flex items-center justify-center">
              <Image
                src={currentLightboxImage.src}
                alt={currentLightboxImage.alt}
                width={1000}
                height={700}
                className="object-contain max-h-[90vh] max-w-[90vw] animate-in fade-in duration-300"
              />
              <div className="absolute bottom-4 left-1/2 -translate-x-1/2 text-white text-center text-sm">
                <p className="font-semibold">{currentLightboxImage.alt}</p>
                <p className="opacity-80">{currentLightboxImage.category}</p>
              </div>
            </div>
            <button
              onClick={showNextImage}
              className="absolute right-4 p-3 rounded-full bg-white/20 text-white hover:bg-white/30 transition-colors hidden md:block"
              aria-label="Image suivante"
            >
              <ChevronRight size={32} />
            </button>
            <div className="md:hidden absolute bottom-4 w-full flex justify-between px-4">
              <button
                onClick={showPrevImage}
                className="p-3 rounded-full bg-white/20 text-white hover:bg-white/30 transition-colors"
                aria-label="Image précédente"
              >
                <ChevronLeft size={24} />
              </button>
              <button
                onClick={showNextImage}
                className="p-3 rounded-full bg-white/20 text-white hover:bg-white/30 transition-colors"
                aria-label="Image suivante"
              >
                <ChevronRight size={24} />
              </button>
            </div>
          </div>
        )}

        <div id="footer" data-section="footer">
          <FooterBase
            columns={footerColumns}
            logoText="Salle Évasion"
            copyrightText="© 2024 Salle Évasion. Tous droits réservés."
          />
        </div>
      </ReactLenis>
    </ThemeProvider>
  );
}