import { motion } from 'framer-motion';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faChevronRight, faPhone, faInfoCircle } from '@fortawesome/free-solid-svg-icons';

// Default theme if not provided
const defaultTheme = {
    primary: 'bg-gray-600',
    textColor: 'text-gray-600',
    borderColor: 'border-gray-500',
    primaryHover: 'hover:bg-gray-700',
    shadowColor: 'hover:shadow-gray-200/50'
};

// Default timeline data if campus data is not available
const defaultTimelineData = {
    title: 'Timeline Pendaftaran',
    academicYear: 'Tahun Ajaran Terbaru',
    waves: [],
    events: []
};

// Function to convert month number to Indonesian month name
const getIndonesianMonth = (month) => {
    const months = [
        "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"
    ];
    return months[month - 1] || "";
};

// Main component to display TimelinePendaftaran
export default function TimelinePendaftaran({ campus }) {
    const timelineData = campus?.timelinePendaftaran || defaultTimelineData;
    const theme = campus?.theme || defaultTheme;
    const waveCount = timelineData.waves?.length || 0;

    // Animation Variants
    const containerVariants = { hidden: { opacity: 0 }, visible: { opacity: 1, transition: { staggerChildren: 0.15 } } };
    const itemVariants = { hidden: { opacity: 0, y: 30 }, visible: { opacity: 1, y: 0, transition: { duration: 0.6, ease: 'easeOut' } } };
    const waveCardVariants = { hidden: { opacity: 0, y: 40, scale: 0.9 }, visible: { opacity: 1, y: 0, scale: 1, transition: { type: 'spring', stiffness: 100, damping: 15 } } };
    const eventCardVariants = { hidden: { opacity: 0, x: -20 }, visible: { opacity: 1, x: 0, transition: { duration: 0.5, ease: 'easeOut' } } };

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

    return (
        <section className="bg-slate-50 py-16 sm:py-24 overflow-hidden" style={backgroundPatternStyle}>
            <motion.div 
                className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8"
                variants={containerVariants}
                initial="hidden"
                whileInView="visible"
                viewport={{ once: true, amount: 0.1 }}
            >
                {/* Title and Academic Year */}
                <motion.div variants={itemVariants} className="text-center">
                    <h2 className={`text-3xl font-extrabold ${theme.textColor} sm:text-4xl tracking-tight mb-6`}>
                        {timelineData.title}
                    </h2>
                    {timelineData.academicYear && (
                        <div className="flex justify-center">
                            <motion.span 
                                className="bg-yellow-400 text-yellow-900 font-bold text-lg px-8 py-3 rounded-full shadow-md"
                                initial={{ scale: 0 }}
                                animate={{ scale: 1 }}
                                transition={{ type: 'spring', stiffness: 200, damping: 10, delay: 0.2 }}
                            >
                                {timelineData.academicYear}
                            </motion.span>
                        </div>
                    )}
                </motion.div>

                {/* Waves Section */}
                {waveCount > 0 && (
                    <motion.div
                        className="mt-16 relative"
                        variants={itemVariants}
                    >
                        <div className="absolute top-4 left-0 w-full h-1 bg-slate-300 rounded-full"></div>
                        
                        <motion.div 
                            className={`absolute top-4 left-0 h-1 ${theme.primary} rounded-full`}
                            initial={{ scaleX: 0, originX: 0 }}
                            whileInView={{ scaleX: 1 }}
                            viewport={{ once: true }}
                            transition={{ duration: 1.5, ease: [0.25, 1, 0.5, 1], delay: 0.5 }}
                        ></motion.div>
                        
                        <div 
                            className="relative grid gap-4 md:gap-8"
                            style={{ gridTemplateColumns: `repeat(${waveCount}, minmax(0, 1fr))` }}
                        >
                            {timelineData.waves.map((wave, index) => {
                                const startDate = new Date(wave.start_date);
                                const endDate = new Date(wave.end_date);
                                const formattedStartDate = `${startDate.getDate()} ${getIndonesianMonth(startDate.getMonth() + 1)} ${startDate.getFullYear()}`;
                                const formattedEndDate = `${endDate.getDate()} ${getIndonesianMonth(endDate.getMonth() + 1)} ${endDate.getFullYear()}`;
                                return (
                                    <motion.div 
                                        key={index} 
                                        variants={waveCardVariants} 
                                        className="flex flex-col items-center pt-4"
                                    >
                                        <motion.div 
                                            className={`absolute top-4 w-4 h-4 rounded-full border-4 border-slate-50 shadow-sm ${theme.primary}`} 
                                            style={{ left: `${(100 / (waveCount * 2)) * (index * 2 + 1)}%` }}
                                            initial={{ scale: 0 }}
                                            animate={{ scale: 1 }}
                                            transition={{ type: 'spring', duration: 0.5, delay: 1.5 + (index * 0.2) }}
                                        />
                                        <motion.div 
                                            className={`w-full mt-8 p-6 text-center rounded-xl shadow-lg ${theme.primary} text-white`}
                                            whileHover={{ y: -10, scale: 1.05 }}
                                            transition={{ type: 'spring', stiffness: 300 }}
                                        >
                                            <p className="text-sm font-semibold opacity-80">{`${formattedStartDate} - ${formattedEndDate}`}</p>
                                            <h3 className="text-2xl font-bold mt-1">{wave.name}</h3>
                                        </motion.div>
                                    </motion.div>
                                );
                            })}
                        </div>
                    </motion.div>
                )}

                {/* Events Section */}
                {timelineData.events && timelineData.events.length > 0 ? (
                    <motion.div
                        className="mt-16 grid grid-cols-1 md:grid-cols-3 gap-6"
                        variants={containerVariants}
                    >
                        {timelineData.events.map((event, index) => {
                            const eventDate = new Date(event.date);
                            const formattedDate = `${eventDate.getDate()} ${getIndonesianMonth(eventDate.getMonth() + 1)} ${eventDate.getFullYear()}`;
                            return (
                                <motion.div
                                    key={index}
                                    variants={eventCardVariants}
                                    whileHover={{ scale: 1.05, y: -5 }}
                                    className={`flex items-center justify-between p-5 rounded-lg shadow-md transition-all duration-300 bg-gray-200 text-gray-700 ${theme.primaryHover} ${theme.shadowColor} hover:text-white`}
                                >
                                    <span className="font-bold text-lg">{event.name}</span>
                                    <div className="h-full w-px bg-current opacity-30 mx-4"></div>
                                    <span className="font-semibold text-md">{formattedDate}</span>
                                </motion.div>
                            );
                        })}
                    </motion.div>
                ) : (
                    <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="mt-16 text-center text-gray-500 py-10">
                        <FontAwesomeIcon icon={faInfoCircle} className="text-3xl mb-3" />
                        <p>Informasi event pendaftaran belum tersedia.</p>
                    </motion.div>
                )}
            </motion.div>

            {/* Action Buttons */}
            <motion.div
                variants={itemVariants}
                className="mt-12 flex flex-col sm:flex-row items-center justify-center gap-4"
            >
                <motion.a
                    href={`/${campus.slug}/pendaftaran`} 
                    className={`inline-flex items-center justify-center w-full sm:w-auto px-8 py-3 font-bold text-white rounded-full shadow-lg ${theme.primary}`}
                    animate={{ scale: [1, 1.03, 1] }}
                    transition={{ duration: 2, repeat: Infinity, repeatDelay: 2, ease: "easeInOut" }}
                    whileHover={{ scale: 1.05 }}
                >
                    Daftar Sekarang <FontAwesomeIcon icon={faChevronRight} className="ml-2 text-sm" />
                </motion.a>
                
                <motion.a 
                    href={`https://wa.me/${campus.whatsappNumber}`} target="_blank" rel="noopener noreferrer" 
                    className={`inline-flex items-center justify-center w-full sm:w-auto px-8 py-3 font-bold text-white rounded-full shadow-lg ${theme.primary}`}
                    whileHover={{ scale: 1.05 }}
                    transition={{ duration: 0.3 }}
                >
                    <FontAwesomeIcon icon={faPhone} className="mr-2" /> Hubungi Kami
                </motion.a>
            </motion.div>
        </section>
    );
}
