import LandingLayout from '@/Layouts/LandingLayout';
import { motion, AnimatePresence } from 'framer-motion';
import { Head } from '@inertiajs/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faDownload, faEye, faExclamationTriangle, faXmark } from '@fortawesome/free-solid-svg-icons';
import { useState } from 'react';
// Pastikan komponen Lightbox Anda ada di path ini
import Lightbox from '@/Components/LandingPage/Lightbox'; 

// ========================================================================
// --- Komponen Kartu Brosur (Reusable) ---
// ========================================================================

/**
 * @param {{ imageUrl: string, title: string, onImageClick: function, onDownloadClick: string, theme: Object }} props
 */
const BrosurCard = ({ imageUrl, title, onImageClick, onDownloadClick, theme }) => (
    <motion.div
        initial={{ opacity: 0, y: 30, scale: 0.95 }}
        whileInView={{ opacity: 1, y: 0, scale: 1 }}
        viewport={{ once: true }}
        transition={{ duration: 0.6, ease: 'easeOut' }}
        className="bg-white rounded-2xl shadow-xl overflow-hidden group border border-slate-200 flex flex-col"
    >
        {/* Bagian Gambar (Klik untuk Lightbox) */}
        <div
            className="relative cursor-pointer overflow-hidden"
            onClick={onImageClick}
        >
            <img
                src={imageUrl}
                alt={title}
                className="w-full h-auto object-contain transition-transform duration-500 ease-in-out group-hover:scale-105"
            />
            {/* Overlay saat hover */}
            <div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex flex-col items-center justify-center text-white p-4">
                <FontAwesomeIcon icon={faEye} className="text-5xl" />
                <span className="mt-2 font-semibold">Lihat Gambar</span>
            </div>
        </div>
        
        {/* Tombol Download di bawah kartu */}
        <div className="p-6 text-center mt-auto">
            <a
                href={onDownloadClick} // Gunakan prop untuk link download
                download // Atribut HTML5 untuk memaksa download
                className={`inline-flex items-center justify-center px-6 py-3 text-base font-semibold text-white ${theme.primary} ${theme.primaryHover} rounded-full shadow-lg transform transition-all duration-300 hover:scale-105`}
            >
                <FontAwesomeIcon icon={faDownload} className="mr-2" />
                Download {title}
            </a>
        </div>
    </motion.div>
);


// ========================================================================
// --- Halaman Utama Brosur ---
// ========================================================================

/**
 * @param {{ campus: Object, content: { title: string, frontUrl: string, backUrl: string, description: string } }} props
 */
export default function BrosurPage({ campus, content }) {
    // Tema
    const theme = campus?.theme || {
        gradientFrom: 'from-gray-700',
        gradientTo: 'to-gray-900',
        primary: 'bg-gray-600',
        primaryHover: 'hover:bg-gray-700',
    };

    // Destructuring konten dari controller
    // Menggunakan nama yang sesuai: frontUrl dan backUrl
    const { title, frontUrl, backUrl, description } = content || {};
    const pageTitle = title || "Brosur Kampus";
    const pageDescription = description || "Unduh brosur kampus untuk menjelajahi program studi, fasilitas, dan layanan terbaik kami.";

    // State untuk Lightbox
    const [lightboxImage, setLightboxImage] = useState(null);
    const closeLightbox = () => setLightboxImage(null);

    // Style background berpola halus
    const backgroundPatternStyle = {
        backgroundImage: 'radial-gradient(circle at 1px 1px, #e2e8f0 0.5px, transparent 0)',
        backgroundSize: '20px 20px',
    };

    /**
     * Fungsi untuk mengunduh kedua gambar (front & back)
     */
    const handleDownloadAll = () => {
        if (!frontUrl || !backUrl) return;

        // Helper untuk membuat link dan mengklik (untuk memicu download)
        const downloadImage = (url, filename) => {
            const link = document.createElement('a');
            link.href = url;
            link.download = filename || 'brosur.png'; // Nama file download default
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        };

        // Mengambil nama file yang layak untuk download
        const getFilename = (url, suffix) => {
            const defaultName = `brosur_${suffix}.jpg`;
            try {
                // Mencoba mengambil nama file dari URL, jika tidak, gunakan default
                const urlParts = new URL(url).pathname.split('/');
                return urlParts.pop() || defaultName;
            } catch (error) {
                return defaultName;
            }
        };

        const frontFilename = getFilename(frontUrl, 'depan');
        const backFilename = getFilename(backUrl, 'belakang');

        // Download gambar pertama
        downloadImage(frontUrl, frontFilename);
        
        // Download gambar kedua setelah jeda singkat (500ms) untuk menghindari browser blocking
        setTimeout(() => {
            downloadImage(backUrl, backFilename);
        }, 500);
    };

    return (
        <LandingLayout campus={campus} title={pageTitle}>
            <Head title={pageTitle} />
            
            {/* 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"
                    >
                        {pageTitle}
                    </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"
                    >
                        {pageDescription}
                    </motion.p>
                </div>
            </header>

            {/* Konten Utama - Grid Brosur */}
            <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">
                    
                    {frontUrl && backUrl ? (
                        <>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-12 lg:gap-16 justify-center max-w-4xl mx-auto">
                                {/* Card Brosur Depan */}
                                <BrosurCard
                                    imageUrl={frontUrl}
                                    title="Sisi Depan"
                                    onImageClick={() => setLightboxImage(frontUrl)}
                                    onDownloadClick={frontUrl}
                                    theme={theme}
                                />
                                
                                {/* Card Brosur Belakang */}
                                <BrosurCard
                                    imageUrl={backUrl}
                                    title="Sisi Belakang"
                                    onImageClick={() => setLightboxImage(backUrl)}
                                    onDownloadClick={backUrl}
                                    theme={theme}
                                />
                            </div>

                            {/* Tombol Download Semua */}
                            <motion.div
                                initial={{ opacity: 0, y: 20 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} transition={{ duration: 0.6, delay: 0.4 }}
                                className="mt-16 text-center"
                            >
                                <button
                                    onClick={handleDownloadAll}
                                    className={`inline-flex items-center justify-center px-8 py-4 text-lg font-semibold text-white ${theme.primary} ${theme.primaryHover} rounded-full shadow-lg transform transition-all duration-300 hover:scale-105`}
                                >
                                    <FontAwesomeIcon icon={faDownload} className="mr-3" />
                                    Download Semua Gambar (Depan & Belakang)
                                </button>
                            </motion.div>
                        </>
                    ) : (
                        // Fallback jika tidak ada data brosur
                        <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}
                            className="flex flex-col items-center justify-center text-center p-12 bg-white rounded-lg shadow-lg text-gray-500 max-w-lg mx-auto">
                            <FontAwesomeIcon icon={faExclamationTriangle} className="text-5xl mb-4" />
                            <h2 className="text-2xl font-semibold text-gray-700">Brosur Belum Tersedia</h2>
                            <p className="mt-2">{pageDescription}</p>
                        </motion.div>
                    )}

                </div>
            </div>

            {/* Render Lightbox */}
            <AnimatePresence>
                {lightboxImage && (
                    <Lightbox imageSrc={lightboxImage} onClose={closeLightbox} />
                )}
            </AnimatePresence>
        </LandingLayout>
    );
}