"use client";

import { useState, useEffect } from "react";
import { Star, Quote, ChevronLeft, ChevronRight } from "lucide-react";
import { Button } from "@/components/ui/button";

export interface TestimonialItem {
  name: string;
  title?: string;
  company?: string;
  content: string;
  rating?: number;
}

const fallbackTestimonials: TestimonialItem[] = [
  {
    name: "Client",
    content: "Excellent customer service—always responsive and professional.",
    rating: 5
  },
  {
    name: "Client",
    content: "Our business has improved significantly, and we feel more confident about the future.",
    rating: 5
  },
  {
    name: "Client",
    content: "They manage our business portfolio with great care and efficiency.",
    rating: 5
  },
  {
    name: "Client",
    content: "Deals with vendors are handled smoothly, saving us time and stress.",
    rating: 5
  },
  {
    name: "Client",
    content: "TRA matters were resolved professionally while protecting our interests.",
    rating: 5
  },
  {
    name: "Client",
    content: "Their guidance on banking and financial decisions has been very valuable.",
    rating: 5
  },
  {
    name: "Client",
    content: "We appreciate the support in finding reliable markets and quality products at good prices.",
    rating: 5
  },
  {
    name: "Client",
    content: "The consultants provide practical, professional advice that helps our daily operations.",
    rating: 5
  },
  {
    name: "Client",
    content: "Business issues are solved quickly, and feedback is always timely.",
    rating: 5
  },
  {
    name: "Client",
    content: "Their guidance on business operations and management has helped us maintain stability and grow.",
    rating: 5
  },
  {
    name: "Client",
    content: "The procedures and guidelines provided for TRA compliance made everything easier.",
    rating: 5
  },
  {
    name: "Client",
    content: "They helped us recruit qualified staff who perfectly matched our needs.",
    rating: 5
  }
];

interface TestimonialsProps {
  testimonials?: TestimonialItem[];
}

