import React, { useState } from 'react';
import EventBookingModal from '@/Components/EventBookingModal';
import { motion } from 'framer-motion';
import HomeLayout from '@/Layouts/HomeLayout';
import EventCard from '@/Components/EventCard';

// --- Default Mock Data for Demonstration ---
const defaultEvents = [
    {
        id: 1,
        title: 'Introduction to Pregnancy: The First Trimester',
        description: 'A foundational course covering early pregnancy signs, nutrition, and prenatal care basics for new parents.',
        image_url: 'https://images.unsplash.com/photo-1576091160550-2173dba999ef?q=80&w=2940&auto=format&fit=crop',
        date: '2024-09-25T18:00:00Z',
        location: 'Online via Zoom',
        price: 0,
        instructor: 'Dr. Sarah Johnson',
        duration: '2 hours',
        category: 'Pregnancy Basics'
    },
    {
        id: 2,
        title: 'Hypnobirthing & Pain Management Workshop',
        description: 'Learn proven techniques for a calm, positive, and empowered birthing experience. A full-day intensive workshop.',
        image_url: 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?q=80&w=2940&auto=format&fit=crop',
        date: '2024-10-12T09:00:00Z',
        location: 'Community Wellness Center, 123 Main St',
        price: 150,
        instructor: 'Emma Williams, Certified Hypnobirthing Coach',
        duration: 'Full day',
        category: 'Childbirth Preparation'
    },
    {
        id: 3,
        title: 'Newborn Care Essentials',
        description: 'Master the essential skills for caring for your newborn in the first few weeks. Hands-on practice included.',
        image_url: 'https://images.unsplash.com/photo-1576078138256-5495b9a4d65d?q=80&w=2940&auto=format&fit=crop',
        date: '2024-11-05T14:00:00Z',
        location: 'Online via Zoom',
        price: 0,
        instructor: 'Nurse Rachel Thompson',
        duration: '3 hours',
        category: 'Newborn Care'
    },
    {
        id: 4,
        title: 'Partner Support & Labor Prep',
        description: 'An essential class for partners on how to provide effective physical and emotional support during labor.',
        image_url: 'https://images.unsplash.com/photo-1513475382585-d06e58bcb0e0?q=80&w=2940&auto=format&fit=crop',
        date: '2024-10-20T10:00:00Z',
        location: 'In-Person at The Family Hub',
        price: 75,
        instructor: 'Michael Chen, Doula',
        duration: '4 hours',
        category: 'Partner Support'
    },
    {
        id: 5,
        title: 'Postpartum Recovery & Self-Care',
        description: 'Focus on healing, nutrition, and mental wellness after childbirth. Learn strategies for a smooth recovery.',
        image_url: 'https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?q=80&w=2940&auto=format&fit=crop',
        date: '2024-11-15T13:00:00Z',
        location: 'Online via Zoom',
        price: 0,
        instructor: 'Dr. Lisa Martinez',
        duration: '2.5 hours',
        category: 'Postpartum Care'
    },
    {
        id: 6,
        title: 'Breastfeeding Fundamentals',
        description: 'Learn proper latch techniques, positions, and troubleshooting common breastfeeding challenges.',
        image_url: 'https://images.unsplash.com/photo-1576078138256-5495b9a4d65d?q=80&w=2940&auto=format&fit=crop',
        date: '2024-12-01T10:00:00Z',
        location: 'In-Person at The Family Hub',
        price: 50,
        instructor: 'Lactation Consultant Jennifer Adams',
        duration: '3 hours',
        category: 'Feeding & Nutrition'
    }
];

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

