'use client';
import React, { useState, useEffect, useRef } from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Autoplay, Pagination, Navigation, EffectCreative } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/pagination';
import 'swiper/css/navigation';
import 'swiper/css/effect-creative';
import Image from "next/image";
import Link from 'next/link';
import { 
  FaStar, 
  FaMapMarkerAlt, 
  FaBriefcase, 
  FaCheckCircle,
  FaBuilding,
  FaGraduationCap,
  FaUsers,
  FaPhone
} from 'react-icons/fa';
import { MdVerified, MdNavigateNext, MdNavigateBefore } from 'react-icons/md';

const FeaturedConsultants = ({ consultantsData = [] }) => {
  const [activeIndex, setActiveIndex] = useState(0);
  const [isBeginning, setIsBeginning] = useState(true);
  const [isEnd, setIsEnd] = useState(false);
  const swiperRef = useRef(null);

  // Set up navigation states
  useEffect(() => {
    if (swiperRef.current && swiperRef.current.swiper) {
      const swiper = swiperRef.current.swiper;
      setIsBeginning(swiper.isBeginning);
      setIsEnd(swiper.isEnd);
    }
  }, [activeIndex]);

  // Manual navigation handlers
  const handleNext = () => {
    if (swiperRef.current && swiperRef.current.swiper && !isEnd) {
      swiperRef.current.swiper.slideNext();
    }
  };

  const handlePrev = () => {
    if (swiperRef.current && swiperRef.current.swiper && !isBeginning) {
      swiperRef.current.swiper.slidePrev();
    }
  };

  // Format rating stars
  const renderStars = (rating) => {
    const stars = [];
    const fullStars = Math.floor(rating || 0);
    
    for (let i = 1; i <= 5; i++) {
      if (i <= fullStars) {
        stars.push(
          <FaStar 
            key={i} 
            className="w-4 h-4 text-yellow-400 fill-current" 
          />
        );
      } else {
        stars.push(
          <FaStar 
            key={i} 
            className="w-4 h-4 text-gray-300 fill-current" 
          />
        );
      }
    }
    return stars;
  };

  // Get badge color
  const getBadgeColor = (badge) => {
    const colors = {
      'Top Rated': 'from-yellow-500 to-amber-500',
      'Highly Rated': 'from-green-500 to-emerald-500',
      'Experienced': 'from-blue-500 to-cyan-500',
      'Fast Responder': 'from-purple-500 to-pink-500',
      'Premium': 'from-orange-500 to-red-500'
    };
    return colors[badge] || 'from-gray-500 to-gray-600';
  };

  // Get expertise color
  const getExpertiseColor = (score) => {
    if (score >= 80) return 'text-green-600';
    if (score >= 60) return 'text-blue-600';
    if (score >= 40) return 'text-amber-500';
    return 'text-red-500';
  };

  // Get image URL
  const getImageUrl = (profilePicture) => {
    if (!profilePicture) return '/default-consultant.jpg';
    if (profilePicture.startsWith('http')) return profilePicture;
    
    if (process.env.NEXT_PUBLIC_AWS_BUCKET && process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION) {
      return `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${profilePicture}`;
    }
    
    return profilePicture;
  };

  // Handle slide change
  const handleSlideChange = (swiper) => {
    setActiveIndex(swiper.realIndex);
    setIsBeginning(swiper.isBeginning);
    setIsEnd(swiper.isEnd);
  };

  return (
    <section className="py-12 md:py-20 bg-gradient-to-b from-white to-gray-50 relative overflow-hidden">
      
      {/* Animated Background */}
      <div className="absolute inset-0 opacity-5">
        <div className="absolute top-0 left-1/4 w-64 h-64 bg-blue-400 rounded-full mix-blend-multiply filter blur-3xl opacity-20 animate-pulse"></div>
        <div className="absolute bottom-0 right-1/4 w-64 h-64 bg-teal-400 rounded-full mix-blend-multiply filter blur-3xl opacity-20 animate-pulse animation-delay-2000"></div>
      </div>

      <div className="container mx-auto px-4 relative z-10">
        {/* Header Section */}
        <div className="text-center mb-12 md:mb-16">
          <div className="inline-flex items-center justify-center w-16 h-16 md:w-20 md:h-20 rounded-full bg-gradient-to-r from-teal-600 to-blue-700 mb-4 md:mb-6 shadow-lg">
            <MdVerified className="w-8 h-8 md:w-10 md:h-10 text-white" />
          </div>
          
          <h2 className="text-2xl md:text-4xl font-bold text-gray-800 mb-4">
            Meet Our <span className="text-transparent bg-clip-text bg-gradient-to-r from-teal-600 to-blue-700">Expert Consultants</span>
          </h2>
          
          <div className="w-24 h-1 bg-gradient-to-r from-teal-600 to-blue-700 mx-auto mb-6 rounded-full"></div>
          
          <p className="text-base md:text-lg text-gray-600 max-w-2xl mx-auto px-4">
            Connect with verified immigration experts who have helped thousands achieve their study abroad dreams
          </p>
          
          {/* Stats */}
          <div className="flex flex-wrap justify-center gap-4 md:gap-8 mt-8">
            {[
              { value: '5000+', label: 'Experts' },
              { value: '4.8★', label: 'Rating' },
              { value: '24h', label: 'Response' },
              { value: '100%', label: 'Success' }
            ].map((stat, index) => (
              <div key={index} className="text-center px-4">
                <div className="text-xl md:text-2xl font-bold text-gray-800">{stat.value}</div>
                <div className="text-xs md:text-sm text-gray-500">{stat.label}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Slider Container */}
        <div className="relative mb-12">
          {/* Swiper Wrapper */}
          <div className="relative">
            <Swiper
              ref={swiperRef}
              modules={[Autoplay, Pagination, Navigation, EffectCreative]}
              spaceBetween={16}
              slidesPerView={1}
              centeredSlides={false}
              breakpoints={{
                640: { 
                  slidesPerView: 1,
                  spaceBetween: 20
                },
                768: { 
                  slidesPerView: 2,
                  spaceBetween: 24
                },
                1024: { 
                  slidesPerView: 3,
                  spaceBetween: 28
                },
                1280: { 
                  slidesPerView: 4,
                  spaceBetween: 32
                }
              }}
              autoplay={{
                delay: 5000,
                disableOnInteraction: false,
                pauseOnMouseEnter: true
              }}
              pagination={{
                clickable: true,
                el: '.custom-pagination',
                bulletClass: 'pagination-bullet',
                bulletActiveClass: 'pagination-bullet-active'
              }}
              navigation={{
                nextEl: '.custom-next',
                prevEl: '.custom-prev',
              }}
              loop={consultantsData.length > 1}
              onSlideChange={handleSlideChange}
              onInit={handleSlideChange}
              className="pb-12"
            >
              {consultantsData.map((consultant, index) => (
                <SwiperSlide key={consultant.id || index}>
                  <div className="h-full">
                    {/* Consultant Card */}
                    <div className="bg-white rounded-xl md:rounded-2xl shadow-lg hover:shadow-2xl transition-all duration-300 h-full flex flex-col border border-gray-200 overflow-hidden group">
                      
                      {/* Badge */}
                      {consultant.badge && (
                        <div className={`absolute top-3 left-3 z-20 px-3 py-1 rounded-full bg-gradient-to-r ${getBadgeColor(consultant.badge)} text-white text-xs font-bold shadow-lg`}>
                          {consultant.badge}
                        </div>
                      )}

                      {/* Image Container */}
                      <div className="relative h-48 md:h-56 overflow-hidden">
                        <Image
                          src={getImageUrl(consultant.profile_picture)}
                          alt={consultant.company_name || 'Consultant'}
                          fill
                          className="object-cover group-hover:scale-105 transition-transform duration-500"
                          sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                          onError={(e) => {
                            e.target.src = '/default-consultant.jpg';
                          }}
                        />
                        
                        {/* Gradient Overlay */}
                        <div className="absolute inset-0 bg-gradient-to-t from-white/50 via-transparent to-transparent"></div>
                        
                        {/* Expertise Score */}
                        <div className="absolute bottom-3 right-3 z-10">
                          <div className="relative w-12 h-12">
                            <svg className="w-full h-full" viewBox="0 0 36 36">
                              <path
                                d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                                fill="none"
                                stroke="#E5E7EB"
                                strokeWidth="2"
                              />
                              <path
                                d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                                fill="none"
                                stroke="#0B6F78"
                                strokeWidth="2"
                                strokeDasharray={`${consultant.expertise_score || 50}, 100`}
                                strokeLinecap="round"
                              />
                            </svg>
                            <div className="absolute inset-0 flex items-center justify-center">
                              <span className={`text-xs font-bold ${getExpertiseColor(consultant.expertise_score || 50)}`}>
                                {(consultant.expertise_score || 50)}%
                              </span>
                            </div>
                          </div>
                        </div>
                      </div>

                      {/* Content Container */}
                      <div className="p-4 md:p-6 flex-1 flex flex-col">
                        
                        {/* Header */}
                        <div className="flex justify-between items-start mb-3">
                          <div className="flex-1">
                            <h3 className="text-lg md:text-xl font-bold text-gray-800 mb-1 line-clamp-1">
                              {consultant.company_name || 'Consultant'}
                            </h3>
                            <p className="text-gray-600 text-sm flex items-center gap-1">
                              <FaBriefcase className="w-3 h-3 flex-shrink-0" />
                              <span className="truncate">{consultant.designation || 'Immigration Consultant'}</span>
                            </p>
                          </div>
                          <div className="flex flex-col items-end ml-2">
                            <div className="flex items-center gap-1">
                              {renderStars(consultant.average_rating || 4.5)}
                              <span className="text-amber-600 text-sm font-bold">
                                {(consultant.average_rating || 4.5).toFixed(1)}
                              </span>
                            </div>
                            <span className="text-gray-500 text-xs">
                              ({consultant.rating_count || 0})
                            </span>
                          </div>
                        </div>

                        {/* Company & Location */}
                        <div className="space-y-2 mb-4">
                          <div className="flex items-center gap-2 text-gray-700 text-sm">
                            <FaBuilding className="w-3 h-3 text-teal-600 flex-shrink-0" />
                            <span className="truncate">{consultant.company_name || 'Consulting Firm'}</span>
                          </div>
                          <div className="flex items-center gap-2 text-gray-700 text-sm">
                            <FaMapMarkerAlt className="w-3 h-3 text-teal-600 flex-shrink-0" />
                            <span className="truncate">
                              {consultant.city ? `${consultant.city}, ${consultant.country}` : consultant.country || 'Location not specified'}
                            </span>
                          </div>
                        </div>

                        {/* Response Time */}
                        <div className="mb-4">
                          <div className="bg-gray-50 rounded-lg p-2 text-center">
                            <div className="text-xs text-gray-500 mb-1">Response Time</div>
                            <div className="text-sm font-semibold text-gray-800">
                              {consultant.response_time_formatted || 'Within 48h'}
                            </div>
                          </div>
                        </div>

                        {/* Specializations */}
                        <div className="mb-4 flex-1">
                          <div className="flex items-center gap-2 text-gray-600 text-sm mb-2">
                            <FaGraduationCap className="w-4 h-4" />
                            <span className="font-medium">Specializations</span>
                          </div>
                          <div className="flex flex-wrap gap-1.5">
                            {(consultant.display_specializations || ['Visa', 'Admission', 'Documentation']).slice(0, 3).map((spec, idx) => (
                              <span 
                                key={idx} 
                                className="px-2.5 py-1 bg-teal-50 text-teal-700 text-xs rounded-lg border border-teal-100"
                              >
                                {spec}
                              </span>
                            ))}
                          </div>
                        </div>

                        {/* Footer */}
                        <div className="pt-4 border-t border-gray-200 mt-auto">
                          <div className="flex items-center justify-between">
                            <div>
                              <div className="text-gray-500 text-xs">Starting from</div>
                              <div className="text-lg font-bold text-gray-800">
                                {consultant.formatted_fee || '$499'}
                              </div>
                            </div>
                            <Link 
                              href={`/consultant/${consultant.seo_slug || '#'}`}
                              className="inline-block"
                            >
                              <button className="px-4 py-2 bg-gradient-to-r from-teal-600 to-blue-700 text-white rounded-lg font-semibold hover:shadow-lg transition-all duration-300 transform hover:scale-105 text-sm md:text-base shadow-md">
                                View Profile
                              </button>
                            </Link>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </SwiperSlide>
              ))}
            </Swiper>

            {/* Navigation Buttons */}
            {consultantsData.length > 0 && (
              <>
                <button
                  onClick={handlePrev}
                  disabled={isBeginning}
                  className={`custom-prev absolute left-0 top-1/2 -translate-y-1/2 -translate-x-4 md:-translate-x-6 z-10 w-10 h-10 md:w-12 md:h-12 rounded-full bg-white shadow-lg flex items-center justify-center border border-gray-200 hover:shadow-xl transition-all duration-300 disabled:opacity-30 disabled:cursor-not-allowed ${
                    isBeginning ? 'opacity-30 cursor-not-allowed' : 'hover:bg-gray-50'
                  }`}
                  aria-label="Previous slide"
                >
                  <MdNavigateBefore className="w-6 h-6 text-gray-700" />
                </button>

                <button
                  onClick={handleNext}
                  disabled={isEnd}
                  className={`custom-next absolute right-0 top-1/2 -translate-y-1/2 translate-x-4 md:translate-x-6 z-10 w-10 h-10 md:w-12 md:h-12 rounded-full bg-white shadow-lg flex items-center justify-center border border-gray-200 hover:shadow-xl transition-all duration-300 disabled:opacity-30 disabled:cursor-not-allowed ${
                    isEnd ? 'opacity-30 cursor-not-allowed' : 'hover:bg-gray-50'
                  }`}
                  aria-label="Next slide"
                >
                  <MdNavigateNext className="w-6 h-6 text-gray-700" />
                </button>
              </>
            )}
          </div>

          {/* Custom Pagination */}
          {consultantsData.length > 0 && (
            <div className="custom-pagination flex justify-center space-x-2 mt-8"></div>
          )}

          {/* No Consultants Message */}
          {consultantsData.length === 0 && (
            <div className="text-center py-12">
              <div className="bg-white rounded-xl p-8 max-w-md mx-auto shadow-lg border border-gray-200">
                <div className="w-16 h-16 rounded-full bg-gradient-to-r from-teal-600 to-blue-700 flex items-center justify-center mx-auto mb-4">
                  <MdVerified className="w-8 h-8 text-white" />
                </div>
                <h3 className="text-xl font-bold text-gray-800 mb-2">No Consultants Available</h3>
                <p className="text-gray-600 mb-6">Our expert consultants will be listed here soon.</p>
                <Link href="/consultant-register">
                  <button className="px-6 py-2 bg-gradient-to-r from-teal-600 to-blue-700 text-white rounded-lg font-semibold hover:shadow-lg transition-all duration-300">
                    Join as Consultant
                  </button>
                </Link>
              </div>
            </div>
          )}
        </div>

        {/* CTA Section */}
        <div className="text-center">
          <div className="bg-gradient-to-r from-teal-50 to-blue-50 rounded-xl md:rounded-2xl p-6 md:p-8 max-w-4xl mx-auto border border-teal-100">
            <div className="flex flex-col md:flex-row items-center justify-between gap-6">
              <div className="text-left">
                <h3 className="text-xl md:text-2xl font-bold text-gray-800 mb-2">
                  Need Personalized Guidance?
                </h3>
                <p className="text-gray-600">
                  Connect with the perfect consultant for your study abroad journey
                </p>
              </div>
              <div className="flex flex-col sm:flex-row gap-3 md:gap-4">
                <Link href="/consultant">
                  <button className="px-6 py-3 bg-gradient-to-r from-teal-600 to-blue-700 text-white font-semibold rounded-lg hover:shadow-lg transition-all duration-300 shadow-md flex items-center justify-center gap-2 min-w-[200px]">
                    <FaUsers className="w-5 h-5" />
                    Browse All Consultants
                  </button>
                </Link>
                <Link href="/free-consultation">
                  <button className="px-6 py-3 bg-white border-2 border-teal-600 text-teal-600 font-semibold rounded-lg hover:bg-teal-600 hover:text-white transition-all duration-300 flex items-center justify-center gap-2 min-w-[200px]">
                    <FaPhone className="w-5 h-5" />
                    Free Consultation
                  </button>
                </Link>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Global Styles */}
      <style jsx global>{`
        @keyframes float {
          0%, 100% { transform: translateY(0); }
          50% { transform: translateY(-10px); }
        }
        
        @keyframes pulse {
          0%, 100% { opacity: 0.1; }
          50% { opacity: 0.2; }
        }
        
        .animate-pulse {
          animation: pulse 4s ease-in-out infinite;
        }
        
        .animation-delay-2000 {
          animation-delay: 2s;
        }
        
        /* Swiper Pagination */
        .pagination-bullet {
          width: 8px;
          height: 8px;
          background: #D1D5DB;
          border-radius: 50%;
          margin: 0 4px;
          cursor: pointer;
          transition: all 0.3s ease;
          opacity: 1;
        }
        
        .pagination-bullet-active {
          width: 24px;
          background: linear-gradient(135deg, #0B6F78, #0a306b);
          border-radius: 12px;
        }
        
        /* Hide default navigation */
        .swiper-button-next,
        .swiper-button-prev {
          display: none !important;
        }
        
        /* Line clamp utility */
        .line-clamp-1 {
          overflow: hidden;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 1;
        }
        
        .line-clamp-2 {
          overflow: hidden;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
        }
        
        /* Mobile optimizations */
        @media (max-width: 640px) {
          .swiper {
            padding: 0 16px !important;
            margin: 0 -16px !important;
          }
          
          .swiper-slide {
            padding: 0 4px !important;
          }
        }
        
        /* Tablet optimizations */
        @media (max-width: 768px) {
          .custom-prev,
          .custom-next {
            display: none !important;
          }
        }
        
        /* Card hover effects */
        .group:hover .group-hover\\:scale-105 {
          transform: scale(1.05);
        }
        
        /* Smooth transitions */
        * {
          transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
        }
      `}</style>
    </section>
  );
};

export default FeaturedConsultants;