'use client';

import { useState, useEffect, useRef } from 'react';
import { 
  Search, 
  Filter, 
  ChevronDown, 
  ChevronUp, 
  Heart, 
  Heart as HeartFill,
  Scale,
  BookOpen,
  Clock,
  DollarSign,
  Calendar,
  Globe,
  ChevronRight,
  X,
  Tag,
  Zap,
  Award,
  Users,
  MapPin,
  GraduationCap,
  Sparkles,
  BarChart3,
  Star,
  TrendingUp,
  Target,
  ExternalLink,
  ArrowRight,
  Loader2,
  Pin,
  Building,
  Languages,
  Users as UsersIcon
} from 'lucide-react';
import Heading from '../atoms/Heading';
import { useWishlist } from '../../context/WishlistContext';
import Swal from 'sweetalert2';
import FreeConsultationModal from '../organisms/FreeConsultationModal';
import ApplyNowModal from '../clientcomponents/ApplyNowModal';
import Link from 'next/link';

// Modern Card Component with gradient hover
const ModernCard = ({ children, className = '', hover = true }) => (
  <div className={`bg-white rounded-2xl border border-gray-100 shadow-lg hover:shadow-xl transition-all duration-300 ${hover ? 'hover:border-teal-100' : ''} overflow-hidden ${className}`}>
    {children}
  </div>
);

