import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { FaCalendarAlt, FaMoneyBillWave, FaMapMarkerAlt, FaChalkboardTeacher, FaTimes, FaExpand, FaChevronLeft, FaChevronRight, FaSearchPlus, FaClock, FaUsers, FaStar } from 'react-icons/fa';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation, Pagination, Autoplay, EffectFade, Thumbs, Keyboard } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import 'swiper/css/effect-fade';
import 'swiper/css/thumbs';

// --- Reusable Components/Utilities ---

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

// Date formatting utility
const formatDate = (dateString) => {
    if (!dateString) return null;
    
    try {
        const date = new Date(dateString);
        // Check if date is valid
        if (isNaN(date.getTime())) return null;
        
        const options = { year: 'numeric', month: 'long', day: 'numeric' };
        return date.toLocaleDateString('en-US', options);
    } catch (error) {
        console.error('Error formatting date:', error);
        return null;
    }
};

// Icon Detail Component with enhanced styling
const DetailItem = ({ icon: Icon, text, colorClass = "text-green-500", bgColorClass = "bg-green-50" }) => (
    <div className={`flex items-center p-2 rounded-lg ${bgColorClass} transition-all duration-300 hover:shadow-md`}>
        <div className={`p-2 rounded-full ${bgColorClass} mr-3`}>
            <Icon className={`h-4 w-4 ${colorClass}`} />
        </div>
        <span className="text-sm text-gray-700 truncate">{text}</span>
    </div>
);

// Rating Component
const RatingDisplay = ({ rating, reviews }) => (
    <div className="flex items-center">
        <div className="flex text-yellow-400">
            {[...Array(5)].map((_, i) => (
                <FaStar key={i} className={`text-sm ${i < rating ? "text-yellow-400" : "text-gray-300"}`} />
            ))}
        </div>
        <span className="ml-2 text-xs text-gray-500">({reviews} reviews)</span>
    </div>
);

// --- School Card Component ---