// --- Main Component: EventsSection ---
const Events = ({ events = defaultEvents }) => {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [selectedEvent, setSelectedEvent] = useState(null);
    const [priceFilter, setPriceFilter] = useState('all'); // all, free, paid

    const handleBookClick = (event) => {
        setSelectedEvent(event);
        setIsModalOpen(true);
    };

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

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

    // Filter events based on price filter
    const filteredEvents = events.filter(event => {
        if (priceFilter === 'free') {
            return event.type === "free";
        } else if (priceFilter === 'paid') {
            return event.type === "paid";
        }
        return true; // 'all' view
    });

    // Format date for display
    const formatDate = (dateString) => {
        const options = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' };
        return new Date(dateString).toLocaleDateString(undefined, options);
    };

    // Format time for display
    const formatTime = (dateString) => {
        const options = { hour: 'numeric', minute: '2-digit' };
        return new Date(dateString).toLocaleTimeString(undefined, options);
    };

    return (
        <HomeLayout>
            {/* Hero Section with Green Gradient */}
            <div className="relative bg-gradient-to-br from-emerald-900 via-green-800 to-teal-900 overflow-hidden">
                {/* Decorative Elements */}
                <div className="absolute inset-0 bg-black opacity-20"></div>
                <div className="absolute top-0 right-0 w-96 h-96 bg-emerald-500 rounded-full filter blur-3xl opacity-10 -translate-y-1/2 translate-x-1/2"></div>
                <div className="absolute bottom-0 left-0 w-96 h-96 bg-teal-500 rounded-full filter blur-3xl opacity-10 translate-y-1/2 -translate-x-1/2"></div>
                
                <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-24 text-center">
                    <h1 className="text-5xl md:text-6xl font-extrabold tracking-tight text-white mb-6">
                        Upcoming Events & Workshops
                    </h1>
                    <p className="text-xl md:text-2xl text-green-100 max-w-3xl mx-auto mb-8">
                        Join our expert-led sessions designed to support you through your pregnancy and parenting journey
                    </p>
                </div>
            </div>
            
            {/* Price Filter Selector */}
            <div className="bg-white shadow-sm border-b border-gray-100 sticky top-0 z-10">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
                    <div className="flex flex-col md:flex-row gap-4 items-center justify-between">
                        <div className="flex gap-2">
                            <button
                                onClick={() => setPriceFilter('all')}
                                className={`px-6 py-3 rounded-full text-sm font-medium transition-all ${
                                    priceFilter === 'all'
                                        ? 'bg-emerald-600 text-white shadow-md transform scale-105'
                                        : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                                }`}
                            >
                                All Events
                            </button>
                            <button
                                onClick={() => setPriceFilter('free')}
                                className={`px-6 py-3 rounded-full text-sm font-medium transition-all ${
                                    priceFilter === 'free'
                                        ? 'bg-emerald-600 text-white shadow-md transform scale-105'
                                        : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                                }`}
                            >
                                Free Events
                            </button>
                            <button
                                onClick={() => setPriceFilter('paid')}
                                className={`px-6 py-3 rounded-full text-sm font-medium transition-all ${
                                    priceFilter === 'paid'
                                        ? 'bg-emerald-600 text-white shadow-md transform scale-105'
                                        : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                                }`}
                            >
                                Paid Events
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            {/* Events Section */}
            <section className="bg-gray-50 py-16" id="events">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="text-center mb-12">
                        <h2 className="text-3xl font-bold text-gray-800 mb-4">
                            {priceFilter === 'all' ? 'All Events' : priceFilter === 'free' ? 'Free Events' : 'Paid Events'}
                        </h2>
                        <p className="text-lg text-gray-600 max-w-2xl mx-auto">
                            {priceFilter === 'all' 
                                ? 'Browse all our upcoming events and workshops' 
                                : priceFilter === 'free' 
                                ? 'Explore our free events and workshops' 
                                : 'Discover our premium paid events and workshops'}
                        </p>
                    </div>
                    
                    {/* Events 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 }}
                    >
                        {filteredEvents.length > 0 ? (
                            filteredEvents.map((event) => (
                                <motion.div
                                    key={event.id}
                                    className="bg-white rounded-xl shadow-lg overflow-hidden transform transition-all duration-300 hover:-translate-y-2 hover:shadow-2xl"
                                    whileHover={{ scale: 1.02 }}
                                >
                                    <EventCard
                                        key={event.id} 
                                        event={event} 
                                        onBookClick={handleBookClick}
                                    />
                                </motion.div>
                            ))
                        ) : (
                            <div className="col-span-full text-center py-16 bg-white rounded-lg shadow-sm">
                                <div className="mx-auto w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mb-4">
                                    <svg className="h-12 w-12 text-gray-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <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>
                                </div>
                                <h3 className="text-xl font-medium text-gray-900 mb-2">No events found</h3>
                                <p className="text-gray-500 max-w-md mx-auto">
                                    {priceFilter === 'all' 
                                        ? 'No events are scheduled at this time. Please check back later.' 
                                        : priceFilter === 'free' 
                                        ? 'No free events are scheduled at this time. Please check back later.' 
                                        : 'No paid events are scheduled at this time. Please check back later.'}
                                </p>
                                <button 
                                    onClick={() => setPriceFilter('all')}
                                    className="mt-6 px-6 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors"
                                >
                                    View All Events
                                </button>
                            </div>
                        )}
                    </motion.div>
                </div>
            </section>
            
            {/* Testimonials Section */}
            <div className="py-16 bg-white">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="text-center mb-12">
                        <h2 className="text-3xl font-bold text-gray-800 mb-4">What Parents Say</h2>
                        <p className="text-lg text-gray-600 max-w-2xl mx-auto">
                            Hear from parents who have attended our events and workshops
                        </p>
                    </div>
                    
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
                        {[
                            {
                                name: 'Emily Rodriguez',
                                event: 'Hypnobirthing Workshop',
                                comment: 'The techniques I learned were invaluable. I felt so prepared and empowered during my birth experience.',
                                rating: 5
                            },
                            {
                                name: 'Michael Chen',
                                event: 'Partner Support Class',
                                comment: 'This class gave me the confidence and skills to support my partner through labor. Highly recommend for all partners!',
                                rating: 5
                            },
                            {
                                name: 'Sarah Johnson',
                                event: 'Newborn Care Essentials',
                                comment: 'As a first-time mom, I was so nervous. This class gave me practical skills and peace of mind.',
                                rating: 5
                            }
                        ].map((testimonial, index) => (
                            <div key={index} className="bg-gray-50 p-6 rounded-lg shadow-sm">
                                <div className="flex items-center mb-4">
                                    {[...Array(testimonial.rating)].map((_, i) => (
                                        <svg key={i} className="h-5 w-5 text-yellow-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                            <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                                        </svg>
                                    ))}
                                </div>
                                <p className="text-gray-600 italic mb-4">"{testimonial.comment}"</p>
                                <div>
                                    <p className="font-semibold text-gray-800">{testimonial.name}</p>
                                    <p className="text-sm text-gray-500">{testimonial.event}</p>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            </div>

            <EventBookingModal
                event={selectedEvent}
                onClose={handleCloseModal}
                onSubmit={handleBookingSubmit}
            />
        </HomeLayout>
    );
};

export default Events;