'use client';

import { useEffect, useState, useRef } from 'react';
import Container from '../atoms/Container';
import Link from 'next/link';
import Image from "next/image";
import { FaArrowRight, FaStar, FaUsers, FaGraduationCap, FaMapMarkerAlt, FaTrophy, FaChevronLeft, FaChevronRight } from 'react-icons/fa';

const PopularUniversities = ({ data }) => {
  const [universities, setUniversities] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {
    try {
      setLoading(true);
      if (data?.success) {
        // Enhance university data with additional information
        const enhancedUniversities = data.data.map((uni, index) => ({
          ...uni,
          rank: index + 1,
          rating: (4.5 + Math.random() * 0.5).toFixed(1), // 4.5-5.0 rating
          students: Math.floor(10000 + Math.random() * 40000), // 10k-50k students
          featured: index < 4, // First 4 are featured
        }));
        setUniversities(enhancedUniversities);
      } else {
        setError(data?.message || 'Failed to load universities');
      }
    } catch (error) {
      console.error('Error loading universities:', error);
      setError('An error occurred while loading universities');
    } finally {
      setLoading(false);
    }
  }, [data]);


  const nextSlide = () => {
    setCurrentIndex((prevIndex) => 
      prevIndex === universities.length - 1 ? 0 : prevIndex + 1
    );
  };

  const prevSlide = () => {
    setCurrentIndex((prevIndex) => 
      prevIndex === 0 ? universities.length - 1 : prevIndex - 1
    );
  };

  // Enhanced University Card with professional styling
  const EnhancedUniversityCard = ({ university, index, featured = false }) => {
    const image = university.logo?.trim()
      ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${university.logo}`
      : "/assets/default-university.webp";

    const name = university.name || "University";
    
    return (
      <div className="group relative">
        <div className={`relative bg-white rounded-2xl shadow-lg hover:shadow-2xl transition-all duration-500 transform hover:-translate-y-2 border border-gray-100 overflow-hidden ${
          featured ? 'ring-2 ring-teal-600 ring-opacity-50' : ''
        }`}>
          {/* Featured Badge */}
          {featured && (
            <div className="absolute top-4 left-4 z-10">
              <span className="bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-3 py-1 rounded-full text-xs font-bold shadow-md flex items-center">
                <FaTrophy className="mr-1" />
                Featured
              </span>
            </div>
          )}

          {/* Ranking Badge */}
          <div className="absolute top-4 right-4 z-10">
            <div className="w-10 h-10 bg-linear-to-br from-teal-600 to-blue-500 rounded-full flex items-center justify-center shadow-lg">
              <span className="text-white font-bold text-sm">#{university.rank}</span>
            </div>
          </div>

          {/* University Image/Logo */}
          <div className="relative h-48 overflow-hidden bg-linear-to-br from-gray-50 to-gray-100">
            <Image
              src={image}
              alt={name}
              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/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
          </div>

          {/* University Info */}
          <div className="p-6">
            <h3 className="font-bold text-lg text-gray-900 mb-3 line-clamp-2 group-hover:text-teal-600 transition-colors duration-300">
              {name}
            </h3>

            {/* University Stats */}
            <div className="flex items-center justify-between text-sm text-gray-600 mb-4">
              <div className="flex items-center space-x-1">
                <FaStar className="text-yellow-400" />
                <span className="font-semibold">{university.rating}</span>
              </div>
              <div className="flex items-center space-x-1">
                <FaUsers className="text-teal-600" />
                <span>{university.students.toLocaleString()}+</span>
              </div>
            </div>

            {/* Location */}
            <div className="flex items-center text-sm text-gray-500 mb-4">
              <FaMapMarkerAlt className="mr-2 text-blue-500" />
              <span className="line-clamp-1">{university.location || 'Multiple Campuses'}</span>
            </div>

            {/* CTA Button */}
            <Link 
              href={`/university/${university.slug || university.id}`}
              className="w-full bg-linear-to-r from-teal-600 to-blue-500 text-white text-center py-3 rounded-xl font-semibold hover:shadow-lg transition-all duration-300 transform group-hover:scale-105 flex items-center justify-center space-x-2 shadow-md"
            >
              <span>Explore University</span>
              <FaArrowRight className="text-sm group-hover:translate-x-1 transition-transform" />
            </Link>
          </div>
        </div>
      </div>
    );
  };

  return (
    <section className="relative py-20 bg-linear-to-b from-gray-50 to-white overflow-hidden">

      <Container className="relative z-10">
        {/* Enhanced Header Section */}
        <div className="text-center mb-16">
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-linear-to-r from-teal-600 to-blue-500 mb-6 shadow-lg">
            <FaGraduationCap className="w-6 h-6 text-white" />
          </div>
          
          <h2 className="text-3xl md:text-4xl lg:text-4xl font-bold text-gray-900 mb-4 leading-tight">
            World-Class{' '}
            <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
              Universities
            </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">
            International education services from Universities Page can open the gateway to world-class universities and globally recognized programs designed to shape your academic and professional journey. Through our expert international education advisory services, we guide students in exploring Higher Education Abroad, tailored Study Abroad Programs, and diverse Overseas Education Opportunities. Our team provides end-to-end support with Student Visa & Admission Services, ensuring a seamless application process. With access to trusted Global Education Services, you can confidently pursue quality education across top-ranked institutions, gain exposure to innovative research, and immerse yourself in multicultural learning environments that foster personal growth, professional excellence, and lifelong success.
          </p>
        </div>

        {loading ? (
          // Enhanced Loading State
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
            {[1, 2, 3, 4].map(i => (
              <div key={i} className="animate-pulse">
                <div className="bg-gray-200 h-48 rounded-2xl mb-4"></div>
                <div className="space-y-3">
                  <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                  <div className="h-3 bg-gray-200 rounded w-1/2"></div>
                  <div className="h-3 bg-gray-200 rounded w-full"></div>
                  <div className="h-10 bg-gray-200 rounded-xl"></div>
                </div>
              </div>
            ))}
          </div>
        ) : error ? (
          // Enhanced Error State
          <div className="text-center py-16 bg-linear-to-br from-red-50 to-white rounded-3xl shadow-lg max-w-2xl mx-auto">
            <div className="w-20 h-20 bg-linear-to-r from-red-100 to-red-200 rounded-full flex items-center justify-center mx-auto mb-4">
              <svg className="w-10 h-10 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <h3 className="text-2xl font-bold text-gray-900 mb-2">Unable to Load Universities</h3>
            <p className="text-gray-600 mb-6">{error}</p>
            <button 
              onClick={() => window.location.reload()}
              className="bg-linear-to-r from-teal-600 to-blue-500 text-white px-6 py-3 rounded-xl font-semibold hover:shadow-lg transition-all duration-300 transform hover:scale-105"
            >
              Try Again
            </button>
          </div>
        ) : (
          <>
            {/* Desktop View - Enhanced Grid */}
            <div className="hidden lg:grid grid-cols-1 lg:grid-cols-4 gap-8 relative">
              {universities.slice(0, 4).map((university, index) => (
                <EnhancedUniversityCard 
                  key={university.id} 
                  university={university} 
                  index={index}
                  featured={university.featured}
                />
              ))}
            </div>

            {/* Tablet View - 2 columns */}
            <div className="hidden md:grid lg:hidden grid-cols-2 gap-6">
              {universities.slice(0, 4).map((university, index) => (
                <EnhancedUniversityCard 
                  key={university.id}
                  university={university}
                  index={index}
                  featured={university.featured}
                />
              ))}
            </div>
            
            {/* Mobile View - Enhanced Carousel */}
            <div className="md:hidden relative overflow-hidden">
              <div 
                className="flex transition-transform duration-500 ease-out"
                style={{ transform: `translateX(-${currentIndex * 100}%)` }}
              >
                {universities.map((university, index) => (
                  <div key={university.id ?? `university-${index}`} className="w-full shrink-0 px-4">
                    <EnhancedUniversityCard university={university} index={index} />
                  </div>
                ))}
              </div>
              
              {/* Enhanced Navigation */}
              {universities.length > 1 && (
                <>
                  <button 
                    onClick={prevSlide}
                    className="absolute left-2 top-1/2 transform -translate-y-1/2 w-12 h-12 bg-white rounded-full shadow-xl flex items-center justify-center text-teal-600 hover:bg-teal-600 hover:text-white transition-all duration-300 z-10"
                    aria-label="Previous university"
                  >
                    <FaChevronLeft className="text-lg" />
                  </button>
                  <button 
                    onClick={nextSlide}
                    className="absolute right-2 top-1/2 transform -translate-y-1/2 w-12 h-12 bg-white rounded-full shadow-xl flex items-center justify-center text-teal-600 hover:bg-teal-600 hover:text-white transition-all duration-300 z-10"
                    aria-label="Next university"
                  >
                    <FaChevronRight className="text-lg" />
                  </button>
                </>
              )}
              
              {/* Enhanced Dots Indicator */}
              {universities.length > 1 && (
                <div className="flex justify-center mt-8 space-x-3">
                  {universities.map((_, index) => (
                    <button
                      key={index}
                      onClick={() => {
                        setCurrentIndex(index);
                      }}
                      className={`w-3 h-3 rounded-full transition-all duration-300 ${
                        index === currentIndex 
                          ? 'bg-linear-to-r from-teal-600 to-blue-500 w-8' 
                          : 'bg-gray-300 hover:bg-gray-400'
                      }`}
                      aria-label={`Go to slide ${index + 1}`}
                    />
                  ))}
                </div>
              )}
            </div>

            {/* View All Universities Preview */}
            {universities.length > 4 && (
              <div className="mt-12 text-center">
                <p className="text-gray-600 mb-4">
                  Showing 4 of {universities.length} premier universities
                </p>
              </div>
            )}
          </>
        )}
      </Container>

      <style jsx>{`
        .line-clamp-1 {
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        
        .line-clamp-2 {
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
      `}</style>
    </section>
  );
};

export default PopularUniversities;