import React, { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { Card, CardContent } from "./ui/card";
import { Button } from "./ui/button";
import { Star } from "lucide-react";
import { ImageWithFallback } from "./figma/ImageWithFallback";

// High-quality Clutch logo placeholder
const clutchLogo = "https://images.unsplash.com/photo-1560472354-b33ff0c44a43?w=120&h=60&fit=crop&auto=format";


const testimonials = [
  {
    id: 1,
    name: "Sarah Chen",
    position: "CTO",
    company: "FinTech Innovations",
    image: "https://images.unsplash.com/photo-1494790108755-2616b332c5cd?w=150&h=150&fit=crop&auto=format",
    rating: 5,
    text: "WDI transformed our legacy banking system into a modern, scalable platform. Their expertise in financial technology is unmatched.",
    projectType: "Banking Platform Modernization"
  },
  {
    id: 2,
    name: "Michael Rodriguez",
    position: "Founder & CEO",
    company: "HealthTech Solutions",
    image: "https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=150&h=150&fit=crop&auto=format",
    rating: 5,
    text: "The mobile health app WDI developed has revolutionized patient care delivery. Exceptional attention to healthcare compliance and user experience.",
    projectType: "Healthcare Mobile App"
  },
  {
    id: 3,
    name: "Emily Watson",
    position: "VP of Digital Strategy",
    company: "RetailMax Corp",
    image: "https://images.unsplash.com/photo-1580489944761-15a19d654956?w=150&h=150&fit=crop&auto=format",
    rating: 5,
    text: "Our e-commerce platform's performance improved by 300% after WDI's optimization. Their technical expertise is outstanding.",
    projectType: "E-commerce Platform Enhancement"
  },
  {
    id: 4,
    name: "James Thompson",
    position: "Chief Innovation Officer",
    company: "EduTech Pioneers",
    image: "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150&h=150&fit=crop&auto=format",
    rating: 5,
    text: "WDI's AI-powered learning platform has transformed how our students engage with content. Incredible innovation and execution.",
    projectType: "AI-Powered EdTech Platform"
  },
  {
    id: 5,
    name: "Lisa Park",
    position: "Operations Director",
    company: "LogiFlow Systems",
    image: "https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=150&h=150&fit=crop&auto=format",
    rating: 5,
    text: "The supply chain management system WDI built has streamlined our operations and reduced costs by 40%. Highly recommended.",
    projectType: "Supply Chain Management System"
  }
];

export const CarouselTestimonials = () => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isAutoPlaying, setIsAutoPlaying] = useState(true);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  // Auto-play functionality
  useEffect(() => {
    if (isAutoPlaying) {
      intervalRef.current = setInterval(() => {
        setCurrentIndex((prevIndex) => 
          prevIndex === testimonials.length - 1 ? 0 : prevIndex + 1
        );
      }, 5000);
    }

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, [isAutoPlaying]);

  const goToPrevious = () => {
    setIsAutoPlaying(false);
    setCurrentIndex(currentIndex === 0 ? testimonials.length - 1 : currentIndex - 1);
  };

  const goToNext = () => {
    setIsAutoPlaying(false);
    setCurrentIndex(currentIndex === testimonials.length - 1 ? 0 : currentIndex + 1);
  };

  const goToSlide = (index: number) => {
    setIsAutoPlaying(false);
    setCurrentIndex(index);
  };

  // Resume auto-play after user interaction
  useEffect(() => {
    if (!isAutoPlaying) {
      const resumeTimer = setTimeout(() => {
        setIsAutoPlaying(true);
      }, 10000); // Resume after 10 seconds

      return () => clearTimeout(resumeTimer);
    }
  }, [isAutoPlaying]);

  return (
    <section className="py-32 bg-background">
      <div className="container mx-auto px-6 lg:px-8">
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          whileInView={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8 }}
          viewport={{ once: true }}
          className="text-center mb-20"
        >
          <h2 className="text-4xl lg:text-5xl font-semibold text-foreground mb-6">
            What Our <span className="text-accent">Clients Say</span>
          </h2>
          <p className="text-xl text-muted-foreground max-w-3xl mx-auto leading-relaxed">
            Hear from industry leaders who have transformed their businesses with our innovative solutions.
          </p>
        </motion.div>

        <div className="relative max-w-6xl mx-auto">
          {/* Main Testimonial Display */}
          <div className="relative overflow-hidden rounded-3xl">
            <AnimatePresence mode="wait">
              <motion.div
                key={currentIndex}
                initial={{ opacity: 0, x: 100 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -100 }}
                transition={{ duration: 0.5, ease: "easeInOut" }}
              >
                <Card className="bg-card/50 backdrop-blur-md border-white/10 shadow-2xl">
                  <CardContent className="p-12">
                    <div className="grid lg:grid-cols-3 gap-12 items-center">
                      {/* Client Photo and Info */}
                      <div className="lg:col-span-1 text-center lg:text-left">
                        <div className="relative mb-8">
                          <div className="w-32 h-32 mx-auto lg:mx-0 rounded-full overflow-hidden border-4 border-accent/20">
                            <ImageWithFallback
                              src={testimonials[currentIndex].image}
                              alt={testimonials[currentIndex].name}
                              className="w-full h-full object-cover"
                            />
                          </div>
                          {/* Rating Stars */}
                          <div className="flex justify-center lg:justify-start gap-1 mt-6">
                            {[...Array(testimonials[currentIndex].rating)].map((_, i) => (
                              <Star key={i} className="w-5 h-5 fill-accent text-accent" />
                            ))}
                          </div>
                        </div>
                        
                        <div className="space-y-2">
                          <h3 className="text-2xl font-semibold text-foreground">
                            {testimonials[currentIndex].name}
                          </h3>
                          <p className="text-accent font-medium">
                            {testimonials[currentIndex].position}
                          </p>
                          <p className="text-muted-foreground">
                            {testimonials[currentIndex].company}
                          </p>
                          <div className="pt-4">
                            <span className="inline-block px-4 py-2 bg-accent/10 text-accent text-sm rounded-full border border-accent/20">
                              {testimonials[currentIndex].projectType}
                            </span>
                          </div>
                        </div>
                      </div>

                      {/* Testimonial Content */}
                      <div className="lg:col-span-2">
                        <div className="relative">
                          {/* Quote Icon */}
                          <div className="absolute -top-4 -left-4 text-6xl text-accent/20 font-serif">"</div>
                          
                          <blockquote className="text-2xl lg:text-3xl text-foreground leading-relaxed font-medium pl-8">
                            {testimonials[currentIndex].text}
                          </blockquote>
                          
                          {/* Clutch Logo */}
                          <div className="flex items-center justify-end mt-8">
                            <div className="text-sm text-muted-foreground mr-4">
                              Verified Review on
                            </div>
                            <ImageWithFallback
                              src={clutchLogo}
                              alt="Clutch"
                              className="h-8 w-auto opacity-70 hover:opacity-100 transition-opacity duration-300"
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </motion.div>
            </AnimatePresence>
          </div>

          {/* Navigation Controls */}
          <div className="flex items-center justify-center mt-12 gap-8">
            {/* Previous Button */}
            <Button
              variant="outline"
              size="lg"
              onClick={goToPrevious}
              className="w-14 h-14 rounded-full border-white/20 hover:border-accent/50 hover:bg-accent/10 transition-all duration-300"
            >
              <ChevronLeft className="w-6 h-6" />
            </Button>

            {/* Dots Indicator */}
            <div className="flex gap-3">
              {testimonials.map((_, index) => (
                <button
                  key={index}
                  onClick={() => goToSlide(index)}
                  className={`w-3 h-3 rounded-full transition-all duration-300 ${
                    index === currentIndex
                      ? 'bg-accent scale-125'
                      : 'bg-white/30 hover:bg-white/50'
                  }`}
                  aria-label={`Go to testimonial ${index + 1}`}
                />
              ))}
            </div>

            {/* Next Button */}
            <Button
              variant="outline"
              size="lg"
              onClick={goToNext}
              className="w-14 h-14 rounded-full border-white/20 hover:border-accent/50 hover:bg-accent/10 transition-all duration-300"
            >
              <ChevronRight className="w-6 h-6" />
            </Button>
          </div>

          {/* Auto-play Indicator */}
          <div className="text-center mt-6">
            <button
              onClick={() => setIsAutoPlaying(!isAutoPlaying)}
              className="text-sm text-muted-foreground hover:text-foreground transition-colors duration-300"
            >
              {isAutoPlaying ? '⏸ Pause Auto-play' : '▶ Resume Auto-play'}
            </button>
          </div>
        </div>

        {/* Additional Social Proof */}
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          whileInView={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8, delay: 0.3 }}
          viewport={{ once: true }}
          className="text-center mt-20 pt-16 border-t border-white/10"
        >
          <div className="grid grid-cols-2 md:grid-cols-4 gap-8 max-w-4xl mx-auto">
            <div className="space-y-2">
              <div className="text-3xl font-bold text-accent">98%</div>
              <div className="text-sm text-muted-foreground">Client Satisfaction</div>
            </div>
            <div className="space-y-2">
              <div className="text-3xl font-bold text-accent">150+</div>
              <div className="text-sm text-muted-foreground">Projects Delivered</div>
            </div>
            <div className="space-y-2">
              <div className="text-3xl font-bold text-accent">5.0</div>
              <div className="text-sm text-muted-foreground">Average Rating</div>
            </div>
            <div className="space-y-2">
              <div className="text-3xl font-bold text-accent">24/7</div>
              <div className="text-sm text-muted-foreground">Support Available</div>
            </div>
          </div>
        </motion.div>
      </div>
    </section>
  );
};