'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { 
  Search, 
  Globe, 
  BookOpen, 
  GraduationCap, 
  Building2, 
  Award,
  Shield,
  Zap,
  Sparkles,
  BarChart3,
  MapPin,
  ChevronRight
} from 'lucide-react';

// Import Shared Components
import ModernCard from '../../components/shared/ModernCard';
import StatCard from '../../components/shared/StatCard';
import SearchBar from '../../components/shared/SearchBar';
import ImageCard from '../../components/shared/ImageCard';
import EmptyState from '../../components/shared/EmptyState';

const UniversitiesPage = ({ countries = [], subjects = [] }) => {
  const [activeTab, setActiveTab] = useState('countries');
  const [searchCountries, setSearchCountries] = useState('');
  const [searchSubjects, setSearchSubjects] = useState('');
  const [loading, setLoading] = useState(false);

  // Filter countries based on search
  const filteredCountries = countries.filter(country => {
    const countryName = country.country || country.country_name || country.name || '';
    return countryName.toLowerCase().includes(searchCountries.toLowerCase());
  });

  // Filter subjects based on search
  const filteredSubjects = subjects.filter(subject => {
    const subjectName = subject.name || subject.subject_name || '';
    return subjectName.toLowerCase().includes(searchSubjects.toLowerCase());
  });

  // Calculate total stats from real data
  const totalStats = {
    universities: countries.reduce((sum, country) => sum + (country.university_count || 0), 0),
    countries: countries.length,
    subjects: subjects.length,
    courses: subjects.reduce((sum, subject) => sum + (subject.course_count || 0), 0)
  };

  // Handle search with animation
  const handleSearch = (value, type) => {
    setLoading(true);
    if (type === 'countries') {
      setSearchCountries(value);
    } else {
      setSearchSubjects(value);
    }
    setTimeout(() => setLoading(false), 300);
  };

  return (
    <div className="min-h-screen bg-linear-to-b from-gray-50 to-white">
      {/* Hero Section */}
      <div className="relative">
        {/* Background Gradient */}
        <div className="absolute inset-0 bg-linear-to-r from-teal-50/50 to-blue-50/50"></div>
        
        {/* Animated Background Elements */}
        <div className="absolute top-0 left-0 w-full h-full overflow-hidden">
          {[...Array(20)].map((_, i) => (
            <div
              key={i}
              className="absolute rounded-full bg-linear-to-r from-teal-200/20 to-blue-200/20 animate-float"
              style={{
                width: Math.random() * 100 + 50,
                height: Math.random() * 100 + 50,
                top: `${Math.random() * 100}%`,
                left: `${Math.random() * 100}%`,
                animationDelay: `${Math.random() * 5}s`,
                animationDuration: `${Math.random() * 10 + 10}s`
              }}
            />
          ))}
        </div>

        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-20 md:py-28">
          <div className="text-center">
            {/* Badge */}
            <div className="inline-flex items-center gap-2 bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-6 py-3 rounded-full text-sm font-semibold mb-8 animate-pulse">
              <Shield className="w-5 h-5" />
              Global University Directory
            </div>

            {/* Main Heading */}
            <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-8 leading-tight">
              Discover{' '}
              <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                World-Class Universities
              </span>{' '}
              <br />
              & Academic Programs
            </h1>

            {/* Subheading */}
            <p className="text-xl md:text-2xl text-gray-600 mb-12 max-w-3xl mx-auto leading-relaxed">
              Explore <span className="font-semibold text-teal-600">top-ranked universities</span>, courses, and programs worldwide. 
              Find your perfect academic destination with intelligent search.
            </p>

            {/* Comparison Type Tabs */}
            <div className="max-w-2xl mx-auto mb-12">
              <div className="bg-white border-2 border-gray-200 rounded-2xl p-1 shadow-sm">
                <div className="flex">
                  <button
                    onClick={() => setActiveTab('countries')}
                    className={`flex-1 py-4 px-8 rounded-xl font-semibold transition-all duration-300 flex items-center justify-center gap-3 ${
                      activeTab === 'countries' 
                        ? 'bg-linear-to-r from-teal-600 to-blue-500 text-white shadow-lg' 
                        : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                    }`}
                  >
                    <Globe className="w-6 h-6" />
                    Browse by Country
                  </button>
                  <button
                    onClick={() => setActiveTab('subjects')}
                    className={`flex-1 py-4 px-8 rounded-xl font-semibold transition-all duration-300 flex items-center justify-center gap-3 ${
                      activeTab === 'subjects' 
                        ? 'bg-linear-to-r from-teal-600 to-blue-500 text-white shadow-lg' 
                        : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                    }`}
                  >
                    <BookOpen className="w-6 h-6" />
                    Browse by Subject
                  </button>
                </div>
              </div>
            </div>

            {/* Search Bar */}
            <SearchBar
              placeholder={
                activeTab === 'countries' 
                  ? "Search countries (e.g., USA, UK, Canada, Germany)..."
                  : "Search subjects (e.g., Computer Science, Business, Engineering)..."
              }
              value={activeTab === 'countries' ? searchCountries : searchSubjects}
              onChange={(e) => handleSearch(e.target.value, activeTab)}
              loading={loading}
              resultCount={activeTab === 'countries' ? filteredCountries.length : filteredSubjects.length}
              onClear={() => activeTab === 'countries' ? setSearchCountries('') : setSearchSubjects('')}
              className="max-w-3xl mx-auto mb-16"
            />
          </div>
        </div>
      </div>

      {/* Global Education Insights Section */}
      <div className="py-16">
        <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-900 mb-4">
              Global Education Insights
            </h2>
            <p className="text-gray-600 max-w-2xl mx-auto">
              Comprehensive database with real-time statistics from universities worldwide
            </p>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
            <StatCard 
              Icon={GraduationCap}
              number={`${totalStats.universities}+`}
              label="Universities"
              color="teal"
            />
            <StatCard 
              Icon={Globe}
              number={`${totalStats.countries}+`}
              label="Countries"
              color="blue"
            />
            <StatCard 
              Icon={BookOpen}
              number={`${totalStats.subjects}+`}
              label="Subjects"
              color="emerald"
            />
            <StatCard 
              Icon={Award}
              number={`${totalStats.courses}+`}
              label="Courses Available"
              color="amber"
            />
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="pb-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Tab Content */}
          {activeTab === 'countries' ? (
            <div className="space-y-12">
              <div className="text-center">
                <div className="inline-flex items-center gap-3 bg-linear-to-r from-teal-50 to-blue-50 px-6 py-3 rounded-full mb-6">
                  <Globe className="w-5 h-5 text-teal-600" />
                  <span className="text-teal-700 font-semibold">Browse by Country</span>
                </div>
                <h2 className="text-4xl font-bold text-gray-900 mb-4">
                  Explore Universities{' '}
                  <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                    Worldwide
                  </span>
                </h2>
                <p className="text-gray-600 text-lg max-w-3xl mx-auto">
                  Discover top universities and colleges in your preferred study destination
                </p>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
                {filteredCountries.map((country, index) => {
                  const countryName = country.country || country.country_name || country.name || 'Unknown Country';
                  const universityCount = country.university_count || 0;
                  const courseCount = country.course_count || 0;
                  
                  return (
                    <ImageCard
                      key={country.id || index}
                      title={countryName}
                      image={country.image || '/assets/default-country.jpg'}
                      link={`/search?type=university&country=${encodeURIComponent(countryName)}`}
                      buttonText="Explore"
                      buttonIcon={MapPin}
                      defaultImageIcon={Globe}
                      imageAlt={countryName}
                    />
                  );
                })}
              </div>

              {filteredCountries.length === 0 && (
                <EmptyState
                  Icon={Globe}
                  title="No countries found"
                  description={searchCountries ? `No results for "${searchCountries}"` : 'Try searching for a country'}
                  searchQuery={searchCountries}
                  onClearSearch={() => setSearchCountries('')}
                />
              )}
            </div>
          ) : (
            <div className="space-y-12">
              <div className="text-center">
                <div className="inline-flex items-center gap-3 bg-linear-to-r from-teal-50 to-blue-50 px-6 py-3 rounded-full mb-6">
                  <BookOpen className="w-5 h-5 text-teal-600" />
                  <span className="text-teal-700 font-semibold">Browse by Subject</span>
                </div>
                <h2 className="text-4xl font-bold text-gray-900 mb-4">
                  Explore Academic{' '}
                  <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                    Programs & Courses
                  </span>
                </h2>
                <p className="text-gray-600 text-lg max-w-3xl mx-auto">
                  Discover courses and programs offered by universities worldwide
                </p>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
                {filteredSubjects.map((subject, index) => {
                  const subjectName = subject.name || subject.subject_name || 'Unknown Subject';
                  const universityCount = subject.university_count || 0;
                  
                  return (
                    <ImageCard
                      key={subject.id || index}
                      title={subjectName}
                      image={subject.icon || '/assets/default-subject.jpg'}
                      link={`/search?type=course&subject=${encodeURIComponent(subjectName)}`}
                      buttonText="Explore"
                      buttonIcon={GraduationCap}
                      defaultImageIcon={BookOpen}
                      imageAlt={subjectName}
                    />
                  );
                })}
              </div>

              {filteredSubjects.length === 0 && (
                <EmptyState
                  Icon={BookOpen}
                  title="No subjects found"
                  description={searchSubjects ? `No results for "${searchSubjects}"` : 'Try searching for a subject'}
                  searchQuery={searchSubjects}
                  onClearSearch={() => setSearchSubjects('')}
                />
              )}
            </div>
          )}

          {/* Call to Action */}
          <div className="mt-20">
            <div className="bg-linear-to-r from-teal-600 to-blue-500 rounded-3xl overflow-hidden">
              <div className="p-12 text-center">
                <div className="inline-flex items-center gap-3 bg-white/20 backdrop-blur-sm px-6 py-3 rounded-full mb-6">
                  <Zap className="w-5 h-5 text-white" />
                  <span className="text-white font-semibold">Need Help Choosing?</span>
                </div>
                <h3 className="text-3xl font-bold text-white mb-4">
                  Get Personalized Guidance
                </h3>
                <p className="text-white/80 text-lg mb-8 max-w-2xl mx-auto">
                  Our education consultants can help you find the perfect university and course combination based on your goals and preferences
                </p>
                <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
                  <Link 
                    href="/apply-online"
                    className="group bg-white text-teal-600 px-10 py-4 rounded-2xl text-lg font-bold shadow-2xl hover:shadow-3xl hover:scale-105 transition-all duration-300 flex items-center gap-3"
                  >
                    <Sparkles className="w-5 h-5" />
                    Apply Now?
                    <ChevronRight className="w-5 h-5 transition-transform duration-300 group-hover:translate-x-1" />
                  </Link>
                  
                  <Link 
                    href="/free-consultation"
                    className="px-10 py-4 border-2 border-white/30 text-white rounded-2xl font-semibold hover:bg-white/10 transition-all duration-300 flex items-center gap-2"
                  >
                    <BarChart3 className="w-5 h-5" />
                    Free Consultation
                  </Link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  );
};

export default UniversitiesPage;