// components/organisms/ScholarshipsSection.jsx
'use client';
import React, { useState, useEffect, useRef } from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Autoplay, Pagination, Navigation } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/pagination';
import 'swiper/css/navigation';
import Image from "next/image";
import Link from 'next/link';

// Define the scholarship type based on your data structure
interface Scholarship {
  id: number;
  slug: string;
  title: string;
  image: string;
  currency_symbol: string;
  amount_min: number;
  amount_max: number;
  cgpa: string;
  description: string;
  country_name: string;
  qualifications: Qualification[]; // Changed to array of qualifications
  created_at?: string;
}

interface Qualification {
  qualification_id: number;
  qualification_name: string;
}

interface ScholarshipsSectionProps {
  scholarshipsData: Scholarship[]; // Data passed from server component
}

const ScholarshipsSection = ({ scholarshipsData }: ScholarshipsSectionProps) => {
  const [activeScholarship, setActiveScholarship] = useState(0);
  const [displayScholarships, setDisplayScholarships] = useState<Scholarship[]>([]);
  const swiperRef = useRef<any>(null);

  const formatAmountRange = (amount_min: number, amount_max: number, currency_symbol = '$') => {
    if (!amount_min && !amount_max) return 'Not specified';
    
    const symbol = currency_symbol || '$';
    
    if (amount_min && amount_max) {
      return `${symbol}${amount_min} - ${symbol}${amount_max}`;
    }
    
    if (amount_min && !amount_max) {
      return `${symbol}${amount_min}+`;
    }
    
    if (!amount_min && amount_max) {
      return `Up to ${symbol}${amount_max}`;
    }
    
    return 'Not specified';
  };

  // Format qualifications display
  const formatQualifications = (qualifications: Qualification[]) => {
    if (!qualifications || qualifications.length === 0) {
      return 'Not specified';
    }
    
    if (qualifications.length === 1) {
      return qualifications[0].qualification_name;
    }
    
    // Show first 2 qualifications and count of remaining
    const firstTwo = qualifications.slice(0, 2).map(q => q.qualification_name).join(', ');
    
    if (qualifications.length > 2) {
      return `${firstTwo} +${qualifications.length - 2} more`;
    }
    
    return firstTwo;
  };

  // Format CGPA function
  const formatCGPA = (cgpa: string) => {
    if (!cgpa) return 'Not specified';
    
    // Check if CGPA is a number
    const numCGPA = parseFloat(cgpa);
    if (!isNaN(numCGPA)) {
      return `CGPA: ${numCGPA.toFixed(1)}`;
    }
    
    return cgpa; // Return as is if it's not a number
  };

  // Strip HTML tags from description
  const stripHtml = (html: string) => {
    if (!html) return 'No description available';
    return html.replace(/<[^>]*>/g, '').substring(0, 120) + '...';
  };

  // Set display scholarships when component mounts or scholarshipsData changes
  useEffect(() => {
    setDisplayScholarships(scholarshipsData && scholarshipsData.length > 0 ? scholarshipsData : []);
  }, [scholarshipsData]);

  // Manual navigation handlers
  const handleNext = () => {
    if (swiperRef.current) {
      swiperRef.current.swiper.slideNext();
    }
  };

  const handlePrev = () => {
    if (swiperRef.current) {
      swiperRef.current.swiper.slidePrev();
    }
  };

  return (
    <section className="py-20 bg-linear-to-b from-gray-50 to-white relative">

      <div className="container mx-auto px-4 sm:px-6 lg:px-8 relative z-10">
        {/* 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">
            <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 14l9-5-9-5-9 5 9 5z" />
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 14l9-5-9-5-9 5 9 5z" />
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 14v6l9-5M12 20l-9-5" />
            </svg>
          </div>
          <h2 className="text-3xl md:text-4xl font-bold text-gray-900 mb-4">
            Featured <span className="text-transparent bg-clip-text bg-linear-to-r from-teal-600 to-blue-500">Scholarships</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">
            Discover amazing scholarship opportunities to fund your international education dreams with the <b>Universities Page</b>. Our platform is designed to help students explore a variety of scholarships and financial aid options while receiving expert support through our international education services and international education advisory services. Whether you are planning to pursue Higher Education Abroad or join specialized Study Abroad Programs, the right scholarship can make your academic journey more affordable and stress-free.
          </p>
        </div>

        {/* Scholarships Swiper */}
        <div className="max-w-7xl mx-auto relative">
          <Swiper
            ref={swiperRef}
            modules={[Autoplay, Pagination, Navigation]}
            spaceBetween={30}
            slidesPerView={1}
            breakpoints={{
              640: { slidesPerView: 1 },
              768: { slidesPerView: 2 },
              1024: { slidesPerView: 3 },
            }}
            autoplay={{ 
              delay: 4000,
              disableOnInteraction: false,
              pauseOnMouseEnter: true
            }}
            pagination={{
              clickable: true,
              el: '.scholarships-pagination',
            }}
            navigation={{
              nextEl: '.scholarships-button-next',
              prevEl: '.scholarships-button-prev',
            }}
            loop={displayScholarships.length > 1}
            grabCursor={true}
            speed={800}
            onSlideChange={(swiper) => setActiveScholarship(swiper.realIndex)}
            className="pb-16"
          >
            {displayScholarships.map((scholarship, index) => (
              <SwiperSlide key={scholarship.id}>
                {/* MAIN FIX: Added h-full to the slide container and set consistent height */}
                <div className="h-full">
                  <div className="bg-white rounded-2xl shadow-lg hover:shadow-xl transition-all duration-500 h-full border border-gray-100 group hover:border-teal-600/20 overflow-hidden flex flex-col">
                    
                    {/* Scholarship Image - Fixed height */}
                    <div className="relative h-48 overflow-hidden">
                      <Image
                        src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${scholarship.image}` || 'https://images.unsplash.com/photo-1523050854058-8df90110c9f1?ixlib=rb-4.0.3&w=400'}
                        alt={scholarship.title}
                        fill
                        className="object-cover group-hover:scale-105 transition-transform duration-500"
                        sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 33vw"
                      />
                      
                      {/* Amount Badge */}
                      <div className="absolute top-4 right-4">
                        <div className="px-3 py-1 rounded-full bg-linear-to-r from-teal-600 to-blue-500 text-white text-xs font-semibold shadow-md">
                          {formatAmountRange(scholarship.amount_min, scholarship.amount_max, scholarship.currency_symbol)}
                        </div>
                      </div>

                      {/* Overlay linear */}
                      <div className="absolute inset-0 bg-linear-to-t from-black/20 to-transparent"></div>
                    </div>

                    {/* Scholarship Content - Fixed structure with consistent spacing */}
                    <div className="p-6 flex flex-col grow">
                      {/* Title - Fixed height with line clamp */}
                      <Link href={`/scholarships/${scholarship.slug}`}>
                        <h3 className="text-xl font-bold text-gray-900 mb-3 line-clamp-2 min-h-14 group-hover:text-teal-600 transition-colors duration-300">
                          {scholarship.title}
                        </h3>
                      </Link>

                      {/* Description - Fixed height with line clamp */}
                      <p className="text-gray-600 leading-relaxed mb-4 line-clamp-3 min-h-18 grow">
                        {stripHtml(scholarship.description)}
                      </p>

                      {/* Details Grid - Consistent spacing */}
                      <div className="grid grid-cols-2 gap-3 mb-4">
                        {/* Location */}
                        <div className="flex items-start space-x-2">
                          <svg className="w-4 h-4 text-teal-600 shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                          </svg>
                          <span className="text-sm text-gray-600 truncate" title={scholarship.country_name || 'Not specified'}>
                            {scholarship.country_name || 'Not specified'}
                          </span>
                        </div>
                        
                        {/* Qualification */}
                        <div className="flex items-start space-x-2">
                          <svg className="w-4 h-4 text-teal-600 shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 14l9-5-9-5-9 5 9 5z" />
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 14l9-5-9-5-9 5 9 5z" />
                          </svg>
                          <span className="text-sm text-gray-600 truncate" title={formatQualifications(scholarship.qualifications)}>
                            {formatQualifications(scholarship.qualifications)}
                          </span>
                        </div>

                        {/* Amount */}
                        <div className="flex items-start space-x-2">
                          <svg className="w-4 h-4 text-teal-600 shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1" />
                          </svg>
                          <span className="text-sm text-gray-600 font-medium truncate">
                            {formatAmountRange(scholarship.amount_min, scholarship.amount_max, scholarship.currency_symbol)}
                          </span>
                        </div>
                        
                        {/* CGPA */}
                        <div className="flex items-start space-x-2">
                          <svg className="w-4 h-4 text-teal-600 shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                          </svg>
                          <span className="text-sm text-gray-600 truncate">
                            {formatCGPA(scholarship.cgpa)}
                          </span>
                        </div>
                      </div>

                      {/* Apply Button - Fixed at bottom */}
                      <div className="mt-auto pt-4">
                        <Link href={`/scholarships/${scholarship.slug}`}>
                          <button className="w-full bg-linear-to-r from-teal-600 to-blue-500 text-white py-3 rounded-xl font-semibold hover:shadow-lg transition-all duration-300 transform hover:scale-[1.02] flex items-center justify-center space-x-2 group cursor-pointer shadow-md">
                            <span>View Details</span>
                            <svg className="w-4 h-4 transform group-hover:translate-x-1 transition-transform duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14 5l7 7m0 0l-7 7m7-7H3" />
                            </svg>
                          </button>
                        </Link>
                      </div>
                    </div>
                  </div>
                </div>
              </SwiperSlide>
            ))}
          </Swiper>

          {/* Show navigation only if there are scholarships */}
          {displayScholarships.length > 0 && (
            <>
              {/* Custom Pagination */}
              <div className="scholarships-pagination flex justify-center space-x-2 mt-8">
                {/* Pagination dots will be injected here by Swiper */}
              </div>

              {/* Navigation Buttons */}
              <div className="flex justify-center items-center space-x-4 mt-8">
                <button 
                  className="scholarships-button-prev w-12 h-12 rounded-full bg-white shadow-lg flex items-center justify-center text-teal-600 hover:bg-teal-600 hover:text-white transition-all duration-300 focus:outline-none focus:ring-4 focus:ring-teal-600/20 group"
                  onClick={handlePrev}
                  aria-label="Previous scholarship"
                >
                  <svg className="w-6 h-6 transform group-hover:scale-110" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                  </svg>
                </button>
                
                <div className="text-sm text-gray-600 font-medium min-w-15 text-center">
                  {activeScholarship + 1} / {displayScholarships.length}
                </div>
                
                <button 
                  className="scholarships-button-next w-12 h-12 rounded-full bg-white shadow-lg flex items-center justify-center text-teal-600 hover:bg-teal-600 hover:text-white transition-all duration-300 focus:outline-none focus:ring-4 focus:ring-teal-600/20 group"
                  onClick={handleNext}
                  aria-label="Next scholarship"
                >
                  <svg className="w-6 h-6 transform group-hover:scale-110" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>
                </button>
              </div>
            </>
          )}

          {/* No Scholarships Message */}
          {displayScholarships.length === 0 && (
            <div className="text-center py-12">
              <div className="bg-white rounded-lg p-8 max-w-md mx-auto shadow-lg">
                <svg className="w-16 h-16 text-gray-400 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 14l9-5-9-5-9 5 9 5z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 14l9-5-9-5-9 5 9 5z" />
                </svg>
                <h3 className="text-lg font-semibold text-gray-900 mb-2">No Scholarships Available</h3>
                <p className="text-gray-600">Check back later for new scholarship opportunities.</p>
              </div>
            </div>
          )}
        </div>

        {/* CTA Section */}
        <div className="text-center mt-16">
          <div className="bg-linear-to-r from-teal-600 to-blue-500 rounded-2xl p-8 max-w-4xl mx-auto shadow-xl">
            <h3 className="text-2xl font-bold text-white mb-4">Scholarship Opportunities with International Education Services</h3>
            <p className="text-white/90 mb-6 max-w-4xl mx-auto">
              Discover hundreds of scholarships designed to match your profile and study goals on Universities Page. Our expert international education services and international education advisory services guide you through Higher Education Abroad, Study Abroad Programs, and Overseas Education Opportunities, while providing support for Student Visa & Admission Services and trusted Global Education Services to make your scholarship journey simple and successful.
            </p>
            <div className="flex flex-col sm:flex-row gap-4 justify-center">
              <Link href="/scholarships">
                <button className="px-8 py-3 bg-white text-teal-600 font-semibold rounded-lg hover:bg-gray-100 transition-all duration-300 transform hover:-translate-y-1 hover:scale-105 shadow-lg">
                  Browse All Scholarships
                </button>
              </Link>
              <Link href="/contact">
                <button className="px-8 py-3 bg-transparent border-2 border-white text-white font-semibold rounded-lg hover:bg-white hover:text-teal-600 transition-all duration-300 transform hover:-translate-y-1 hover:scale-105">
                  Get Scholarship Advice
                </button>
              </Link>
            </div>
          </div>
        </div>
      </div>

      {/* Add custom CSS for Swiper pagination */}
      <style jsx global>{`
        .scholarships-pagination .swiper-pagination-bullet {
          width: 12px;
          height: 12px;
          background: #E5E7EB;
          border-radius: 50%;
          margin: 0 4px;
          cursor: pointer;
          transition: all 0.3s ease;
          opacity: 1;
        }
        
        .scholarships-pagination .swiper-pagination-bullet-active {
          background: linear-linear(135deg, #0d9488, #3b82f6);
          transform: scale(1.2);
        }
        
        .scholarships-pagination {
          position: relative;
          margin-top: 2rem;
        }

        /* Line clamp utilities */
        .line-clamp-2 {
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        
        .line-clamp-3 {
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        /* Swiper slide height */
        .swiper-slide {
          height: auto !important;
        }

        /* Swiper navigation button states */
        .scholarships-button-next.swiper-button-disabled,
        .scholarships-button-prev.swiper-button-disabled {
          opacity: 0.5;
          cursor: not-allowed;
          transform: none;
        }

        .scholarships-button-next.swiper-button-disabled:hover,
        .scholarships-button-prev.swiper-button-disabled:hover {
          background: white;
          color: #0d9488;
          transform: none;
        }
      `}</style>
    </section>
  );
};

export default ScholarshipsSection;