// Badge Component with colors
const Badge = ({ children, color = 'teal', icon: Icon }) => {
  const colorClasses = {
    teal: 'bg-teal-50 text-teal-700 border-teal-100',
    blue: 'bg-blue-50 text-blue-700 border-blue-100',
    emerald: 'bg-emerald-50 text-emerald-700 border-emerald-100',
    amber: 'bg-amber-50 text-amber-700 border-amber-100',
    purple: 'bg-purple-50 text-purple-700 border-purple-100',
    pink: 'bg-pink-50 text-pink-700 border-pink-100',
    indigo: 'bg-indigo-50 text-indigo-700 border-indigo-100'
  };

  return (
    <span className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium border ${colorClasses[color]}`}>
      {Icon && <Icon className="w-3 h-3" />}
      {children}
    </span>
  );
};

const UniversityCourses = ({ university, initialCourses = [], subjectsData = { data: [] } }) => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [subjects, setSubjects] = useState([]);
  const [allCourses, setAllCourses] = useState(initialCourses);
  const [subjectSearchTerm, setSubjectSearchTerm] = useState('');
  const [courseSearchTerm, setCourseSearchTerm] = useState('');
  const [showAllSubjects, setShowAllSubjects] = useState(false);
  const [selectedSubjectId, setSelectedSubjectId] = useState(null);
  const [hoveredCourse, setHoveredCourse] = useState(null);
  
  const [currentPage, setCurrentPage] = useState(1);
  const [coursesPerPage] = useState(12);
  const [displayedCourses, setDisplayedCourses] = useState([]);

  const { wishlist, toggleWishlist, isWishlisted } = useWishlist();
  const [isConsultationModalOpen, setIsConsultationModalOpen] = useState(false);
  const [selectedCourse, setSelectedCourse] = useState(null);

  const SUBJECTS_PER_PAGE = 10;

  // Stats for the university
  const universityStats = [
    { icon: BookOpen, number: allCourses.length, label: 'Total Courses', color: 'teal' },
    { icon: UsersIcon, number: allCourses.filter(c => c.scholarship === 1).length, label: 'Scholarships', color: 'blue' },
    { icon: Building, number: subjects.length, label: 'Subjects', color: 'emerald' },
    { icon: TrendingUp, number: 'High', label: 'Demand', color: 'amber' }
  ];

  useEffect(() => {
    const initializeData = async () => {
      try {
        setLoading(true);
        const courses = initialCourses || [];
        const allSubjects = subjectsData?.data || [];
        
        const coursesBySubject = {};
        const subjectCounts = {};
        
        courses.forEach(course => {
          if (course.subject_id) {
            const subjectId = course.subject_id;
            if (!coursesBySubject[subjectId]) {
              coursesBySubject[subjectId] = [];
              subjectCounts[subjectId] = 0;
            }
            coursesBySubject[subjectId].push(course);
            subjectCounts[subjectId]++;
          }
        });
        
        const subjectsWithCourses = allSubjects
          .filter(subject => subjectCounts[subject.id])
          .map(subject => ({
            ...subject,
            count: subjectCounts[subject.id] || 0,
            courses: coursesBySubject[subject.id] || []
          }))
          .sort((a, b) => a.name.localeCompare(b.name));
        
        setAllCourses(courses);
        setSubjects(subjectsWithCourses);
        
      } catch (err) {
        console.error('Error initializing data:', err);
        setError(err.message || 'Failed to load data');
      } finally {
        setLoading(false);
      }
    };

    initializeData();
  }, [initialCourses, subjectsData]);

  useEffect(() => {
    const filtered = getFilteredCourses();
    const endIndex = currentPage * coursesPerPage;
    setDisplayedCourses(filtered.slice(0, endIndex));
  }, [allCourses, courseSearchTerm, selectedSubjectId, currentPage, coursesPerPage]);

  const getFilteredSubjects = () => {
    let filtered = [...subjects];
    
    if (subjectSearchTerm) {
      const searchLower = subjectSearchTerm.toLowerCase();
      filtered = filtered.filter(subject => 
        subject.name.toLowerCase().includes(searchLower)
      );
    }
    
    return filtered;
  };
  
  const getFilteredCourses = () => {
    let courses = [...allCourses];
    
    if (selectedSubjectId) {
      courses = courses.filter(course => course.subject_id === selectedSubjectId);
    }
    
    if (courseSearchTerm) {
      const searchLower = courseSearchTerm.toLowerCase();
      courses = courses.filter(course => 
        course.name?.toLowerCase().includes(searchLower) ||
        (course.description?.toLowerCase().includes(searchLower) ?? false)
      );
    }
    
    return courses;
  };

  const handleLoadMore = () => {
    setCurrentPage(prev => prev + 1);
  };

  const handleSubjectClick = (subjectId) => {
    setSelectedSubjectId(prevId => prevId === subjectId ? null : subjectId);
    setCurrentPage(1);
  };

  const clearAllFilters = () => {
    setSelectedSubjectId(null);
    setCourseSearchTerm('');
    setSubjectSearchTerm('');
    setCurrentPage(1);
  };

  const filteredSubjects = getFilteredSubjects();
  const visibleSubjects = showAllSubjects ? filteredSubjects : filteredSubjects.slice(0, SUBJECTS_PER_PAGE);
  const filteredCourses = getFilteredCourses();
  const hasMoreCourses = displayedCourses.length < filteredCourses.length;
  const selectedSubject = subjects.find(s => s.id === selectedSubjectId);

  if (loading) {
    return (
      <div className="min-h-[400px] flex flex-col items-center justify-center bg-gradient-to-b from-gray-50 to-white">
        <div className="animate-spin rounded-full h-14 w-14 border-t-2 border-b-2 border-teal-600 mb-6"></div>
        <p className="text-gray-600">Loading amazing courses...</p>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      {/* Header Section */}
      <div className="bg-gradient-to-r from-teal-600 to-blue-500 rounded-3xl p-8 text-white">
        <div className="flex items-center gap-4">
          <div className="p-3 rounded-2xl bg-white/20 backdrop-blur-sm">
            <GraduationCap className="w-7 h-7" />
          </div>
          <div>
            <h2 className="text-3xl font-bold mb-2">Explore Courses at {university?.name}</h2>
            <p className="text-white/90">
              Browse {filteredCourses.length} courses across {subjects.length} subjects
            </p>
          </div>
        </div>
      </div>

      {/* Horizontal Filter Bar */}
      <ModernCard>
        <div className="p-6">
          {/* Search and Filter Header */}
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                <input
                  type="text"
                  placeholder="Search courses by name, description, or keywords..."
                  value={courseSearchTerm}
                  onChange={(e) => setCourseSearchTerm(e.target.value)}
                  className="w-full pl-12 pr-10 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent"
                />
                {courseSearchTerm && (
                  <button
                    onClick={() => setCourseSearchTerm('')}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  >
                    <X className="w-5 h-5" />
                  </button>
                )}
              </div>
            </div>
            
            <div className="flex items-center gap-3">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                <input
                  type="text"
                  placeholder="Search subjects..."
                  value={subjectSearchTerm}
                  onChange={(e) => setSubjectSearchTerm(e.target.value)}
                  className="pl-9 pr-8 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent text-sm w-48"
                />
                {subjectSearchTerm && (
                  <button
                    onClick={() => setSubjectSearchTerm('')}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  >
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>
              
              {(selectedSubjectId || courseSearchTerm) && (
                <button
                  onClick={clearAllFilters}
                  className="px-4 py-2.5 text-sm text-gray-600 hover:text-gray-900 font-medium border border-gray-300 rounded-lg hover:border-gray-400 transition-all duration-200"
                >
                  Clear All
                </button>
              )}
            </div>
          </div>

          {/* Active Filters */}
          {(selectedSubjectId || courseSearchTerm) && (
            <div className="flex items-center gap-2 mb-4">
              <span className="text-sm text-gray-600">Active filters:</span>
              <div className="flex flex-wrap gap-2">
                {selectedSubjectId && (
                  <Badge color="teal" icon={BookOpen}>
                    Subject: {selectedSubject?.name}
                  </Badge>
                )}
                {courseSearchTerm && (
                  <Badge color="blue" icon={Search}>
                    Search: "{courseSearchTerm}"
                  </Badge>
                )}
              </div>
            </div>
          )}

          {/* Horizontal Subjects Filter Row */}
          <div className="mb-4">
            <div className="flex items-center justify-between mb-3">
              <h3 className="text-lg font-bold text-gray-900">Filter by Subject</h3>
              <button
                onClick={() => setSelectedSubjectId(null)}
                className={`text-sm font-medium px-4 py-2 rounded-lg transition-all duration-200 ${
                  !selectedSubjectId 
                    ? 'bg-gradient-to-r from-teal-600 to-blue-500 text-white' 
                    : 'text-teal-600 hover:text-teal-700 hover:bg-teal-50'
                }`}
              >
                All Subjects ({allCourses.length})
              </button>
            </div>
            
            <div className="relative">
              <div className="flex flex-wrap gap-2">
                {/* All Subjects Button */}
                <button
                  onClick={() => handleSubjectClick(null)}
                  className={`flex-shrink-0 flex items-center gap-2 px-4 py-2.5 rounded-xl transition-all duration-200 whitespace-nowrap ${
                    !selectedSubjectId 
                      ? 'bg-gradient-to-r from-teal-600 to-blue-500 text-white shadow-md' 
                      : 'bg-gray-100 hover:bg-gray-200 text-gray-700'
                  }`}
                >
                  <BookOpen className="w-4 h-4" />
                  <span className="font-medium">All</span>
                  <span className={`ml-1 px-1.5 py-0.5 rounded-full text-xs ${
                    !selectedSubjectId ? 'bg-white/20' : 'bg-white/70 text-gray-700'
                  }`}>
                    {allCourses.length}
                  </span>
                </button>
                
                {/* Subject Buttons - All visible */}
                {filteredSubjects.map((subject) => (
                  <button
                    key={subject.id}
                    onClick={() => handleSubjectClick(subject.id)}
                    className={`flex-shrink-0 flex items-center gap-2 px-4 py-2.5 rounded-xl transition-all duration-200 whitespace-nowrap ${
                      selectedSubjectId === subject.id
                        ? 'bg-gradient-to-r from-teal-600 to-blue-500 text-white shadow-md' 
                        : 'bg-gray-100 hover:bg-gray-200 text-gray-700'
                    }`}
                  >
                    <BookOpen className="w-4 h-4" />
                    <span className="font-medium">{subject.name}</span>
                    <span className={`ml-1 px-1.5 py-0.5 rounded-full text-xs ${
                      selectedSubjectId === subject.id ? 'bg-white/20' : 'bg-white/70 text-gray-700'
                    }`}>
                      {subject.count}
                    </span>
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* Results Count */}
          <div className="flex items-center justify-between pt-4 border-t border-gray-100">
            <div>
              <span className="text-gray-600">
                Showing {Math.min(displayedCourses.length, filteredCourses.length)} of {filteredCourses.length} courses
                {selectedSubjectId && ` in ${selectedSubject?.name}`}
              </span>
            </div>
            <Badge color="amber" icon={Star}>
              {filteredCourses.length} Courses Available
            </Badge>
          </div>
        </div>
      </ModernCard>

      {/* Results Header */}
      <div>
        <h2 className="text-2xl font-bold text-gray-900 mb-2">
          {selectedSubjectId ? selectedSubject?.name : 'All'} Courses
        </h2>
        <p className="text-gray-600 mb-6">
          Discover the perfect program for your academic journey
        </p>
      </div>

      {/* Courses Grid - 3 per row */}
      {displayedCourses.length > 0 ? (
        <>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {displayedCourses.map(course => {
              const isWishlistedCourse = isWishlisted({...course, type: 'course'});
              const courseSubject = subjects.find(s => s.id === course.subject_id);
              const isHovered = hoveredCourse === course.id;
              
              return (
                <ModernCard 
                  key={course.id}
                  className="group relative overflow-hidden"
                  onMouseEnter={() => setHoveredCourse(course.id)}
                  onMouseLeave={() => setHoveredCourse(null)}
                >
                  {/* Hover Gradient */}
                  <div className={`absolute inset-0 bg-gradient-to-br from-teal-500/5 to-blue-500/5 opacity-0 group-hover:opacity-100 transition-opacity duration-300 ${isHovered ? 'opacity-100' : ''}`}></div>
                  
                  <div className="relative p-5">
                    {/* Course Header */}
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex-1 pr-4">
                        <div className="flex items-center gap-1.5 mb-2">
                          {courseSubject && (
                            <Badge color="teal" icon={BookOpen} className="text-xs">
                              {courseSubject.name}
                            </Badge>
                          )}
                          {course.scholarship === 1 && (
                            <Badge color="amber" icon={Award} className="text-xs">
                              Scholarship
                            </Badge>
                          )}
                        </div>
                        <h3 className="text-base font-bold text-gray-900 mb-2 line-clamp-2 group-hover:text-teal-700 transition-colors">
                          {course.name}
                        </h3>
                      </div>
                      
                      {/* Action Buttons */}
                      <div className="flex gap-1">
                        <button
                          onClick={() => toggleWishlist({...course, type: 'course'})}
                          className={`p-1.5 rounded-md transition-all duration-300 ${isWishlistedCourse ? 'bg-red-50 text-red-500' : 'hover:bg-gray-100 text-gray-400 hover:text-gray-600'}`}
                          title={isWishlistedCourse ? 'Remove from wishlist' : 'Add to wishlist'}
                        >
                          {isWishlistedCourse ? (
                            <HeartFill className="w-4 h-4" />
                          ) : (
                            <Heart className="w-4 h-4" />
                          )}
                        </button>
                        
                        <button
                          onClick={() => {
                            Swal.fire({
                              title: 'Compare Course',
                              text: 'This course has been added to comparison.',
                              icon: 'success',
                              timer: 1500,
                              showConfirmButton: false,
                              background: '#ffffff',
                              color: '#1f2937'
                            });
                          }}
                          className="p-1.5 rounded-md hover:bg-blue-50 text-gray-400 hover:text-blue-600 transition-all duration-300"
                          title="Compare Course"
                        >
                          <Scale className="w-4 h-4" />
                        </button>
                      </div>
                    </div>

                    {/* Course Details Grid - Compact */}
                    <div className="grid grid-cols-2 gap-3 mb-4">
                      <div className="flex items-center gap-2 p-2 bg-gray-50 rounded-lg">
                        <div className="p-1.5 rounded-md bg-white border border-gray-200">
                          <Clock className="w-3.5 h-3.5 text-teal-600" />
                        </div>
                        <div className="min-w-0">
                          <div className="text-xs text-gray-500 truncate">Duration</div>
                          <div className="font-semibold text-gray-900 text-sm truncate">{course.duration || 'Flexible'}</div>
                        </div>
                      </div>

                      <div className="flex items-center gap-2 p-2 bg-gray-50 rounded-lg">
                        <div className="p-1.5 rounded-md bg-white border border-gray-200">
                          <DollarSign className="w-3.5 h-3.5 text-emerald-600" />
                        </div>
                        <div className="min-w-0">
                          <div className="text-xs text-gray-500 truncate">Tuition</div>
                          <div className="font-semibold text-gray-900 text-sm truncate">
                            {course.currency_symbol || ''}{course.tuition_fee || 'Contact'}
                          </div>
                        </div>
                      </div>

                      <div className="flex items-center gap-2 p-2 bg-gray-50 rounded-lg">
                        <div className="p-1.5 rounded-md bg-white border border-gray-200">
                          <Calendar className="w-3.5 h-3.5 text-amber-500" />
                        </div>
                        <div className="min-w-0">
                          <div className="text-xs text-gray-500 truncate">Intake</div>
                          <div className="font-semibold text-gray-900 text-sm truncate">{university.intake || 'Multiple'}</div>
                        </div>
                      </div>

                      <div className="flex items-center gap-2 p-2 bg-gray-50 rounded-lg">
                        <div className="p-1.5 rounded-md bg-white border border-gray-200">
                          <Globe className="w-3.5 h-3.5 text-blue-500" />
                        </div>
                        <div className="min-w-0">
                          <div className="text-xs text-gray-500 truncate">Language</div>
                          <div className="font-semibold text-gray-900 text-sm truncate">{course.language || 'English'}</div>
                        </div>
                      </div>
                    </div>

                    {/* Description */}
                    {course.description && (
                      <div className="mb-4">
                        <p className="text-gray-600 text-xs line-clamp-2 leading-relaxed">
                          {course.description}
                        </p>
                      </div>
                    )}

                    {/* Action Buttons */}
                    <div className="flex gap-2">
                      <Link 
                        href={`/${course.university_slug}/${course.course_slug}`}
                        className="group flex-1 flex items-center justify-center gap-1.5 bg-gradient-to-r from-teal-600 to-blue-500 text-white py-2.5 px-3 rounded-lg font-semibold hover:shadow-lg transition-all duration-300 text-sm"
                      >
                        View Details
                        <ArrowRight className="w-3.5 h-3.5 group-hover:translate-x-0.5 transition-transform" />
                      </Link>
                      
                      <button 
                        onClick={() => {
                          if (window.openApplyNowModal) {
                            const courseData = {
                              ...course,
                              type: 'course',
                              university: university?.name,
                              name: course.name
                            };
                            window.openApplyNowModal(courseData);
                          }
                        }}
                        className="flex-1 border border-teal-600 text-teal-600 py-2.5 px-3 rounded-lg font-semibold hover:bg-teal-600 hover:text-white transition-all duration-300 text-sm"
                      >
                        Apply Now
                      </button>
                    </div>
                  </div>
                </ModernCard>
              );
            })}
          </div>

          {/* Load More */}
          {hasMoreCourses && (
            <div className="flex justify-center mt-10">
              <button
                onClick={handleLoadMore}
                className="group px-8 py-4 bg-gradient-to-r from-teal-600 to-blue-500 text-white rounded-2xl font-semibold hover:shadow-xl transition-all duration-300 flex items-center gap-3"
              >
                Load More Courses
                <ChevronDown className="w-5 h-5 group-hover:translate-y-1 transition-transform" />
              </button>
            </div>
          )}

          {/* End Results Count */}
          <div className="text-center text-gray-600 text-sm mt-6">
            Showing {Math.min(displayedCourses.length, filteredCourses.length)} of {filteredCourses.length} courses
            {selectedSubjectId && ` in ${selectedSubject?.name}`}
          </div>
        </>
      ) : (
        <ModernCard className="text-center py-16">
          <div className="max-w-md mx-auto">
            <div className="inline-flex p-6 rounded-2xl bg-gradient-to-r from-teal-50 to-blue-50 mb-6">
              <div className="text-4xl">🔍</div>
            </div>
            <h3 className="text-xl font-bold text-gray-900 mb-3">No Courses Found</h3>
            <p className="text-gray-600 mb-6">
              {selectedSubjectId || courseSearchTerm 
                ? "Try adjusting your search or filters to find what you're looking for."
                : "No courses available at the moment."}
            </p>
            
            {(selectedSubjectId || courseSearchTerm) && (
              <button
                onClick={clearAllFilters}
                className="px-6 py-3 bg-gradient-to-r from-teal-600 to-blue-500 text-white rounded-xl font-semibold hover:shadow-lg transition-all duration-300"
              >
                Clear All Filters
              </button>
            )}
          </div>
        </ModernCard>
      )}

      {/* Consultation Modal */}
      <FreeConsultationModal
        isOpen={isConsultationModalOpen}
        title="Course Consultation"
        description={`Get expert guidance about ${selectedCourse?.name} - completely free!`}
      />

      {/* Apply Now Modal */}
      <ApplyNowModal />
    </div>
  );
};

export default UniversityCourses;