import React, { useState } from 'react';
import { Head } from '@inertiajs/react';
import HomeLayout from '@/Layouts/HomeLayout';
import SchoolModal from '@/Components/SchoolModal';
import { motion } from 'framer-motion';

// --- Animation Configuration ---
const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
        opacity: 1,
        transition: {
            staggerChildren: 0.1,
            delayChildren: 0.2,
        },
    },
};

const itemVariants = {
    hidden: { y: 20, opacity: 0 },
    visible: {
        y: 0,
        opacity: 1,
        transition: { duration: 0.5, ease: "easeOut" },
    },
};

const SchoolServiceCard = ({ service, onBookClick }) => {
    const formatDate = (dateString) => {
        const options = { year: 'numeric', month: 'short', day: 'numeric' };
        return new Date(dateString).toLocaleDateString(undefined, options);
    };

    const mainImageUrl = service.image_urls && service.image_urls.length > 0 
        ? service.image_urls[0] 
        : `https://placehold.co/600x400/E2E8F0/475569?text=${encodeURIComponent(service.title)}`;

    return (
        <motion.div
            className="bg-white rounded-lg border border-gray-200 overflow-hidden shadow-sm hover:shadow-lg transition-shadow duration-300"
            variants={itemVariants}
            whileHover={{ y: -4 }}
        >
            {/* Service Image */}
            <div className="relative h-48 bg-gray-100">
                <img
                    src={mainImageUrl}
                    alt={service.title}
                    className="w-full h-full object-cover"
                    onError={(e) => {
                        e.target.onerror = null;
                        e.target.src = `https://placehold.co/600x400/E2E8F0/475569?text=${encodeURIComponent(service.title)}`;
                    }}
                />
                {/* Price/Type Badge */}
                <div className="absolute top-4 right-4">
                    {service.type === 'paid' ? (
                        <span className="bg-slate-800 text-white text-xs font-semibold px-2.5 py-1 rounded">
                            ₵{service.price}
                        </span>
                    ) : (
                        <span className="bg-emerald-100 text-emerald-800 text-xs font-semibold px-2.5 py-1 rounded">
                            Free
                        </span>
                    )}
                </div>
            </div>

            {/* Service Details */}
            <div className="p-6">
                <h3 className="text-xl font-bold text-slate-900 mb-3 leading-tight">{service.title}</h3>
                
                <ul className="text-sm text-slate-600 space-y-2 mb-4">
                    <li className="flex items-center">
                        <svg className="w-4 h-4 mr-2 text-emerald-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" /></svg>
                        Starts: {formatDate(service.start_date)}
                    </li>
                    <li className="flex items-center">
                        <svg className="w-4 h-4 mr-2 text-emerald-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" /><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" /></svg>
                        {service.location}
                    </li>
                </ul>
                
                <p className="text-slate-600 text-sm mb-5 line-clamp-2">{service.description}</p>
                
                <motion.button
                    className="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-medium py-2.5 px-4 rounded-md transition-colors duration-200"
                    whileHover={{ scale: 1.02 }}
                    whileTap={{ scale: 0.98 }}
                    onClick={() => onBookClick(service)}
                >
                    {service.type === 'paid' ? 'Enroll Now' : 'Register for Free'}
                </motion.button>
            </div>
        </motion.div>
    );
};

// --- Main Component: SchoolPage ---
export default function SchoolPage({ schoolServices }) {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [selectedSchool, setSelectedSchool] = useState(null);

    const handleBookClick = (service) => {
        setSelectedSchool(service);
        setIsModalOpen(true);
    };

    const handleCloseModal = () => {
        setIsModalOpen(false);
        setSelectedSchool(null);
    };

    const handleBookingSubmit = (bookingData) => {
        console.log('School booking submitted:', bookingData);
        // Here you would typically handle the form submission, e.g., send to a backend API
        handleCloseModal();
    };

    return (
        <HomeLayout>
            <Head title="School Services" />
            <section className="bg-slate-50 py-16 md:py-24" id="school-services">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <h1 className="text-4xl font-bold text-gray-800 mb-12 text-center">Our School Programs</h1>

                    {/* School Services Grid */}
                    <motion.div
                        className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8"
                        variants={containerVariants}
                        initial="hidden"
                        whileInView="visible"
                        viewport={{ once: true, amount: 0.1 }}
                    >
                        {schoolServices && schoolServices.length > 0 ? (
                            schoolServices.map((service) => (
                                <SchoolServiceCard key={service.id} service={service} onBookClick={handleBookClick} />
                            ))
                        ) : (
                            <div className="col-span-full text-center py-12">
                                <p className="text-lg text-slate-500">No school programs are available at this time. Please check back later.</p>
                            </div>
                        )}
                    </motion.div>
                </div>

                <SchoolModal
                    school={selectedSchool}
                    isOpen={isModalOpen}
                    onClose={handleCloseModal}
                    onBook={handleBookingSubmit}
                />
            </section>
        </HomeLayout>
    );
}
