'use client';

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

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

const CoursesPage = ({pageData}) => {
  const [levels, setLevels] = useState([]);
  const [subjects, setSubjects] = useState([]);
  const [activeTab, setActiveTab] = useState('type');
  const [searchType, setSearchType] = useState('');
  const [searchSubject, setSearchSubject] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchdata = async () => {
      try {
        setLoading(true);
        const [levels, subjects] = await Promise.all([
          fetch('/api/frontend/getpostlevel', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            }
          }),
          fetch('/api/frontend/getsubject', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            }
          }),
        ]);

        if(!levels.ok || !subjects.ok) throw new Error('Failed to fetch data')

        const levelData = await levels.json();
        const subjectsData = await subjects.json();

        setLevels(levelData.data || []);
        setSubjects(subjectsData.data || []);
      } catch (error) {
        console.error('Error fetching data:', error);
      } finally {
        setLoading(false);
      }
    }

    fetchdata()
  }, [])

  const filteredLevels = levels.filter((level) =>
    level.title?.toLowerCase().includes(searchType.toLowerCase())
  );

  const filteredSubjects = subjects.filter((subject) =>
    subject.name?.toLowerCase().includes(searchSubject.toLowerCase())
  );

  // Calculate total stats
  const totalStats = {
    courses: 100000,
    instructors: 500,
    subjects: subjects.length,
    students: 10000
  };

  // Handle search with animation
  const handleSearch = (value, type) => {
    setLoading(true);
    if (type === 'type') {
      setSearchType(value);
    } else {
      setSearchSubject(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" />
              Smart Course Finder
            </div>

            {/* Main Heading */}
            <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-8 leading-tight">
              {pageData?.simple_title}{' '}
              <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                {pageData?.color_title}
              </span>
            </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">100,000+ courses</span> across diverse fields. 
              Start your learning journey with world-class education.
            </p>

            {/* Search 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('type')}
                    className={`flex-1 py-4 px-8 rounded-xl font-semibold transition-all duration-300 flex items-center justify-center gap-3 ${
                      activeTab === 'type' 
                        ? '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'
                    }`}
                  >
                    <GraduationCap className="w-6 h-6" />
                    Browse by Course Type
                  </button>
                  <button
                    onClick={() => setActiveTab('subject')}
                    className={`flex-1 py-4 px-8 rounded-xl font-semibold transition-all duration-300 flex items-center justify-center gap-3 ${
                      activeTab === 'subject' 
                        ? '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 === 'type' 
                  ? "Search course types (e.g., Undergraduate, Masters, PhD)..."
                  : "Search subjects (e.g., Computer Science, Business, Engineering)..."
              }
              value={activeTab === 'type' ? searchType : searchSubject}
              onChange={(e) => handleSearch(e.target.value, activeTab)}
              loading={loading}
              resultCount={activeTab === 'type' ? filteredLevels.length : filteredSubjects.length}
              onClear={() => activeTab === 'type' ? setSearchType('') : setSearchSubject('')}
              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">
              Course Finder Insights
            </h2>
            <p className="text-gray-600 max-w-2xl mx-auto">
              Comprehensive database with courses from universities worldwide
            </p>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
            <StatCard 
              Icon={BookOpen}
              number={`${totalStats.courses.toLocaleString()}+`}
              label="Courses Available"
              color="teal"
            />
            <StatCard 
              Icon={GraduationCap}
              number={`${totalStats.instructors}+`}
              label="Expert Instructors"
              color="blue"
            />
            <StatCard 
              Icon={Building2}
              number={`${totalStats.subjects}+`}
              label="Subject Areas"
              color="emerald"
            />
            <StatCard 
              Icon={Award}
              number={`${totalStats.students.toLocaleString()}+`}
              label="Happy Students"
              color="amber"
            />
          </div>
        </div>
      </div>

      <div className='mb-16'>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Content Card */}
          <div className="bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-200">
            {/* Content Container with Padding */}
            <div className="p-6 md:p-8 lg:p-12">
              <TextDisplay 
                content={pageData?.top_content}
                className="prose prose-lg max-w-none sn-content"
              />
            </div>
          </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 === 'type' ? (
            <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">
                  <GraduationCap className="w-5 h-5 text-teal-600" />
                  <span className="text-teal-700 font-semibold">Browse by Course Type</span>
                </div>
                <h2 className="text-4xl font-bold text-gray-900 mb-4">
                  Explore Courses by{' '}
                  <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                    Level & Qualification
                  </span>
                </h2>
                <p className="text-gray-600 text-lg max-w-3xl mx-auto">
                  Find courses by qualification level and program type
                </p>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
                {filteredLevels.map((level, index) => (
                  <ImageCard
                    key={level.id || index}
                    title={level.title || 'Unknown Level'}
                    image={level.image || '/assets/default-level.jpg'}
                    link={`/search?type=course&qualification=${encodeURIComponent(level.id || level.title)}`}
                    buttonText="Courses"
                    buttonIcon={BookOpen}
                    defaultImageIcon={GraduationCap}
                    imageAlt={level.title || 'Course Level'}
                  />
                ))}
              </div>

              {filteredLevels.length === 0 && (
                <EmptyState
                  Icon={GraduationCap}
                  title="No course types found"
                  description={searchType ? `No results for "${searchType}"` : 'Try searching for a course type'}
                  searchQuery={searchType}
                  onClearSearch={() => setSearchType('')}
                />
              )}
            </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 by academic discipline and field of study
                </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) => (
                  <ImageCard
                    key={subject.id || index}
                    title={subject.name || 'Unknown Subject'}
                    image={subject.icon || '/assets/default-subject.jpg'}
                    link={`/search?type=course&subject=${encodeURIComponent(subject.name)}`}
                    buttonText="Courses"
                    buttonIcon={GraduationCap}
                    defaultImageIcon={BookOpen}
                    imageAlt={subject.name || 'Subject'}
                  />
                ))}
              </div>

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

          <div className='pb-16 pt-10'>
            <div className="max-w-7xl mx-auto">
              {/* Content Card */}
              <div className="bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-200">
                {/* Content Container with Padding */}
                <div className="p-6 md:p-8 lg:p-12">
                  <TextDisplay 
                    content={pageData?.middle_content}
                    className="prose prose-lg max-w-none sn-content"
                  />
                </div>
              </div>
            </div>
          </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 academic advisors are here to help you find the perfect course tailored to your goals and aspirations
                </p>
                <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
                  <Link 
                    href="/contact-us"
                    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" />
                    Get Personalized Advice
                    <ChevronRight className="w-5 h-5 transition-transform duration-300 group-hover:translate-x-1" />
                  </Link>
                  
                  <Link 
                    href="/comparison"
                    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" />
                    Compare Courses
                  </Link>
                </div>
              </div>
            </div>
          </div>

          <div className='pb-16 pt-10'>
            <div className="max-w-7xl mx-auto">
              {/* Content Card */}
              <div className="bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-200">
                {/* Content Container with Padding */}
                <div className="p-6 md:p-8 lg:p-12">
                  <TextDisplay 
                    content={pageData?.bottom_content}
                    className="prose prose-lg max-w-none sn-content"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  );
};

export default CoursesPage;