'use client';

import { useState, useEffect, useRef } from 'react';
import { AboutTestimonialsSectionProps, AboutTestimonial } from '@/lib/page-builder/types';
import { Star, Quote, ChevronLeft, ChevronRight, TrendingUp, Users, Award } from 'lucide-react';

export default function AboutTestimonialsSection({
  title = "What Our Clients Say",
  highlightedText = "Clients Say",
  description = "Don't just take our word for it. See what our clients have to say about their experience.",
  badgeText = "Client Success Stories",
  showBadge = true,
  testimonials = [],
  layout = 'grid',
  columns = 3,
  autoRotate = true,
  autoRotateInterval = 5000,
  showSEOStats = true,
  showStars = true,
  showQuotes = true,
  showProgressBar = true,
  seoImprovementTitle = "SEO Transformation",
  seoImprovementLabel = "Overall SEO Improvement",
  seoImprovementPercentage = 85,
  seoStats = {
    trafficIncrease: '+240%',
    keywordsIncrease: '+275%',
    authorityIncrease: '+122%'
  },
  className = "",
  id
}: AboutTestimonialsSectionProps) {
  
  const [currentSlide, setCurrentSlide] = useState(0);
  const [isAnimating, setIsAnimating] = useState(false);
  const progressIntervalRef = useRef<NodeJS.Timeout | null>(null);

  // Helper function to render stars
  const renderStars = (rating: number) => {
    return (
      <div className="flex gap-0.5">
        {[...Array(5)].map((_, i) => (
          <Star
            key={i}
            className={`w-4 h-4 ${i < rating ? 'fill-[#FFB800] text-[#FFB800]' : 'text-gray-300'}`}
          />
        ))}
      </div>
    );
  };

  // Get grid class for layout
  const getGridClass = () => {
    if (layout === 'carousel') return 'flex overflow-hidden';
    
    switch (columns) {
      case 2:
        return "grid md:grid-cols-2 gap-6 lg:gap-8";
      case 3:
        return "grid md:grid-cols-2 lg:grid-cols-3 gap-6 lg:gap-8";
      case 4:
        return "grid md:grid-cols-2 lg:grid-cols-4 gap-6 lg:gap-8";
      default:
        return "grid md:grid-cols-2 lg:grid-cols-3 gap-6 lg:gap-8";
    }
  };

  // Render title with gradient
  const renderTitle = () => {
    if (!highlightedText || !title.includes(highlightedText)) {
      return <h2 className="text-3xl md:text-4xl lg:text-5xl font-bold text-[#1A1F36] mb-4">{title}</h2>;
    }

    const parts = title.split(highlightedText);
    return (
      <h2 className="text-3xl md:text-4xl lg:text-5xl font-bold text-[#1A1F36] mb-4">
        {parts[0]}
        <span className="text-gradient">{highlightedText}</span>
        {parts[1]}
      </h2>
    );
  };

  // Carousel navigation
  const nextSlide = () => {
    if (isAnimating) return;
    setIsAnimating(true);
    setCurrentSlide((prev) => (prev + 1) % testimonials.length);
    setTimeout(() => setIsAnimating(false), 500);
    resetProgress();
  };

  const prevSlide = () => {
    if (isAnimating) return;
    setIsAnimating(true);
    setCurrentSlide((prev) => (prev - 1 + testimonials.length) % testimonials.length);
    setTimeout(() => setIsAnimating(false), 500);
    resetProgress();
  };

  const goToSlide = (index: number) => {
    if (isAnimating || index === currentSlide) return;
    setIsAnimating(true);
    setCurrentSlide(index);
    setTimeout(() => setIsAnimating(false), 500);
    resetProgress();
  };

  const resetProgress = () => {
    if (progressIntervalRef.current) {
      clearInterval(progressIntervalRef.current);
    }
    if (autoRotate && testimonials.length > 0) {
      startProgressBar();
    }
  };

  const startProgressBar = () => {
    const interval = 50;
    const steps = autoRotateInterval / interval;
    let currentStep = 0;
    
    progressIntervalRef.current = setInterval(() => {
      currentStep++;
      // setProgress((currentStep / steps) * 100);
      if (currentStep >= steps) {
        nextSlide();
      }
    }, interval);
  };

  // Auto rotate effect
  useEffect(() => {
    if (autoRotate && testimonials.length > 0 && layout === 'carousel') {
      startProgressBar();
      return () => {
        if (progressIntervalRef.current) {
          clearInterval(progressIntervalRef.current);
        }
      };
    }
  }, [autoRotate, testimonials.length, currentSlide, layout]);

  // Default testimonials if none provided
  const displayTestimonials = testimonials.length > 0 ? testimonials : [
    {
      id: '1',
      name: 'Sarah Johnson',
      company: 'TechStart Inc.',
      role: 'Marketing Director',
      image: '',
      content: 'The guest posting service exceeded our expectations. Our organic traffic increased by 150% in just 3 months!',
      rating: 5,
      before: { traffic: '10k', keywords: '150', authority: '25' },
      after: { traffic: '25k', keywords: '560', authority: '55' }
    },
    {
      id: '2',
      name: 'Michael Chen',
      company: 'EcomGrowth',
      role: 'SEO Manager',
      image: '',
      content: 'Professional team, quality websites, and real results. Highly recommended for anyone serious about SEO.',
      rating: 5,
      before: { traffic: '5k', keywords: '80', authority: '18' },
      after: { traffic: '15k', keywords: '300', authority: '42' }
    },
    {
      id: '3',
      name: 'Emily Rodriguez',
      company: 'DigitalEdge',
      role: 'Founder',
      image: '',
      content: 'Best investment we made for our online presence. The ROI has been incredible and the support team is amazing.',
      rating: 5,
      before: { traffic: '8k', keywords: '120', authority: '22' },
      after: { traffic: '22k', keywords: '450', authority: '58' }
    }
  ];

  // Single testimonial card component
  const TestimonialCard = ({ testimonial, index }: { testimonial: AboutTestimonial; index: number }) => {
    const isHighlight = testimonial.rating === 5;
    
    return (
      <div
        className={`
          group rounded-2xl p-6 transition-all duration-300
          ${layout === 'carousel' ? 'w-full shrink-0' : ''}
          ${isHighlight && layout !== 'carousel'
            ? 'bg-linear-to-br from-[#0066FF]/5 to-[#00D4FF]/5 border border-blue-100 shadow-md hover:shadow-xl' 
            : 'bg-white border border-gray-100 shadow-sm hover:shadow-lg'
          }
          hover:-translate-y-1
        `}
        style={{
          animation: layout !== 'carousel' ? `fadeInUp 0.5s ease-out ${index * 0.1}s forwards` : 'none',
          opacity: layout !== 'carousel' ? 0 : 1,
          transform: layout !== 'carousel' ? 'translateY(20px)' : 'none'
        }}
      >
        {/* Quote Icon */}
        {showQuotes && (
          <div className="mb-4">
            <Quote className="w-8 h-8 text-[#0066FF]/20 fill-[#0066FF]/10" />
          </div>
        )}

        {/* Content */}
        <p className="text-[#475569] leading-relaxed mb-6">
          {testimonial.content}
        </p>

        {/* Stars */}
        {showStars && (
          <div className="mb-4">
            {renderStars(testimonial.rating)}
          </div>
        )}

        {/* Client Info */}
        <div className="flex items-center gap-3">
          
        <div className="w-12 h-12 rounded-full bg-linear-to-br from-[#0066FF] to-[#00D4FF] flex items-center justify-center text-white font-bold text-lg">
            {testimonial.name.charAt(0)}
        </div>
          <div>
            <h4 className="font-semibold text-[#1A1F36]">{testimonial.name}</h4>
            <p className="text-sm text-[#475569]">
              {testimonial.role} {testimonial.company && `@ ${testimonial.company}`}
            </p>
          </div>
        </div>
      </div>
    );
  };

  return (
    <section 
      id={id || "testimonials"} 
      className={`py-16 md:py-20 px-4 bg-linear-to-b from-white to-[#F8FAFF] ${className}`}
    >
      <div className="max-w-7xl mx-auto">
        {/* Section Header */}
        <div className="text-center mb-12 md:mb-16">
          {showBadge && badgeText && (
            <span className="inline-block px-4 py-1.5 bg-linear-to-r from-blue-50 to-orange-50 rounded-full text-sm font-medium text-[#0066FF] mb-4">
              {badgeText}
            </span>
          )}
          
          {renderTitle()}
          
          {description && (
            <p className="text-lg text-[#475569] max-w-2xl mx-auto">
              {description}
            </p>
          )}
        </div>

        {/* SEO Stats Bar (Optional) */}
        {showSEOStats && (
          <div className="mb-12 bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <div className="text-center">
                <div className="flex items-center justify-center gap-2 text-[#0066FF] mb-2">
                  <TrendingUp className="w-5 h-5" />
                  <span className="text-sm font-medium">Traffic Increase</span>
                </div>
                <div className="text-4xl font-bold text-[#1A1F36]">{seoStats?.trafficIncrease || '+240%'}</div>
                <p className="text-sm text-[#475569] mt-1">Average organic growth</p>
              </div>
              <div className="text-center">
                <div className="flex items-center justify-center gap-2 text-[#0066FF] mb-2">
                  <Users className="w-5 h-5" />
                  <span className="text-sm font-medium">Keywords Ranking</span>
                </div>
                <div className="text-4xl font-bold text-[#1A1F36]">{seoStats?.keywordsIncrease || '+275%'}</div>
                <p className="text-sm text-[#475569] mt-1">Top 10 positions</p>
              </div>
              <div className="text-center">
                <div className="flex items-center justify-center gap-2 text-[#0066FF] mb-2">
                  <Award className="w-5 h-5" />
                  <span className="text-sm font-medium">Domain Authority</span>
                </div>
                <div className="text-4xl font-bold text-[#1A1F36]">{seoStats?.authorityIncrease || '+122%'}</div>
                <p className="text-sm text-[#475569] mt-1">Average increase</p>
              </div>
            </div>

            {/* Progress Bar */}
            {showProgressBar && (
              <div className="mt-6 pt-4 border-t border-gray-100">
                <div className="flex justify-between text-sm mb-2">
                  <span className="text-[#475569]">{seoImprovementTitle}</span>
                  <span className="font-semibold text-[#0066FF]">{seoImprovementPercentage}%</span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div
                    className="bg-linear-to-r from-[#0066FF] to-[#00D4FF] h-2 rounded-full transition-all duration-500"
                    style={{ width: `${seoImprovementPercentage}%` }}
                  />
                </div>
                <p className="text-xs text-[#475569] mt-2">{seoImprovementLabel}</p>
              </div>
            )}
          </div>
        )}

        {/* Testimonials Display */}
        {layout === 'carousel' && testimonials.length > 0 ? (
          // Carousel Layout
          <div className="relative">
            <div className="overflow-hidden">
              <div
                className="flex transition-transform duration-500 ease-out"
                style={{ transform: `translateX(-${currentSlide * 100}%)` }}
              >
                {displayTestimonials.map((testimonial, idx) => (
                  <div key={testimonial.id} className="w-full shrink-0 px-4">
                    <TestimonialCard testimonial={testimonial} index={idx} />
                  </div>
                ))}
              </div>
            </div>

            {/* Carousel Navigation */}
            {displayTestimonials.length > 1 && (
              <>
                <button
                  onClick={prevSlide}
                  className="absolute left-0 top-1/2 -translate-y-1/2 -translate-x-4 lg:-translate-x-6 bg-white rounded-full p-2 shadow-lg hover:shadow-xl transition-all"
                >
                  <ChevronLeft className="w-5 h-5 text-[#1A1F36]" />
                </button>
                <button
                  onClick={nextSlide}
                  className="absolute right-0 top-1/2 -translate-y-1/2 translate-x-4 lg:translate-x-6 bg-white rounded-full p-2 shadow-lg hover:shadow-xl transition-all"
                >
                  <ChevronRight className="w-5 h-5 text-[#1A1F36]" />
                </button>
              </>
            )}

            {/* Dots */}
            {displayTestimonials.length > 1 && (
              <div className="flex justify-center gap-2 mt-8">
                {displayTestimonials.map((_, idx) => (
                  <button
                    key={idx}
                    onClick={() => goToSlide(idx)}
                    className={`
                      h-2 rounded-full transition-all duration-300
                      ${currentSlide === idx ? 'w-8 bg-[#0066FF]' : 'w-2 bg-gray-300 hover:bg-gray-400'}
                    `}
                  />
                ))}
              </div>
            )}
          </div>
        ) : (
          // Grid Layout
          <div className={getGridClass()}>
            {displayTestimonials.map((testimonial, index) => (
              <TestimonialCard key={testimonial.id} testimonial={testimonial} index={index} />
            ))}
          </div>
        )}
      </div>

      {/* Global Styles */}
      <style>
        {`
          @keyframes fadeInUp {
            from {
              opacity: 0;
              transform: translateY(20px);
            }
            to {
              opacity: 1;
              transform: translateY(0);
            }
          }
          
          .text-gradient {
            background: linear-gradient(135deg, #0066FF 0%, #00D4FF 100%);
            background-clip: text;
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            display: inline-block;
          }
        `}
      </style>
    </section>
  );
}