import LandingLayout from '@/Layouts/LandingLayout';
import { useState, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Head } from '@inertiajs/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faImages, faMagnifyingGlassPlus, faExclamationTriangle, faChevronLeft, faChevronRight } from '@fortawesome/free-solid-svg-icons';
import Lightbox from '@/Components/LandingPage/Lightbox'; // Pastikan komponen Lightbox ada

const IMAGES_PER_PAGE = 8; // Atur jumlah gambar per halaman

/**
 * Halaman Galeri Kampus
 * Menerima data dinamis dari GalleryController:
 * - campus: Data dasar kampus
 * - images: Daftar foto galeri dari DB (dengan properti: id, title, category, image_url)
 * - categories: Daftar KEMUNGKINAN kategori (Array statis dari Controller, misal: ['Semua', 'Fasilitas', 'Kegiatan', ...])
 */
export default function GalleryPage({ campus, images }) { 
    // Kita tidak akan menggunakan props 'categories' statis lagi, tapi akan membuatnya dinamis dari 'images'.

    // Tema fallback
    const theme = campus?.theme || {
        badgeBg: 'bg-gray-100',
        badgeText: 'text-gray-700',
        primary: 'bg-gray-600',
        gradientFrom: 'from-gray-600',
        gradientTo: 'to-gray-800',
    };

    const allImages = images || [];

    // State Management
    const [activeFilter, setActiveFilter] = useState('Semua'); // Default filter
    const [currentPage, setCurrentPage] = useState(1);
    const [lightboxImage, setLightboxImage] = useState(null);

    // =========================================================================
    // 1. Logika untuk menentukan Kategori yang Memiliki Isi (dinamis)
    // =========================================================================
    const filterCategories = useMemo(() => {
        // Ambil kategori unik dari semua gambar yang ada
        const uniqueCategories = new Set(allImages
            .map(image => image.category)
            .filter(category => category) // Hilangkan null/undefined category
        );

        // Ubah Set menjadi Array dan tambahkan 'Semua' di awal
        const categoriesWithContent = ['Semua', ...Array.from(uniqueCategories)];
        
        // Cek jika filter aktif saat ini tidak ada di kategori yang baru, reset ke 'Semua'
        if (activeFilter !== 'Semua' && !uniqueCategories.has(activeFilter)) {
            setActiveFilter('Semua');
        }

        return categoriesWithContent;
    }, [allImages]); // Dijalankan hanya jika 'images' berubah


    // =========================================================================
    // 2. Logika untuk Filtering & Pagination
    // =========================================================================
    
    // Tentukan gambar yang difilter
    const filteredImages = useMemo(() => {
        return activeFilter === 'Semua' 
            ? allImages 
            : allImages.filter(image => image.category === activeFilter);
    }, [allImages, activeFilter]);

    // Hitung total halaman berdasarkan gambar yang difilter
    const pageCount = Math.ceil(filteredImages.length / IMAGES_PER_PAGE);

    // Ambil gambar untuk halaman saat ini
    const startIndex = (currentPage - 1) * IMAGES_PER_PAGE;
    const currentImages = filteredImages.slice(startIndex, startIndex + IMAGES_PER_PAGE);

    // Handler untuk mengubah filter (dan reset ke halaman 1)
    const handleFilterChange = (category) => {
        setActiveFilter(category);
        setCurrentPage(1); // Selalu kembali ke halaman pertama saat filter berubah
    };

    // Handler untuk Pagination
    const goToPage = (pageNumber) => {
        setCurrentPage(pageNumber);
        // Scroll ke atas grid galeri dengan halus
        document.getElementById('gallery-grid')?.scrollIntoView({ behavior: 'smooth' });
    };

    // Fungsi Lightbox
    const openLightbox = (image) => setLightboxImage({ src: image.image_url, title: image.title });
    const closeLightbox = () => setLightboxImage(null);
    
    // Style background
    const backgroundPatternStyle = {
        backgroundImage: 'radial-gradient(circle at 1px 1px, #e2e8f0 0.5px, transparent 0)',
        backgroundSize: '20px 20px',
    };

    return (
        <LandingLayout campus={campus} title={`Galeri - ${campus.name}`}>
            <Head title={`Galeri - ${campus.name}`} />
            
            {/* Header Halaman */}
            <header className={`relative py-24 sm:py-32 bg-gradient-to-r ${theme.gradientFrom} ${theme.gradientTo} overflow-hidden`}>
                 <div className="absolute inset-0 opacity-10 mix-blend-overlay">
                     <svg className="absolute right-0 bottom-0 transform translate-x-1/2 translate-y-1/2 lg:translate-x-1/3" width="800" height="800" fill="none" viewBox="0 0 800 800">
                         <circle cx="400" cy="400" r="400" stroke="white" strokeWidth="0.5" />
                         <circle cx="400" cy="400" r="300" stroke="white" strokeWidth="0.5" strokeDasharray="2 4"/>
                     </svg>
                 </div>
                 <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
                     <motion.h1 initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.5 }}
                         className="text-4xl sm:text-6xl font-extrabold text-white tracking-tight drop-shadow-lg">
                         Galeri Kampus
                     </motion.h1>
                     <motion.p initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.5, delay: 0.2 }}
                         className="mt-4 text-xl text-gray-200 max-w-3xl mx-auto drop-shadow-md">
                         Lihat lebih dekat berbagai momen, kegiatan, dan fasilitas unggulan di lingkungan {campus.name}.
                     </motion.p>
                 </div>
            </header>

            {/* Konten Utama */}
            <div className="relative py-16 sm:py-24" style={backgroundPatternStyle}>
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    
                    {/* Filter Buttons (menggunakan filterCategories dinamis) */}
                    {filterCategories.length > 1 && ( // Hanya tampilkan jika ada lebih dari 1 kategori (termasuk 'Semua')
                        <motion.div initial={{ opacity: 0 }} whileInView={{ opacity: 1 }} viewport={{ once: true }} transition={{ duration: 0.5, delay: 0.2 }} className="mb-12 flex justify-center flex-wrap gap-3">
                            {filterCategories.map((category) => (
                                <button
                                    key={category}
                                    onClick={() => handleFilterChange(category)}
                                    className={`px-5 py-2 text-sm font-semibold rounded-full transition-all duration-300 transform hover:scale-105
                                        ${activeFilter === category
                                            ? `${theme.primary} text-white shadow-lg`
                                            : 'bg-white text-slate-700 shadow-md hover:bg-slate-100'
                                        }`}
                                >
                                    {category}
                                </button>
                            ))}
                        </motion.div>
                    )}
                    
                    {/* Image Grid */}
                    <motion.div layout id="gallery-grid" className="mt-12 grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 sm:gap-6">
                        <AnimatePresence>
                            {currentImages.map((image) => (
                                <motion.div
                                    layout
                                    key={image.id}
                                    initial={{ opacity: 0, scale: 0.8 }}
                                    animate={{ opacity: 1, scale: 1 }}
                                    exit={{ opacity: 0, scale: 0.8 }}
                                    transition={{ type: 'spring', stiffness: 200, damping: 25 }}
                                    className="group relative aspect-[4/3] rounded-xl overflow-hidden shadow-lg cursor-pointer"
                                    onClick={() => openLightbox(image)}
                                >
                                    <img src={image.image_url} alt={image.title} className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-110" />
                                    <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-50 transition-opacity duration-300 flex items-center justify-center">
                                        <FontAwesomeIcon icon={faMagnifyingGlassPlus} className="text-white text-4xl opacity-0 group-hover:opacity-100 transform scale-50 group-hover:scale-100 transition-all duration-300" />
                                    </div>
                                    {/* Teks di bawah gambar */}
                                     <div className="absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black/70 to-transparent">
                                         <h3 className="text-white font-semibold text-sm truncate">{image.title}</h3>
                                     </div>
                                </motion.div>
                            ))}
                        </AnimatePresence>
                    </motion.div>
                    
                    {/* Fallback jika tidak ada gambar */}
                    {allImages.length === 0 ? (
                        <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}
                            className="flex flex-col items-center justify-center text-center py-12 text-gray-500">
                            <FontAwesomeIcon icon={faImages} className="text-5xl mb-4" />
                            <h2 className="text-2xl font-semibold text-gray-700">Galeri Kosong</h2>
                            <p className="mt-2">Belum ada foto yang ditambahkan ke galeri kampus ini.</p>
                        </motion.div>
                    ) : filteredImages.length === 0 && (
                             <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}
                                 className="flex flex-col items-center justify-center text-center py-12 text-gray-500">
                                 <FontAwesomeIcon icon={faExclamationTriangle} className="text-5xl mb-4" />
                                 <h2 className="text-2xl font-semibold text-gray-700">Tidak Ada Gambar</h2>
                                 <p className="mt-2">Tidak ada gambar yang cocok dengan kategori "{activeFilter}".</p>
                             </motion.div>
                    )}

                    {/* Pagination Controls */}
                    {pageCount > 1 && (
                        <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="mt-16 flex justify-center items-center space-x-2">
                            {/* Tombol "Previous" */}
                            <button
                                onClick={() => goToPage(currentPage - 1)}
                                disabled={currentPage === 1}
                                className={`w-10 h-10 rounded-full font-semibold text-sm transition-all duration-300 bg-white text-slate-700 shadow-sm hover:bg-slate-100 disabled:opacity-50 disabled:cursor-not-allowed`}
                            >
                                <FontAwesomeIcon icon={faChevronLeft} />
                            </button>

                            {/* Tombol Halaman */}
                            {Array.from({ length: pageCount }, (_, i) => i + 1).map((pageNumber) => (
                                <button
                                    key={pageNumber}
                                    onClick={() => goToPage(pageNumber)}
                                    className={`w-10 h-10 rounded-full font-semibold text-sm transition-all duration-300
                                        ${currentPage === pageNumber
                                            ? `${theme.primary} text-white shadow-md`
                                            : 'bg-white text-slate-700 shadow-sm hover:bg-slate-100'
                                        }`}
                                >
                                    {pageNumber}
                                </button>
                            ))}
                            
                            {/* Tombol "Next" */}
                            <button
                                onClick={() => goToPage(currentPage + 1)}
                                disabled={currentPage === pageCount}
                                className={`w-10 h-10 rounded-full font-semibold text-sm transition-all duration-300 bg-white text-slate-700 shadow-sm hover:bg-slate-100 disabled:opacity-50 disabled:cursor-not-allowed`}
                            >
                                <FontAwesomeIcon icon={faChevronRight} />
                            </button>
                        </motion.div>
                    )}
                </div>
            </div>

            {/* Lightbox */}
            <AnimatePresence>
                {lightboxImage && (
                    <Lightbox 
                        imageSrc={lightboxImage.src} 
                        imageTitle={lightboxImage.title} 
                        onClose={closeLightbox} 
                    />
                )}
            </AnimatePresence>
        </LandingLayout>
    );
}