export function Testimonials({ testimonials: propTestimonials }: TestimonialsProps) {
  const [fetchedTestimonials, setFetchedTestimonials] = useState<TestimonialItem[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchTestimonials() {
      try {
        const res = await fetch('/api/testimonials');
        if (res.ok) {
          const data = await res.json();
          if (Array.isArray(data) && data.length > 0) {
            const formatted = data.map((t: any) => ({
              name: t.client_name,
              title: t.client_title,
              company: t.client_company,
              content: t.testimonial_text,
              rating: t.rating || 5
            }));
            setFetchedTestimonials(formatted);
          }
        }
      } catch (error) {
        console.error('Failed to fetch testimonials:', error);
      } finally {
        setLoading(false);
      }
    }
    // Only fetch if no props provided
    if (!propTestimonials) {
      fetchTestimonials();
    } else {
      setLoading(false);
    }
  }, [propTestimonials]);

  const activeTestimonials = propTestimonials || (fetchedTestimonials.length > 0 ? fetchedTestimonials : fallbackTestimonials);

  const items = activeTestimonials.map(t => ({
    ...t,
    rating: typeof t.rating === 'number' ? t.rating : 5,
  }));

  const [currentIndex, setCurrentIndex] = useState(0);
  const [isAutoPlay, setIsAutoPlay] = useState(true);

  // Auto-play testimonials every 3 seconds
  useEffect(() => {
    if (!isAutoPlay) return;

    const interval = setInterval(() => {
      setCurrentIndex((prev) => (prev + 1) % items.length);
    }, 3000);

    return () => clearInterval(interval);
  }, [isAutoPlay, items.length]);

  const nextTestimonial = () => {
    setCurrentIndex((prev) => (prev + 1) % items.length);
    setIsAutoPlay(false); // Pause auto-play when user navigates
  };

  const prevTestimonial = () => {
    setCurrentIndex((prev) => (prev - 1 + items.length) % items.length);
    setIsAutoPlay(false); // Pause auto-play when user navigates
  };

  return (
    <section className="py-20 bg-gradient-to-br from-white via-blue-50 to-slate-50 relative overflow-hidden">
      {/* Background Pattern */}
      <div className="absolute inset-0 opacity-5">
        <div className="absolute -top-40 -left-40 w-96 h-96 bg-na-blue rounded-full blur-3xl"></div>
        <div className="absolute -bottom-40 -right-40 w-96 h-96 bg-na-orange rounded-full blur-3xl"></div>
      </div>

      <div className="container-professional relative z-10">
        <div className="text-center mb-16 max-w-content mx-auto">
          <h2 className="font-heading text-responsive-3xl font-bold text-na-blue mb-4">
            What Our <span className="text-na-orange decoration-4 underline-offset-8">Clients Say</span>
          </h2>
          <p className="text-responsive-lg text-gray-600 max-w-prose mx-auto">
            Discover why businesses across Tanzania trust Numbers Associates with their financial success.
          </p>
        </div>

        <div className="max-w-4xl mx-auto">
          {/* Testimonials Carousel with Slide Animation */}
          <div 
            className="relative h-80 px-4"
            onMouseEnter={() => setIsAutoPlay(false)}
            onMouseLeave={() => setIsAutoPlay(true)}
          >
            {/* Sliding Cards */}
            <div className="relative w-full h-full">
              {items.map((testimonial, index) => {
                const position = (index - currentIndex + items.length) % items.length;
                const isActive = position === 0;
                const isNext = position === 1;
                const isPrev = position === items.length - 1;

                return (
                  <div
                    key={index}
                    className={`absolute inset-0 transition-all duration-500 ease-out transform ${
                      isActive 
                        ? 'opacity-100 translate-x-0 z-20' 
                        : isNext 
                        ? 'opacity-0 translate-x-full z-10' 
                        : isPrev 
                        ? 'opacity-0 -translate-x-full z-10' 
                        : 'opacity-0 translate-x-full z-0'
                    }`}
                  >
                    <div className="bg-white/80 backdrop-blur-lg rounded-2xl shadow-2xl p-8 md:p-12 border border-white/20 relative h-full flex flex-col justify-center hover:ring-1 hover:ring-orange-300/50 transition-all [box-shadow:0_20px_40px_-10px_rgba(0,0,0,0.2),0_0_1px_rgba(0,0,0,0.05)]">
                      <Quote className="absolute top-8 left-8 text-na-orange/30" size={48} />
                      
                      {/* Rating Stars */}
                      <div className="flex justify-center mb-6">
                        {Array.from({ length: testimonial.rating ?? 0 }).map((_, i) => (
                          <Star key={i} className="text-yellow-400 fill-current" size={20} />
                        ))}
                      </div>

                      {/* Testimonial Content */}
                      <blockquote className="text-center mb-8 flex-grow flex items-center justify-center">
                        <p className="text-gray-700 text-lg md:text-xl leading-relaxed italic font-medium">
                          "{testimonial.content}"
                        </p>
                      </blockquote>

                      {/* Author Info */}
                      <div className="text-center">
                        <h4 className="font-semibold text-na-blue text-lg mb-1">{testimonial.name}</h4>
                        {(testimonial.title || testimonial.company) && (
                          <p className="text-gray-600 text-sm">
                            {testimonial.title ? `${testimonial.title}, ` : ''}{testimonial.company}
                          </p>
                        )}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Navigation */}
          <div className="flex justify-center items-center mt-8 space-x-4">
            <Button
              variant="outline"
              size="sm"
              onClick={prevTestimonial}
              className="border-na-blue text-na-blue hover:bg-na-blue hover:text-white rounded-full w-10 h-10 p-0"
            >
              <ChevronLeft size={18} />
            </Button>
            
            {/* Dots Indicator */}
            <div className="flex space-x-2">
              {items.map((_, index) => (
                <button
                  key={index}
                  onClick={() => setCurrentIndex(index)}
                  className={`w-3 h-3 rounded-full transition-all ${
                    index === currentIndex 
                      ? 'bg-na-orange scale-110' 
                      : 'bg-gray-300 hover:bg-gray-400'
                  }`}
                  aria-label={`Go to testimonial ${index + 1}`}
                />
              ))}
            </div>
            
            <Button
              variant="outline"
              size="sm"
              onClick={nextTestimonial}
              className="border-na-blue text-na-blue hover:bg-na-blue hover:text-white rounded-full w-10 h-10 p-0"
            >
              <ChevronRight size={18} />
            </Button>
          </div>

          {/* Stats Section */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-8 mt-16 text-center">
            <div className="bg-white/60 backdrop-blur-sm rounded-xl p-6 border border-white/30">
              <div className="text-2xl md:text-3xl font-bold text-na-blue mb-2">500+</div>
              <div className="text-gray-600 text-sm">Satisfied Clients</div>
            </div>
            <div className="bg-white/60 backdrop-blur-sm rounded-xl p-6 border border-white/30">
              <div className="text-2xl md:text-3xl font-bold text-na-blue mb-2">15+</div>
              <div className="text-gray-600 text-sm">Years Experience</div>
            </div>
            <div className="bg-white/60 backdrop-blur-sm rounded-xl p-6 border border-white/30">
              <div className="text-2xl md:text-3xl font-bold text-na-blue mb-2">98%</div>
              <div className="text-gray-600 text-sm">Client Retention</div>
            </div>
            <div className="bg-white/60 backdrop-blur-sm rounded-xl p-6 border border-white/30">
              <div className="text-2xl md:text-3xl font-bold text-na-blue mb-2">24/7</div>
              <div className="text-gray-600 text-sm">Support Available</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
