// components/organisms/StudentReviews.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";

// Define the review type
interface Review {
  id: number;
  review_name: string;
  profile_pic: string;
  review: string;
  rating?: number;
  created_at?: string;
  updated_at?: string;
}

interface StudentReviewsProps {
  reviewsData: Review[]; // Data passed from server component
}

const StarRating = () => {
  return (
    <div className="flex items-center justify-center space-x-1 mb-4">
      {[1, 2, 3, 4, 5].map((star) => (
        <svg
          key={star}
          className="w-5 h-5 text-yellow-400"
          fill="currentColor"
          viewBox="0 0 20 20"
        >
          <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
        </svg>
      ))}
    </div>
  );
};

const StudentReviews = ({ reviewsData }: StudentReviewsProps) => {
  const [activeReview, setActiveReview] = useState(0);
  const [displayReviews, setDisplayReviews] = useState<Review[]>([]);
  const swiperRef = useRef<any>(null);

  // Fallback data in case API fails or returns no data
  const fallbackReviews: Review[] = [
    {
      id: 1,
      review_name: 'Sarah Chen',
      profile_pic: 'https://images.unsplash.com/photo-1494790108755-2616b612b786?ixlib=rb-4.0.3&w=150',
      review: 'The guidance I received was exceptional. From visa processing to accommodation, every step was seamlessly handled.',
    },
    {
      id: 2,
      review_name: 'Ahmed Hassan',
      profile_pic: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-4.0.3&w=150',
      review: 'Outstanding service! The team helped me secure a scholarship I never thought possible.',
    },
    {
      id: 3,
      review_name: 'Maria Rodriguez',
      profile_pic: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?ixlib=rb-4.0.3&w=150',
      review: 'Professional and reliable. They matched me with the perfect program and provided excellent support.',
    },
  ];

  // Set display reviews when component mounts or reviewsData changes
  useEffect(() => {
    // Use API data or fallback data
    setDisplayReviews(reviewsData && reviewsData.length > 0 ? reviewsData : fallbackReviews);
  }, [reviewsData]);

  // 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="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" />
            </svg>
          </div>
          <h2 className="text-3xl md:text-4xl font-bold text-gray-900 mb-4">
            What Our Students <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">Say</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">
            Hear directly from our successful students about the Universities Page study abroad consultants about their experiences with our international education services. Learn how our guidance helped them choose the right programs, explore Higher Education Abroad, and achieve their study abroad dreams.
          </p>
        </div>

        {/* Reviews Swiper */}
        <div className="max-w-6xl 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: 5000,
              disableOnInteraction: false,
              pauseOnMouseEnter: true
            }}
            pagination={{
              clickable: true,
              el: '.reviews-pagination',
            }}
            navigation={{
              nextEl: '.reviews-button-next',
              prevEl: '.reviews-button-prev',
            }}
            loop={displayReviews.length > 1}
            grabCursor={true}
            speed={800}
            onSlideChange={(swiper) => setActiveReview(swiper.realIndex)}
            className="pb-16"
          >
            {displayReviews.map((review) => (
              <SwiperSlide key={review.id}>
                <div className="bg-white rounded-2xl shadow-lg hover:shadow-xl transition-all duration-500 p-8 h-full border border-gray-100 group hover:border-teal-600/20 flex flex-col">
                  {/* Star Rating - Always 5 stars */}
                  <StarRating />
                  
                  {/* Review Content */}
                  <blockquote className="text-gray-700 leading-relaxed mb-6 text-center grow">
                    &quot;{review.review}&quot;
                  </blockquote>

                  {/* Reviewer Info */}
                  <div className="flex flex-col items-center mt-auto">
                    <div className="relative">
                      <Image
                        src={review.profile_pic || '/default-avatar.png'}
                        alt={review.review_name}
                        width={80}
                        height={80}
                        className="w-20 h-20 rounded-full object-cover border-4 border-white shadow-lg mb-4"
                        onError={(e) => {
                          // Fallback for broken images
                          e.currentTarget.src = 'https://images.unsplash.com/photo-1494790108755-2616b612b786?ixlib=rb-4.0.3&w=150';
                        }}
                      />
                    </div>
                    <h4 className="font-semibold text-gray-900 text-lg">{review.review_name}</h4>
                  </div>

                  {/* Hover Effect */}
                  <div className="absolute inset-0 rounded-2xl bg-linear-to-br from-teal-600/5 to-blue-500/5 opacity-0 group-hover:opacity-100 transition-opacity duration-500 pointer-events-none"></div>
                </div>
              </SwiperSlide>
            ))}
          </Swiper>

          {/* Show navigation only if there are reviews */}
          {displayReviews.length > 0 && (
            <>
              {/* Custom Pagination */}
              <div className="reviews-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="reviews-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 review"
                >
                  <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">
                  {activeReview + 1} / {displayReviews.length}
                </div>
                
                <button 
                  className="reviews-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 review"
                >
                  <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 Reviews Message */}
          {displayReviews.length === 0 && (
            <div className="text-center py-12">
              <div className="bg-gray-50 rounded-lg p-8 max-w-md mx-auto">
                <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="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                </svg>
                <h3 className="text-lg font-semibold text-gray-900 mb-2">No Reviews Yet</h3>
                <p className="text-gray-600">Be the first to share your experience!</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">Join Our Universities Page - Study Abroad Consultants</h3>
            <p className="text-white/90 mb-6 max-w-4xl mx-auto">
              Be the next success story on Universities Page! Join our growing community of international students who have achieved their academic and career goals with the support of our international education services. Explore new opportunities, pursue Higher Education Abroad, and turn your study abroad dreams into reality.
            </p>
            <div className="flex flex-col sm:flex-row gap-4 justify-center">
              <a
                href="https://www.google.com/search?q=universitiespage&rlz=1C1ONGR_en-GBPK1174PK1174&oq=universitiespage+&gs_lcrp=EgZjaHJvbWUyBggAEEUYOTIGCAEQRRg8MgYIAhBFGD8yBggDEEUYPDIGCAQQRRg8MgYIBRBFGD8yBggGEEUYQdIBBzgxNWowajSoAgCwAgE&sourceid=chrome&ie=UTF-8#lrd=0x391903a687766e03:0xb3d2577d5a2fe6ce,1,,,,"
                target="_blank"
                rel="noopener noreferrer"
              >
                <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">
                  Share Your Experience
                </button>
              </a>

              <a
                href="https://www.google.com/search?q=universitiespage&rlz=1C1ONGR_en-GBPK1174PK1174&oq=universitiespage+&gs_lcrp=EgZjaHJvbWUyBggAEEUYOTIGCAEQRRg8MgYIAhBFGD8yBggDEEUYPDIGCAQQRRg8MgYIBRBFGD8yBggGEEUYQdIBBzgxNWowajSoAgCwAgE&sourceid=chrome&ie=UTF-8#lrd=0x391903a687766e03:0xb3d2577d5a2fe6ce,1,,,,"
                target="_blank"
                rel="noopener noreferrer"
              >
                <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">
                  Read More Reviews
                </button>
              </a>
            </div>
          </div>
        </div>
      </div>

      {/* Add custom CSS for Swiper pagination */}
      <style jsx global>{`
        .reviews-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;
        }
        
        .reviews-pagination .swiper-pagination-bullet-active {
          background: linear-linear(135deg, #0d9488, #3b82f6);
          transform: scale(1.2);
        }
        
        .reviews-pagination {
          position: relative;
          margin-top: 2rem;
        }

        /* Swiper navigation button states */
        .reviews-button-next.swiper-button-disabled,
        .reviews-button-prev.swiper-button-disabled {
          opacity: 0.5;
          cursor: not-allowed;
          transform: none;
        }

        .reviews-button-next.swiper-button-disabled:hover,
        .reviews-button-prev.swiper-button-disabled:hover {
          background: white;
          color: #0d9488;
          transform: none;
        }
      `}</style>
    </section>
  );
};

export default StudentReviews;