import LandingLayout from '@/Layouts/LandingLayout';
import { motion, AnimatePresence } from 'framer-motion';
import { Head } from '@inertiajs/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
    faShieldHalved, faFileInvoiceDollar, faWallet,
    faHeadset
} from '@fortawesome/free-solid-svg-icons';
import { faWhatsapp } from '@fortawesome/free-brands-svg-icons';
import { useState, useEffect, useMemo } from 'react'; // Import useMemo

export default function BiayaPage({ campus, tuitionData }) {
    // Tema fallback lengkap
    const theme = campus?.theme || {
        gradientFrom: 'from-gray-700',
        gradientTo: 'to-gray-900',
        primary: 'bg-gray-600',
        activeBg: 'bg-gray-700',
        textColor: 'text-gray-600',
        badgeBg: 'bg-gray-100',
        shadowColor: 'hover:shadow-gray-200/50',
        borderColor: 'border-gray-500'
    };

    // Data fallback lengkap
    const currentCampus = campus || { name: "Kampus Kami", whatsappNumber: '6281234567890' };
    
    // Pastikan availableTabs menggunakan useMemo
    const availableTabs = useMemo(() => tuitionData ? Object.keys(tuitionData) : [], [tuitionData]);

    const [activeTab, setActiveTab] = useState(availableTabs[0] || null);

    // Reset tab aktif jika data kampus berubah (misal ganti slug)
    useEffect(() => {
        if (availableTabs.length > 0 && !availableTabs.includes(activeTab)) {
            setActiveTab(availableTabs[0] || null);
        }
    }, [availableTabs, activeTab]);

    // Ambil data yang relevan
    const currentProgramData = tuitionData[activeTab]?.tableData || [];
    const currentRegistrationFees = tuitionData[activeTab]?.registrationFees || [];

    // Remove duplicates and keep the first entry for each registration fee type
    const uniqueRegistrationFees = Array.from(new Map(currentRegistrationFees.map(fee => [fee.type, fee])).values());

    // Varian animasi
    const containerVariants = { hidden: {}, visible: { transition: { staggerChildren: 0.05 } } }; 
    const itemVariants = { hidden: { opacity: 0, y: 10 }, visible: { opacity: 1, y: 0 } }; // Animasi geser sedikit
    const whatsappButtonVariants = {
        initial: { scale: 1 },
        animate: { scale: [1, 1.05, 1], transition: { duration: 1.5, ease: "easeInOut", repeat: Infinity, delay: 1 } },
        hover: { scale: 1.05, transition: { duration: 0.3 } }
    };

    // Style background berpola halus
    const backgroundPatternStyle = {
        backgroundImage: 'radial-gradient(circle at 1px 1px, #e2e8f0 0.5px, transparent 0)',
        backgroundSize: '20px 20px',
    };

    return (
        <LandingLayout campus={campus} title={`Rincian Biaya - ${campus.name}`}>
            <Head title={`Rincian Biaya - ${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">
                        Rincian Biaya Pendidikan
                    </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">
                        Biaya transparan dan terjangkau untuk program studi di {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">

                    {/* Jaminan Biaya & Biaya Awal */}
                    <motion.div initial={{ opacity: 0, scale: 0.95 }} whileInView={{ opacity: 1, scale: 1 }} viewport={{ once: true }} transition={{ duration: 0.5, delay: 0.1 }}
                        className="mb-12 max-w-3xl mx-auto bg-white border-2 border-green-200 rounded-xl shadow-lg p-6 flex items-start space-x-5">
                        <div className="flex-shrink-0"><FontAwesomeIcon icon={faShieldHalved} className="text-4xl text-green-500" /></div>
                        <div>
                            <h3 className="text-lg font-bold text-gray-900">Jaminan Biaya Kuliah Tetap</h3>
                            <p className="mt-1 text-gray-600">
                                Nikmati ketenangan selama masa studi. Biaya kuliah dapat diangsur bulanan dengan nominal <span className="mx-1.5 inline-block bg-green-600 text-white font-bold px-2 py-0.5 rounded-md text-sm tracking-wider">FLAT</span> hingga Anda wisuda.
                            </p>
                        </div>
                    </motion.div>
                    
                    <motion.div initial={{ opacity: 0, scale: 0.9 }} whileInView={{ opacity: 1, scale: 1 }} viewport={{ once: true }} transition={{ duration: 0.5, delay: 0.2 }} 
                        className="grid grid-cols-1 md:grid-cols-2 gap-8 mb-16 max-w-4xl mx-auto">
                        {uniqueRegistrationFees.length > 0 ? (
                            uniqueRegistrationFees.map((fee, index) => (
                                <div key={index} className={`relative bg-gradient-to-br ${fee.type === 'D3' ? 'from-rose-500 to-red-600' : 'from-sky-500 to-blue-600'} text-white p-8 rounded-xl shadow-lg transform hover:scale-105 transition-transform duration-300`}>
                                    <FontAwesomeIcon icon={faFileInvoiceDollar} className="text-4xl text-white/50 absolute top-4 right-4" />
                                    <motion.p key={fee.type} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }} transition={{ duration: 0.2 }} className="text-3xl font-bold mt-2">
                                        Biaya Pendaftaran {fee.type} <br></br>Rp {fee.fee},-
                                    </motion.p>
                                </div>
                            ))
                        ) : (
                            <div className="relative bg-gradient-to-br from-rose-500 to-red-600 text-white p-8 rounded-xl shadow-lg transform hover:scale-105 transition-transform duration-300">
                                <FontAwesomeIcon icon={faFileInvoiceDollar} className="text-4xl text-white/50 absolute top-4 right-4" />
                                <h3 className="text-xl font-bold">Biaya Pendaftaran</h3>
                                <p className="text-4xl font-bold mt-2">Tidak Tersedia</p>
                            </div>
                        )}
                        <div className="relative bg-gradient-to-br from-sky-500 to-blue-600 text-white p-8 rounded-xl shadow-lg transform hover:scale-105 transition-transform duration-300">
                            <FontAwesomeIcon icon={faWallet} className="text-4xl text-white/50 absolute top-4 right-4" />
                            <h3 className="text-xl font-bold">Biaya Awal</h3>
                            <p className="text-sm mt-2">Termasuk Angsuran ke-1, Uang Masuk, dan Kartu Tanda Mahasiswa (KTM).</p>
                        </div>
                    </motion.div>

                    {/* --- Tab "Pil" Dinamis --- */}
                    {availableTabs.length > 0 && (
                        <div className={`flex rounded-full max-w-xl mx-auto bg-slate-200 p-1`}>
                            {availableTabs.map((tab) => {
                                const isActive = activeTab === tab;
                                return (
                                    <motion.button 
                                        key={tab}
                                        onClick={() => setActiveTab(tab)}
                                        layout // ⭐ Tambahkan layout untuk transisi halus
                                        // ⭐ Styling yang membuat tombol menjadi pil aktif
                                        className={`flex-1 rounded-full py-2 text-sm font-medium transition-all duration-300 focus:outline-none 
                                            ${isActive 
                                                ? `text-white shadow-md ${theme.primary}` 
                                                : 'text-slate-700 hover:text-black bg-transparent'}`
                                            }
                                        whileHover={{ scale: 1.02 }} 
                                        whileTap={{ scale: 0.98 }}
                                    >
                                        <span className="flex items-center justify-center text-center">
                                            {tab}
                                        </span>
                                    </motion.button>
                                );
                            })}
                        </div>
                    )}
                    {/* --- Akhir Tab Dinamis --- */}

                    {/* Kontainer Tabel dengan Animasi */}
                    {activeTab && (
                        <AnimatePresence mode="wait">
                            <motion.div
                                key={activeTab} // Kunci animasi agar tabel berganti
                                variants={containerVariants}
                                initial="hidden"
                                animate="visible"
                                exit={{ opacity: 0 }}
                                className="mt-12 overflow-hidden shadow-xl rounded-lg border border-slate-200"
                            >
                                <div className="overflow-x-auto">
                                    <table className="min-w-full divide-y divide-slate-200">
                                        {/* Header Tabel Berwarna */}
                                        <thead className={`${theme.primary} text-white`}>
                                            <tr>
                                                <th scope="col" className="px-6 py-4 text-left text-xs font-semibold uppercase tracking-wider">Program Studi</th>
                                                <th scope="col" className="px-6 py-4 text-left text-xs font-semibold uppercase tracking-wider">Biaya Awal</th>
                                                <th scope="col" className="px-6 py-4 text-left text-xs font-semibold uppercase tracking-wider">Angsuran Normal / Bulan</th>
                                                <th scope="col" className="px-6 py-4 text-left text-xs font-semibold uppercase tracking-wider">Promo Angsuran / Bulan</th>
                                            </tr>
                                        </thead>
                                        {/* Body Tabel */}
                                        <tbody className="bg-white divide-y divide-slate-100">
                                            {currentProgramData.map((item, index) => (
                                                <motion.tr key={index} variants={itemVariants} className="odd:bg-white even:bg-slate-50 hover:bg-slate-100/50 transition-colors duration-200">
                                                    <td className="px-6 py-4 whitespace-nowrap text-sm font-semibold text-slate-800">{item.major}</td>
                                                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600">Rp {item.initialFee}</td>
                                                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 line-through">Rp {item.oldMonthlyFee} /bulan</td>
                                                    <td className={`px-6 py-4 whitespace-nowrap text-lg font-bold ${theme.textColor}`}>Rp {item.newMonthlyFee} /bulan</td>
                                                </motion.tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            </motion.div>
                        </AnimatePresence>
                    )}
                </div>

                {/* CTA (Tidak ada perubahan) */}
                <motion.div initial={{ opacity: 0, y: 50 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, amount: 0.5 }} transition={{ duration: 0.6, ease: "easeOut" }}
                    className="mt-24 max-w-xl lg:max-w-2xl mx-auto">
                    <motion.div className={`relative bg-white rounded-3xl shadow-2xl border-b-4 ${theme.borderColor} overflow-hidden p-8 md:p-10 text-center transform hover:scale-105 transition-all duration-500 ease-in-out`} whileHover={{ y: -5 }}>
                        <div className="absolute inset-0 bg-gradient-to-tr from-blue-100/50 via-white/0 to-blue-100/50 opacity-40 rounded-3xl pointer-events-none"></div>
                        <FontAwesomeIcon icon={faHeadset} className={`text-5xl mb-4 animate-bounce ${theme.textColor}`} />
                        <h3 className="text-2xl sm:text-3xl font-extrabold text-gray-900 leading-tight">Punya Pertanyaan Seputar Pendaftaran?</h3>
                        <p className="mt-3 text-lg text-gray-600 max-w-md mx-auto">
                            Tim kami siap membantu Anda. Hubungi kami via WhatsApp untuk respon cepat dan informasi lengkap tentang <span className={`font-semibold ${theme.textColor}`}>{currentCampus.name}</span>.
                        </p>
                        <motion.a href={`https://wa.me/${currentCampus.whatsappNumber}`} target="_blank" rel="noopener noreferrer"
                            className="mt-8 inline-flex items-center justify-center bg-gradient-to-r from-green-500 to-green-600 text-white font-bold py-3.5 px-8 rounded-full shadow-lg hover:shadow-xl transform active:scale-95 transition-all duration-300 ease-in-out focus:outline-none focus:ring-4 focus:ring-green-300"
                            variants={whatsappButtonVariants} initial="initial" animate="animate" whileHover="hover">
                            <FontAwesomeIcon icon={faWhatsapp} className="text-2xl mr-3" />
                            <span>Tanya via WhatsApp</span>
                        </motion.a>
                    </motion.div>
                </motion.div>
            </div>
        </LandingLayout>
    );
}