import LandingLayout from '@/Layouts/LandingLayout';
import { motion, AnimatePresence } from 'framer-motion';
import { Head } from '@inertiajs/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faChevronDown, faGraduationCap, faExclamationTriangle, faArchive } from '@fortawesome/free-solid-svg-icons';
import { useState } from 'react';

/**
 * ==================================================================
 * PERUBAHAN UTAMA: Komponen Accordion Didesain Ulang
 * ==================================================================
 * - Tombol header tidak lagi menampilkan Total SKS.
 * - Konten accordion sekarang berisi tabel penuh.
 * - Tabel memiliki header (thead) berwarna sesuai tema.
 * - Tabel memiliki footer (tfoot) untuk menampilkan Total SKS.
 */
const SemesterAccordion = ({ title, courses, theme }) => {
    const [isOpen, setIsOpen] = useState(false); // Default tertutup

    // Hitung Total SKS per semester
    const totalSKS = courses.reduce((acc, course) => acc + (course.sks || 0), 0);

    return (
        // Sekarang, seluruh accordion adalah satu kartu besar
        <div className="bg-white rounded-xl shadow-lg overflow-hidden border border-slate-200">
            {/* Tombol Accordion (Header Kartu) */}
            <button
                onClick={() => setIsOpen(!isOpen)}
                className="w-full flex justify-between items-center p-5 text-left transition-colors duration-200 hover:bg-slate-50/50"
            >
                <span className="text-xl font-semibold text-gray-800">{title}</span>
                <FontAwesomeIcon
                    icon={faChevronDown}
                    className={`text-lg transition-transform duration-300 ${theme.textColor} ${isOpen ? 'rotate-180' : ''}`}
                />
            </button>
            
            {/* Konten Accordion (Tabel Berwarna) */}
            <AnimatePresence>
                {isOpen && (
                    <motion.div
                        initial={{ height: 0, opacity: 0 }}
                        animate={{ height: 'auto', opacity: 1 }}
                        exit={{ height: 0, opacity: 0 }}
                        transition={{ duration: 0.3, ease: 'easeOut' }}
                        className="overflow-hidden" // Biarkan overflow-hidden di sini untuk animasi
                    >
                        {/* Wrapper untuk overflow horizontal di mobile */}
                        <div className="overflow-x-auto">
                            <table className="min-w-full">
                                {/* Header Tabel Berwarna Sesuai Tema */}
                                <thead className={`${theme.primary} text-white`}>
                                    <tr>
                                        <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider">Kode MK</th>
                                        <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider">Mata Kuliah</th>
                                        <th className="px-6 py-3 text-center text-xs font-semibold uppercase tracking-wider">SKS</th>
                                    </tr>
                                </thead>
                                
                                {/* Body Tabel dengan Zebra-Striping */}
                                <tbody className="bg-white divide-y divide-slate-200">
                                    {courses.map((course, index) => (
                                        <tr key={index} className="odd:bg-white even:bg-slate-50 hover:bg-slate-100 transition-colors">
                                            <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{course.code}</td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600">{course.name}</td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700 text-center font-semibold">{course.sks}</td>
                                        </tr>
                                    ))}
                                </tbody>
                                
                                {/* Footer Tabel (Total SKS) */}
                                <tfoot className="bg-slate-100 border-t-2 border-slate-300">
                                    <tr>
                                        <td colSpan="2" className="px-6 py-3 text-right text-sm font-bold text-gray-800 uppercase">Total SKS Semester</td>
                                        <td className={`px-6 py-3 text-center text-xl font-extrabold ${theme.textColor}`}>
                                            {totalSKS}
                                        </td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </motion.div>
                )}
            </AnimatePresence>
        </div>
    );
};
/* ================================================================== */
/* AKHIR PERUBAHAN                                                    */
/* ================================================================== */


/**
 * Halaman Utama Kurikulum (Tidak ada perubahan signifikan di sini)
 */
export default function KurikulumPage({ campus, content, majorsList }) {
    // 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',
    };
    
    // Data fallback lengkap
    const pageTitle = content?.title || "Kurikulum Kampus";
    const pageDescription = content?.description || "Informasi belum tersedia.";
    const curriculumData = content?.majorsData || {};
    const majorNames = majorsList || []; // Mengambil dari props level atas

    // State untuk melacak tab jurusan yang aktif
    const [activeMajor, setActiveMajor] = useState(majorNames[0] || null);

    // 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={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"/>
                        <circle cx="400" cy="400" r="200" stroke="white" strokeWidth="0.5" />
                    </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 */}
             <div className="relative py-16 sm:py-24" style={backgroundPatternStyle}>
                <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
                    
                    {majorNames.length > 0 ? (
                        <>
                            {/* Tab Pilihan Jurusan (Fleksibel) */}
                            <div className="mb-12">
                                <h2 className="text-2xl font-bold text-gray-800 text-center mb-6">Pilih Program Studi</h2>
                                {/* Container tab 'pil' yang fleksibel */}
                                <motion.div 
                                    initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.3 }}
                                    className="flex flex-wrap justify-center gap-3"
                                >
                                    {majorNames.map((majorName) => (
                                        <button
                                            key={majorName}
                                            onClick={() => setActiveMajor(majorName)}
                                            className={`px-5 py-2 text-sm font-semibold rounded-full transition-all duration-300 transform hover:scale-105
                                                        ${activeMajor === majorName 
                                                            ? `${theme.primary} text-white shadow-lg` // Styling aktif
                                                            : 'bg-white text-slate-700 shadow-md hover:bg-slate-100' // Styling non-aktif
                                                        }`}
                                        >
                                            {majorName}
                                        </button>
                                    ))}
                                </motion.div>
                            </div>

                            {/* Accordion Semester (sesuai tab aktif) */}
                            <AnimatePresence mode="wait">
                                <motion.div
                                    key={activeMajor} // Kunci animasi agar berganti saat tab di-klik
                                    initial={{ opacity: 0, y: 20 }}
                                    animate={{ opacity: 1, y: 0 }}
                                    exit={{ opacity: 0, y: -20 }}
                                    transition={{ duration: 0.3 }}
                                    className="space-y-4" // Ganti dari kartu putih tunggal menjadi container
                                >
                                    {/* Cek jika ada data kurikulum untuk major yang aktif */}
                                    {curriculumData[activeMajor] ? (
                                        curriculumData[activeMajor].map((semester, index) => (
                                            <SemesterAccordion
                                                key={index}
                                                title={semester.semester}
                                                courses={semester.courses}
                                                theme={theme}
                                            />
                                        ))
                                    ) : (
                                        <p className="text-center text-gray-500">Data kurikulum untuk jurusan ini tidak ditemukan.</p>
                                    )}
                                </motion.div>
                            </AnimatePresence>
                        </>
                    ) : (
                        // Fallback jika tidak ada data jurusan
                        <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">
                            <FontAwesomeIcon icon={faExclamationTriangle} className="text-5xl mb-4" />
                            <h2 className="text-2xl font-semibold text-gray-700">Kurikulum Belum Tersedia</h2>
                            <p className="mt-2">Informasi kurikulum untuk kampus ini sedang dalam pembaruan.</p>
                        </motion.div>
                    )}
                </div>
            </div>
        </LandingLayout>
    );
}