'use client';
import { useEffect, useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { 
  BookOpen, 
  GraduationCap, 
  Clock, 
  Calendar, 
  Globe, 
  DollarSign, 
  Tag, 
  Briefcase,
  Award,
  Users,
  MapPin,
  ChevronRight,
  Sparkles,
  Shield,
  Zap,
  MessageSquare,
  Filter
} from 'lucide-react';
import CourseCard from '../../components/molecules/CourseCard';
import FreeConsultationModal from '../organisms/FreeConsultationModal';
import ApplyNowModal from './ApplyNowModal';
import ModernCard from '../../components/shared/ModernCard';
import FeatureCard from '../../components/shared/FeatureCard';

const CourseDetailPage = ({s_course}) => {
  const [course, setCourse] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [relatedCourses, setRelatedCourses] = useState([]);

  const [isConsultationModalOpen, setIsConsultationModalOpen] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null);

  // Function to open consultation modal
  const openConsultationModal = (item) => {
    setSelectedItem(item);
    setIsConsultationModalOpen(true);
  };

  // Function to close consultation modal
  const closeConsultationModal = () => {
    setIsConsultationModalOpen(false);
    setSelectedItem(null);
  };

  // Function to open Apply Now modal using the global function
  const openApplyNowModal = () => {
    if (!course) return;
    
    // Prepare the item data in the same format as your other pages
    const itemData = {
      type: 'course',
      id: course.id,
      name: course.name,
      university: course.university_name,
      courseName: course.name,
      university_name: course.university_name,
      location: course.location,
      consultation_fee: course.consultation_fee,
      consultation_fee_discount: course.consultation_fee_discount,
      consultation_fee_after_discount: course.consultation_fee_after_discount,
      currency: course.currency
    };
    
    // Call the global function that's already set up in your ApplyNowModal
    if (window.openApplyNowModal) {
      window.openApplyNowModal(itemData);
    } else {
      console.warn('ApplyNowModal not available');
    }
  };

  const formatDuration = () => {
    if (course.duration && course.duration_type) {
      return `${course.duration} ${course.duration_type}`;
    } else if (course.duration) {
      return `${course.duration} months`;
    }
    return 'N/A';
  };

  const formatCurrency = (amount, currency, type) => {
    if (amount === null || amount === undefined) return 'N/A';
    if (type === '$') {
      return `$${parseFloat(amount).toLocaleString()}`;
    } else if(type === 'PKR'){
      return `PKR ${parseFloat(amount).toLocaleString()}`;
    } else {
      return `${currency || 'PKR'} ${parseFloat(amount).toLocaleString()}`;
    }
  };

  const formatScholarship = (scholarship) => {
    if (scholarship === 1 || scholarship === '1' || scholarship === true) {
      return 'Available';
    } else if (scholarship === 0 || scholarship === '0' || scholarship === false) {
      return 'Not Available';
    }
    return 'N/A';
  };

  useEffect(() => {
    try {
      setLoading(true);
      if(!s_course.success){
        throw new Error(s_course.message);
      }

      if(s_course.success){
        setCourse(s_course.data);
        setRelatedCourses(s_course.relatedcourse || []);
      } else {
        console.log(s_course.message);
        setError(s_course.message);
      }
    } catch (error){
      console.log(error.message);
      setError(error.message);
      setLoading(false)
    } finally{
      setLoading(false);
    }
  }, [s_course]);

  if (loading) {
    return (
      <div className="min-h-screen bg-linear-to-b from-gray-50 to-white flex items-center justify-center">
        <div className="text-center">
          <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-4">
            <Sparkles className="w-5 h-5" />
            Loading Course Details
          </div>
          <p className="text-gray-600">Please wait while we fetch the course information...</p>
        </div>
      </div>
    );
  }

  if (error || !course) {
    return (
      <div className="min-h-screen bg-linear-to-b from-gray-50 to-white flex items-center justify-center">
        <div className="text-center">
          <div className="inline-flex items-center gap-2 bg-linear-to-r from-red-100 to-pink-100 text-red-700 px-6 py-3 rounded-full text-sm font-semibold mb-4">
            <Shield className="w-5 h-5" />
            Course Not Found
          </div>
          <p className="text-gray-600 mb-6">{error || 'The requested course could not be found.'}</p>
          <Link href="/">
            <button className="bg-linear-to-r from-teal-600 to-blue-500 text-white px-6 py-3 rounded-xl hover:from-teal-700 hover:to-blue-600 transition font-medium">
              Go Back Home
            </button>
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-linear-to-b from-gray-50 to-white pb-24">
      {/* Hero Section */}
      <div className="relative">
        <div className="absolute inset-0 bg-linear-to-r from-teal-50/50 to-blue-50/50"></div>
        
        <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-16 md:py-24">
          <div className="text-center">
            <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-6 animate-pulse">
              <Sparkles className="w-5 h-5" />
              Featured Course
            </div>

            <h1 className="text-4xl md:text-6xl font-bold text-gray-900 mb-6 leading-tight">
              {course.title || course.name}
            </h1>

            <p className="text-lg md:text-xl text-gray-600 mb-8 max-w-3xl mx-auto leading-relaxed">
              Offered by {course.university_name || 'Unknown University'} • {course.location || 'Multiple Locations'}
            </p>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="pb-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* University Info Card */}
          <ModernCard className="p-8 mb-8">
            <div className="flex flex-col lg:flex-row items-center gap-8">
              <div className="flex-1">
                <div className="flex items-center gap-6">
                  <div className="p-3 rounded-xl bg-linear-to-r from-teal-50 to-blue-50 border border-teal-100">
                    <div className="relative w-20 h-20">
                      <Image
                        src={
                          course.universityLogo && course.universityLogo.trim() !== ""
                            ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${course.universityLogo.replace(/^\/+/, "")}`
                            : "/assets/default-course.webp"
                        }
                        alt={course.university || "university logo"}
                        fill
                        className="object-contain"
                      />
                    </div>
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold text-gray-900 mb-2">
                      {course.university_name || 'Unknown University'}
                    </h2>
                    <div className="flex items-center text-gray-600">
                      <MapPin className="w-4 h-4 mr-2 text-teal-600" />
                      {course.location || 'Location not specified'}
                    </div>
                  </div>
                </div>
              </div>

            </div>
          </ModernCard>

          {/* Course Details Grid */}
          <div className="grid lg:grid-cols-3 gap-8 mb-12">
            {/* Left Column - Course Information */}
            <div className="lg:col-span-2 space-y-8">
              <ModernCard className="p-8">
                <div className="flex items-center gap-4 mb-8">
                  <div className="p-3 rounded-xl bg-linear-to-r from-teal-50 to-blue-50 border border-teal-100">
                    <BookOpen className="w-8 h-8 text-teal-600" />
                  </div>
                  <div>
                    <h3 className="text-2xl font-bold text-gray-900">Course Overview</h3>
                    <p className="text-gray-600 mt-1">Complete program details and requirements</p>
                  </div>
                </div>

                <div className="grid md:grid-cols-2 gap-6">
                  <div className="flex items-center gap-4 p-4 rounded-xl border border-gray-200">
                    <div className="p-3 rounded-lg bg-linear-to-r from-teal-50 to-blue-50">
                      <BookOpen className="w-5 h-5 text-teal-600" />
                    </div>
                    <div>
                      <p className="text-sm text-gray-600">Subject</p>
                      <p className="font-semibold text-gray-900">{course?.subject_name || 'N/A'}</p>
                    </div>
                  </div>

                  <div className="flex items-center gap-4 p-4 rounded-xl border border-gray-200">
                    <div className="p-3 rounded-lg bg-linear-to-r from-teal-50 to-blue-50">
                      <GraduationCap className="w-5 h-5 text-blue-600" />
                    </div>
                    <div>
                      <p className="text-sm text-gray-600">Qualification</p>
                      <p className="font-semibold text-gray-900">{course?.qualification || 'N/A'}</p>
                    </div>
                  </div>

                  <div className="flex items-center gap-4 p-4 rounded-xl border border-gray-200">
                    <div className="p-3 rounded-lg bg-linear-to-r from-teal-50 to-blue-50">
                      <Clock className="w-5 h-5 text-emerald-600" />
                    </div>
                    <div>
                      <p className="text-sm text-gray-600">Duration</p>
                      <p className="font-semibold text-gray-900">{formatDuration()}</p>
                    </div>
                  </div>

                  <div className="flex items-center gap-4 p-4 rounded-xl border border-gray-200">
                    <div className="p-3 rounded-lg bg-linear-to-r from-teal-50 to-blue-50">
                      <Calendar className="w-5 h-5 text-amber-600" />
                    </div>
                    <div>
                      <p className="text-sm text-gray-600">Intakes</p>
                      <p className="font-semibold text-gray-900">{course?.intake || 'N/A'}</p>
                    </div>
                  </div>

                  <div className="flex items-center gap-4 p-4 rounded-xl border border-gray-200">
                    <div className="p-3 rounded-lg bg-linear-to-r from-teal-50 to-blue-50">
                      <Globe className="w-5 h-5 text-purple-600" />
                    </div>
                    <div>
                      <p className="text-sm text-gray-600">Languages</p>
                      <p className="font-semibold text-gray-900">{course?.languages || course?.language || 'English'}</p>
                    </div>
                  </div>

                  <div className="flex items-center gap-4 p-4 rounded-xl border border-gray-200">
                    <div className="p-3 rounded-lg bg-linear-to-r from-teal-50 to-blue-50">
                      <DollarSign className="w-5 h-5 text-green-600" />
                    </div>
                    <div>
                      <p className="text-sm text-gray-600">Tuition Fee</p>
                      <p className="font-semibold text-gray-900">{formatCurrency(course?.yearly_fee, course?.currency, course?.curreny_symbol)}</p>
                    </div>
                  </div>

                  <div className="flex items-center gap-4 p-4 rounded-xl border border-gray-200">
                    <div className="p-3 rounded-lg bg-linear-to-r from-teal-50 to-blue-50">
                      <DollarSign className="w-5 h-5 text-blue-600" />
                    </div>
                    <div>
                      <p className="text-sm text-gray-600">Consultation Fee</p>
                      <p className="font-semibold text-gray-900">{formatCurrency(course?.consultation_fee, course?.currency, 'PKR')}</p>
                    </div>
                  </div>

                  {course?.consultation_fee_discount && (
                    <div className="flex items-center gap-4 p-4 rounded-xl border border-green-200 bg-green-50">
                      <div className="p-3 rounded-lg bg-linear-to-r from-green-50 to-emerald-50">
                        <Tag className="w-5 h-5 text-green-600" />
                      </div>
                      <div>
                        <p className="text-sm text-gray-600">Discount</p>
                        <p className="font-semibold text-green-700">{course?.consultation_fee_discount}% OFF</p>
                      </div>
                    </div>
                  )}

                  {course?.consultation_fee_after_discount && (
                    <div className="flex items-center gap-4 p-4 rounded-xl border border-gray-200">
                      <div className="p-3 rounded-lg bg-linear-to-r from-teal-50 to-blue-50">
                        <DollarSign className="w-5 h-5 text-teal-600" />
                      </div>
                      <div>
                        <p className="text-sm text-gray-600">Fee After Discount</p>
                        <p className="font-semibold text-gray-900">
                          {formatCurrency(course?.consultation_fee_after_discount, course?.currency, 'PKR')}
                        </p>
                      </div>
                    </div>
                  )}

                  <div className="flex items-center gap-4 p-4 rounded-xl border border-gray-200">
                    <div className="p-3 rounded-lg bg-linear-to-r from-teal-50 to-blue-50">
                      <Award className="w-5 h-5 text-amber-600" />
                    </div>
                    <div>
                      <p className="text-sm text-gray-600">Scholarship</p>
                      <p className="font-semibold text-gray-900">{formatScholarship(course?.scholarship)}</p>
                    </div>
                  </div>
                </div>
              </ModernCard>
            </div>

            {/* Right Column - Key Benefits & Actions */}
            <div className="space-y-8">
              <ModernCard className="p-8">
                <div className="flex items-center gap-4 mb-6">
                  <div className="p-3 rounded-xl bg-linear-to-r from-teal-50 to-blue-50 border border-teal-100">
                    <Sparkles className="w-6 h-6 text-teal-600" />
                  </div>
                  <h3 className="text-xl font-bold text-gray-900">Why Choose This Program?</h3>
                </div>

                <div className="space-y-4">
                  <FeatureCard
                    Icon={GraduationCap}
                    title="Industry Recognition"
                    description="Globally accredited degree with industry partnerships"
                    color="teal"
                    size="small"
                  />

                  <FeatureCard
                    Icon={Users}
                    title="Expert Faculty"
                    description="Learn from industry professionals and academic experts"
                    color="blue"
                    size="small"
                  />

                  <FeatureCard
                    Icon={Briefcase}
                    title="Career Support"
                    description="Dedicated career services and internship placement"
                    color="emerald"
                    size="small"
                  />

                  <FeatureCard
                    Icon={Globe}
                    title="Global Network"
                    description="Join an international alumni community"
                    color="purple"
                    size="small"
                  />
                </div>
              </ModernCard>
            </div>
          </div>

          {/* Related Courses Section */}
          <div className="mt-16">
            <div className="text-center mb-12">
              <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-4">
                <GraduationCap className="w-5 h-5" />
                Related Courses
              </div>
              <h2 className="text-3xl font-bold text-gray-900 mb-4">
                Explore Similar <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">Programs</span>
              </h2>
              <p className="text-gray-600 max-w-2xl mx-auto">
                Discover similar programs that match your academic interests and career goals
              </p>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-12">
              {relatedCourses.slice(0, 3).map((related) => (
                <CourseCard
                  key={related.id}
                  id={related.id}
                  image={related.image}
                  title={related.title || related.name}
                  university={related.university_name}
                  location={related.location}
                  flagimage={related.flag_image}
                  country_name={related.country_name}
                  slug={related.slug}
                  university_slug={related.university_slug}
                />
              ))}
            </div>
            
            <div className="text-center mb-16">
              <Link 
                href="/courses"
                className="inline-flex items-center gap-2 bg-linear-to-r from-teal-600 to-blue-500 text-white px-8 py-3 rounded-xl hover:from-teal-700 hover:to-blue-600 transition font-medium"
              >
                View All Courses
                <ChevronRight className="w-5 h-5" />
              </Link>
            </div>
          </div>

          {/* CTA Section - Added after related courses */}
          <div className="bg-linear-to-r from-teal-600 to-blue-500 rounded-3xl p-12 text-center mb-20">
            <div className="max-w-2xl mx-auto">
              <div className="inline-flex items-center gap-2 bg-white/20 backdrop-blur-sm px-6 py-2 rounded-full mb-6">
                <MessageSquare className="w-5 h-5 text-white" />
                <span className="text-sm font-semibold text-white">Get Expert Guidance</span>
              </div>
              
              <h2 className="text-3xl font-bold text-white mb-4">
                Ready to Start Your Journey?
              </h2>
              
              <p className="text-white/80 text-lg mb-8 max-w-xl mx-auto">
                Get free personalized consultation from our education experts and take the first step toward your dream education.
              </p>
              
              <div className="flex flex-col sm:flex-row gap-4 justify-center">
                <button 
                  onClick={() => openConsultationModal(course)}
                  className="inline-flex items-center justify-center gap-2 bg-white/20 backdrop-blur-sm text-white font-semibold py-3 px-8 rounded-xl hover:bg-white/30 transition-all duration-300"
                >
                  <Sparkles className="w-5 h-5" />
                  Free Consultation
                </button>
                
                <Link 
                  href="/courses"
                  className="inline-flex items-center justify-center gap-2 border-2 border-white/30 text-white font-semibold py-3 px-8 rounded-xl hover:bg-white/10 transition-all duration-300"
                >
                  <Filter className="w-5 h-5" />
                  Browse All Programs
                </Link>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Sticky Apply Now Section */}
      <div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 shadow-xl z-40">
        <div className="max-w-7xl mx-auto px-4">
          <div className="flex flex-col sm:flex-row items-center justify-between p-4 gap-4">
            <div className="flex-1">
              <div className="flex flex-col sm:flex-row items-start sm:items-center gap-2 sm:gap-4">
                <div className="flex items-center gap-2">
                  {course?.consultation_fee_discount ? (
                    <>
                      <span className="text-lg font-bold text-gray-900">
                        {formatCurrency(course?.consultation_fee_after_discount, course?.currency, 'PKR')}
                      </span>
                      <span className="text-sm text-gray-500 line-through">
                        {formatCurrency(course?.consultation_fee, course?.currency, 'PKR')}
                      </span>
                      <span className="bg-green-100 text-green-800 text-xs font-semibold px-2 py-1 rounded-full">
                        {course?.consultation_fee_discount}% OFF
                      </span>
                    </>
                  ) : (
                    <span className="text-lg font-bold text-gray-900">
                      {formatCurrency(course?.consultation_fee, course?.currency, 'PKR')}
                    </span>
                  )}
                </div>
                
                <div className="hidden sm:block">
                  <span className="text-xs text-gray-600">
                    Consultation Fee • {course?.university_name}
                  </span>
                </div>
              </div>
              
              <div className="sm:hidden mt-1">
                <span className="text-xs text-gray-500 truncate block">
                  {course?.university_name}
                </span>
              </div>
            </div>

            <div className="flex w-full sm:w-auto gap-3">
              <button 
                onClick={() => openConsultationModal(course)}
                className="flex-1 sm:flex-none border border-teal-600 text-teal-600 text-center py-2 px-4 rounded-lg hover:bg-teal-600 hover:text-white transition-all duration-300 font-semibold text-sm"
              >
                Consultation
              </button>
              
              <button 
                onClick={openApplyNowModal}
                className="flex-1 sm:flex-none bg-gray-900 text-white text-center py-2 px-6 rounded-lg hover:bg-black transition-all duration-300 font-semibold text-sm flex items-center justify-center gap-2"
              >
                <Zap className="w-4 h-4" />
                Apply Now
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <FreeConsultationModal
        isOpen={isConsultationModalOpen}
        onClose={closeConsultationModal}
        title=""
        description={`Get expert guidance about ${selectedItem?.university || selectedItem?.name} - completely free!`}
      />
      <ApplyNowModal />
    </div>
  );
};

export default CourseDetailPage;