const SchoolCard = ({ school, onOpenModal }) => {
    const [thumbsSwiper, setThumbsSwiper] = useState(null);
    const [isZoomed, setIsZoomed] = useState(false);
    const [currentImageIndex, setCurrentImageIndex] = useState(0);
    
    // Fallback for ID and Images
    const cardId = `school-card-${school.id || Math.random().toString(36).substr(2, 9)}`;
    const imageUrls = school.image_urls || [];
    const allImages = [...imageUrls];
    
    // Format the date properly
    const formattedDate = formatDate(school.start_date);
    
    // Determine if the school is paid
    const isPaid = school.type === 'paid';

    const handleImageClick = () => {
        setIsZoomed(true);
    };

    const closeZoom = () => {
        setIsZoomed(false);
    };

    return (
        <>
            <motion.div 
                className="group relative overflow-hidden rounded-3xl bg-white transition-all duration-500 cursor-pointer shadow-xl border border-gray-100"
                variants={itemVariants}
                whileHover={{
                    y: -8,
                    boxShadow: "0 25px 50px -12px rgba(16, 185, 129, 0.25), 0 10px 15px -3px rgba(16, 185, 129, 0.1)"
                }} 
                whileTap={{ scale: 0.99 }}
            >
                <div className="relative overflow-hidden">
                    {/* School Image Swiper with enhanced styling */}
                    <div className="relative h-64 overflow-hidden">
                        {allImages.length > 0 ? (
                            <div className="relative h-full">
                                <Swiper
                                    key={cardId}
                                    modules={[Navigation, Pagination, Autoplay, EffectFade, Thumbs, Keyboard]}
                                    navigation={{
                                        nextEl: `.swiper-button-next-custom-${cardId}`,
                                        prevEl: `.swiper-button-prev-custom-${cardId}`,
                                    }}
                                    pagination={{
                                        clickable: true,
                                        dynamicBullets: true,
                                    }}
                                    autoplay={{
                                        delay: 3500,
                                        disableOnInteraction: false,
                                        pauseOnMouseEnter: true
                                    }}
                                    effect="fade"
                                    fadeEffect={{ crossFade: true }}
                                    thumbs={{ swiper: thumbsSwiper }}
                                    keyboard={{ enabled: true, onlyInViewport: true }}
                                    loop={true}
                                    onSlideChange={(swiper) => setCurrentImageIndex(swiper.realIndex)}
                                    className="h-full"
                                    style={{
                                        '--swiper-pagination-color': '#10b981',
                                        '--swiper-pagination-bullet-inactive-color': '#d1d5db',
                                        '--swiper-pagination-bullet-size': '6px',
                                        '--swiper-pagination-bullet-horizontal-gap': '3px'
                                    }}
                                >
                                    {allImages.map((image, index) => (
                                        <SwiperSlide key={`${cardId}-${index}`}>
                                            <div className="relative h-full overflow-hidden">
                                                <img 
                                                    src={image} 
                                                    alt={school.name} 
                                                    className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105"
                                                    loading="lazy"
                                                    onClick={handleImageClick}
                                                    onError={(e) => { 
                                                        e.target.onerror = null; 
                                                        e.target.src = "https://placehold.co/600x400/D1FAE5/065F46?text=School+Service" 
                                                    }}
                                                />
                                                {/* Gradient overlay for better text readability */}
                                                <div className="absolute inset-0 bg-gradient-to-t from-black/30 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div> 
                                            </div>
                                        </SwiperSlide>
                                    ))}
                                </Swiper>
                                
                                {/* Enhanced Custom Navigation Buttons */}
                                <button className={`swiper-button-prev-custom swiper-button-prev-custom-${cardId} absolute left-3 top-1/2 -translate-y-1/2 w-10 h-10 bg-white/80 backdrop-blur-sm rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-300 z-10 hover:bg-white hover:scale-110 shadow-lg`}>
                                    <FaChevronLeft className="text-gray-700 h-4 w-4" />
                                </button>
                                <button className={`swiper-button-next-custom swiper-button-next-custom-${cardId} absolute right-3 top-1/2 -translate-y-1/2 w-10 h-10 bg-white/80 backdrop-blur-sm rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-300 z-10 hover:bg-white hover:scale-110 shadow-lg`}>
                                    <FaChevronRight className="text-gray-700 h-4 w-4" />
                                </button>
                                
                                {/* Enhanced Image Counter */}
                                <div className="absolute top-4 right-4 bg-black/50 backdrop-blur-sm text-white text-xs px-3 py-1.5 rounded-full font-medium z-10 flex items-center">
                                    <FaSearchPlus className="mr-1.5 h-3 w-3" />
                                    {currentImageIndex + 1} / {allImages.length}
                                </div>
                            </div>
                        ) : (
                            <div className="relative h-full bg-gradient-to-br from-green-50 to-emerald-100 flex items-center justify-center">
                                <div className="text-center">
                                    <FaCalendarAlt className="text-green-300 w-16 h-16 mx-auto mb-3" />
                                    <p className="text-green-600 font-medium">No images available</p>
                                </div>
                            </div>
                        )}

                        {/* Enhanced Type/Price Badge with gradient */}
                        <div className={`absolute bottom-0 left-0 right-0 px-4 py-3 text-white text-sm font-semibold shadow-lg z-10 
                            bg-gradient-to-r ${isPaid ? 'from-green-600 to-emerald-600' : 'from-emerald-500 to-teal-600'}`}
                        >
                            <div className="flex justify-between items-center">
                                <span>{isPaid ? 'Enrollment Fee' : 'Free Service'}</span>
                                {isPaid && (
                                    <span className="text-lg font-bold">₵{school.price}</span>
                                )}
                            </div>
                        </div>
                        
                        {/* Enhanced Quick View Button */}
                        <button
                            className="absolute top-4 right-4 bg-white/90 backdrop-blur-sm p-3 rounded-full shadow-lg opacity-0 group-hover:opacity-100 transition-all duration-300 hover:bg-white hover:scale-110 z-20"
                            onClick={(e) => { e.stopPropagation(); onOpenModal(school); }}
                            aria-label="Quick View"
                        >
                            <FaExpand className="w-5 h-5 text-gray-700" />
                        </button>
                    </div>
                    
                    {/* Enhanced Content Section */}
                    <div className="p-6">
                        {/* School Name and Rating */}
                        <div className="flex justify-between items-start mb-4">
                            <h3 className="text-xl font-bold text-gray-900 line-clamp-2 pr-2 leading-tight">
                                {school.name}
                            </h3>
                            {school.rating && (
                                <RatingDisplay rating={school.rating} reviews={school.reviews || 0} />
                            )}
                        </div>
                        
                        {/* Enhanced Details Grid with better spacing and visual hierarchy */}
                        <div className="space-y-3 mb-6">
                            {formattedDate && (
                                <DetailItem 
                                    icon={FaCalendarAlt} 
                                    text={formattedDate} 
                                    colorClass="text-blue-500" 
                                    bgColorClass="bg-blue-50" 
                                />
                            )}
                            {school.duration && (
                                <DetailItem 
                                    icon={FaClock} 
                                    text={school.duration} 
                                    colorClass="text-purple-500" 
                                    bgColorClass="bg-purple-50" 
                                />
                            )}
                            {school.location && (
                                <DetailItem 
                                    icon={FaMapMarkerAlt} 
                                    text={school.location} 
                                    colorClass="text-red-500" 
                                    bgColorClass="bg-red-50" 
                                />
                            )}
                            {school.instructor && (
                                <DetailItem 
                                    icon={FaChalkboardTeacher} 
                                    text={school.instructor.name} 
                                    colorClass="text-green-500" 
                                    bgColorClass="bg-green-50" 
                                />
                            )}
                            {school.capacity && (
                                <DetailItem 
                                    icon={FaUsers} 
                                    text={`${school.capacity} students max`} 
                                    colorClass="text-indigo-500" 
                                    bgColorClass="bg-indigo-50" 
                                />
                            )}
                        </div>
                        
                        {/* Enhanced Action Button with gradient */}
                        <button
                            onClick={() => onOpenModal(school)}
                            className={`w-full py-3 px-4 text-white font-semibold rounded-xl transition-all duration-300 flex items-center justify-center shadow-md hover:shadow-xl transform hover:scale-[1.02] ${
                                isPaid 
                                    ? 'bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700' 
                                    : 'bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-600 hover:to-teal-700'
                            }`}
                        >
                            <FaExpand className="mr-2 h-4 w-4" />
                            {isPaid ? 'View Details & Book' : 'Explore & Register'}
                        </button>
                    </div>
                </div>
            </motion.div>
            
            {/* Enhanced Image Zoom Modal */}
            <AnimatePresence>
                {isZoomed && (
                    <motion.div
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        className="fixed inset-0 bg-black/95 z-50 flex items-center justify-center p-4"
                        onClick={closeZoom}
                    >
                        <motion.div
                            initial={{ scale: 0.8, opacity: 0 }}
                            animate={{ scale: 1, opacity: 1 }}
                            exit={{ scale: 0.8, opacity: 0 }}
                            transition={{ type: "spring", damping: 25, stiffness: 300 }}
                            className="relative max-w-5xl max-h-[90vh] w-full"
                            onClick={(e) => e.stopPropagation()}
                        >
                            <button
                                className="absolute -top-12 right-0 text-white hover:text-gray-300 transition-colors p-2"
                                onClick={closeZoom}
                                aria-label="Close image zoom"
                            >
                                <FaTimes className="text-3xl" />
                            </button>
                            
                            <Swiper
                                key={`${cardId}-zoom`}
                                modules={[Navigation, Pagination]}
                                navigation
                                pagination={{ clickable: true }}
                                initialSlide={currentImageIndex}
                                className="h-full w-full rounded-xl overflow-hidden shadow-2xl"
                                style={{
                                    '--swiper-navigation-color': '#fff',
                                    '--swiper-pagination-color': '#fff',
                                }}
                            >
                                {allImages.map((image, index) => (
                                    <SwiperSlide key={`${cardId}-zoom-${index}`} className="flex items-center justify-center bg-gray-900">
                                        <img 
                                            src={image} 
                                            alt={school.name} 
                                            className="max-w-full max-h-full object-contain"
                                        />
                                    </SwiperSlide>
                                ))}
                            </Swiper>
                            
                            <div className="text-center text-white mt-4">
                                <p className="text-lg font-medium">{school.name}</p>
                                <p className="text-sm text-gray-300 mt-1">Image {currentImageIndex + 1} of {allImages.length}</p>
                            </div>
                        </motion.div>
                    </motion.div>
                )}
            </AnimatePresence>
        </>
    );
};

export default SchoolCard;