'use client';

import { useEffect, useState } from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation, Autoplay, Pagination } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import Image from "next/image";

import { Star, MapPin, Zap,ChevronLeft,ChevronRight } from 'lucide-react';

import Container from '../atoms/Container';
import Link from 'next/link';

const PopularCourses = ({ data }) => {
  const [courses, setCourses] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [favorites, setFavorites] = useState(new Set());

  useEffect(() => {
    try {
      setLoading(true);
      if (data.success) {
        setCourses(data.data);
      } else {
        setError(data.message);
      }
    } catch (error) {
      setError('Failed to load courses');
    } finally {
      setLoading(false);
    }
  }, [data]);

  const toggleFavorite = (courseId) => {
    setFavorites(prev => {
      const newFavorites = new Set(prev);
      newFavorites.has(courseId) ? newFavorites.delete(courseId) : newFavorites.add(courseId);
      return newFavorites;
    });
  };

  const CourseCard = ({ course }) => {
    const isFavorite = favorites.has(course.id);
    
    return (
      <div className="group bg-white rounded-3xl shadow-lg hover:shadow-2xl transition-all duration-500 transform hover:-translate-y-2 border border-gray-100 overflow-hidden relative">
        {/* Premium Badge */}
        <div className="absolute top-4 left-4 z-10">
          <div className="bg-linear-to-r from-teal-600 to-blue-500 text-white px-3 py-1 rounded-full text-xs font-bold flex items-center gap-1">
            <Zap className="w-3 h-3" />
            FEATURED
          </div>
        </div>

        {/* Image Section */}
        <div className="relative overflow-hidden h-48">
          <Image
            src={
              course?.university_logo
                ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${course?.university_logo}`
                : "/assets/default-course.webp"
            }
            alt={course?.name || "Course image"}
            fill
            className="object-contain p-6 transition-transform duration-700 group-hover:scale-110"
          />

          <div className="absolute inset-0 bg-linear-to-t from-black/40 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
          
          {/* Action Buttons */}
          <div className="absolute top-4 right-4 flex gap-2">
            <button 
              onClick={() => toggleFavorite(course.id)}
              className="bg-white/90 backdrop-blur-sm rounded-full p-2 hover:bg-white transition-all duration-300 transform hover:scale-110"
            >
              {/* Favorite button icon can be added here */}
            </button>
          </div>
        </div>

        {/* Content Section */}
        <div className="p-6">
          {/* University Info */}
          <div className="flex items-center mb-3">
            <div className="w-10 h-10 bg-linear-to-r from-teal-600 to-blue-500 rounded-xl flex items-center justify-center text-white font-bold text-sm mr-3">
              {course.university?.charAt(0) || 'U'}
            </div>
            <div className="flex-1 min-w-0">
              <p className="font-semibold text-gray-800 truncate">{course.university || 'University'}</p>
              <div className="flex items-center text-sm text-gray-500">
                <MapPin className="w-3 h-3 mr-1" />
                <span className="truncate">{course.location || 'Multiple Locations'}</span>
              </div>
            </div>
          </div>

          {/* Course Title */}
          <h3 className="text-lg font-bold text-gray-900 mb-3 line-clamp-2 leading-tight group-hover:text-teal-600 transition-colors duration-300 min-h-14">
            {course.name || course.title}
          </h3>

          {/* Rating & Price */}
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-1">
              {[1,2,3,4,5].map((star) => (
                <Star key={star} className={`w-4 h-4 ${star <= 4 ? 'text-yellow-400 fill-yellow-400' : 'text-gray-300'}`} />
              ))}
              <span className="text-sm text-gray-600 ml-1">4.8</span>
            </div>
            <div className="text-right">
              <div className="text-xl font-bold text-teal-600">Scholarship</div>
              <div className="text-xs text-gray-500">Available</div>
            </div>
          </div>

          {/* CTA Button */}
          <Link 
            href={`/${course.university_slug}/${course.slug}`}
            className="block w-full bg-linear-to-r from-teal-600 to-blue-500 text-white text-center font-semibold py-3 rounded-xl hover:shadow-lg transition-all duration-300 transform hover:-translate-y-0.5 shadow-md hover:scale-105"
          >
            View Details
          </Link>
        </div>
      </div>
    );
  };

  return (
    <section className="relative py-16 md:py-24 bg-linear-to-b from-gray-50 to-white">

      <Container className="relative z-10">
        {/* Enhanced Header */}
        <div className="text-center mb-16">
          <div className="inline-flex items-center bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-6 py-3 rounded-full text-sm font-semibold mb-6 shadow-md">
            <Star className="w-4 h-4 mr-2" />
            TRENDING PROGRAMS
          </div>
          <h2 className="text-4xl md:text-4xl lg:text-5xl font-bold text-gray-900 mb-6">
            Popular <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">Courses</span>
          </h2>
          <div className="w-24 h-1 bg-linear-to-r from-teal-600 to-blue-500 mx-auto mb-6 rounded-full"></div>
          <p className="text-lg md:text-xl text-gray-600 max-w-6xl mx-auto leading-relaxed">
            Discover world-class programs from top universities that will shape your future career path with our comprehensive international education services and personalized international education advisory services. On the Universities Page study abroad consultants, you can explore an extensive selection of Higher Education Abroad options, diverse Study Abroad Programs, and exciting Overseas Education Opportunities tailored to your goals. Our team provides expert guidance for Student Visa & Admission Services, helping you navigate every step of the process with ease. Access trusted Global Education Services, gain exposure to innovative academic environments, and build a strong foundation for your academic, professional, and personal success around the world.
          </p>
        </div>

        {/* Courses Slider */}
        <div className="relative">
          {loading ? (
            <div className="flex justify-center items-center py-20">
              <div className="animate-spin rounded-full h-16 w-16 border-4 border-teal-600 border-t-transparent"></div>
            </div>
          ) : error ? (
            <div className="text-center text-red-500 py-10 text-lg bg-red-50 rounded-2xl">{error}</div>
          ) : (
            <>
              <Swiper
                modules={[Navigation, Autoplay, Pagination]}
                spaceBetween={30}
                slidesPerView={1}
                breakpoints={{
                  640: { slidesPerView: 1.2 },
                  768: { slidesPerView: 2 },
                  1024: { slidesPerView: 3 },
                  1280: { slidesPerView: 3.5 }
                }}
                autoplay={{ delay: 6000, disableOnInteraction: false }}
                navigation={{
                  prevEl: '.course-prev',
                  nextEl: '.course-next',
                }}
                pagination={{ 
                  clickable: true,
                  el: '.courses-pagination',
                }}
                className="pb-16"
              >
                {courses.map((course, index) => (
                  <SwiperSlide key={course.id || index}>
                    <CourseCard course={course} />
                  </SwiperSlide>
                ))}
              </Swiper>

              {/* Navigation */}
              <div className="flex justify-center md:justify-end gap-4 mt-8">
                <button className="course-prev bg-white p-4 rounded-full shadow-xl text-teal-600 hover:bg-teal-600 hover:text-white transition-all duration-300 transform hover:scale-110">
                  <ChevronLeft className="w-6 h-6" />
                </button>
                <button className="course-next bg-white p-4 rounded-full shadow-xl text-teal-600 hover:bg-teal-600 hover:text-white transition-all duration-300 transform hover:scale-110">
                  <ChevronRight className="w-6 h-6" />
                </button>
              </div>

              <div className="courses-pagination flex justify-center mt-8 gap-2" />
            </>
          )}
        </div>

        {/* Enhanced CTA */}
        <div className="text-center mt-16">
          <div className="bg-linear-to-r from-teal-600 to-blue-500 rounded-3xl p-8 md:p-12 text-white shadow-2xl">
            <h3 className="text-2xl md:text-3xl font-bold mb-4">Ready to Transform Your Future with Universities Page?</h3>
            <p className="text-lg opacity-90 mb-6 max-w-2xl mx-auto">
              Join thousands of successful students who discovered their ideal course with the support of our expert international education services and trusted student visa consultants, guiding you every step of the way to achieve your academic and career goals.
            </p>
            <div className="flex flex-col sm:flex-row gap-4 justify-center">
              <Link href="/courses">
                <button className="bg-white text-teal-600 px-8 py-4 text-lg font-semibold rounded-xl hover:bg-gray-100 transition-all duration-300 transform hover:-translate-y-1 shadow-lg hover:scale-105">
                  Explore All Courses
                </button>
              </Link>
              <Link href="/free-consultation">
                <button className="border-2 border-white text-white px-8 py-4 text-lg font-semibold rounded-xl hover:bg-white hover:text-teal-600 transition-all duration-300 transform hover:-translate-y-1 hover:scale-105">
                  Get Free Consultation
                </button>
              </Link>
            </div>
          </div>
        </div>
      </Container>
    </section>
  );
};

export default PopularCourses;