'use client';

import { useState, useEffect } from 'react';
import Image from 'next/image';
import { Star, Users, ChevronLeft, ChevronRight } from 'lucide-react';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Testimonial } from '@/lib/data-store';

interface TestimonialSliderProps {
  testimonials: Testimonial[];
  autoPlay?: boolean;
  autoPlayDelay?: number;
  showArrows?: boolean;
  showDots?: boolean;
  className?: string;
}

export default function TestimonialSlider({
  testimonials,
  autoPlay = true,
  autoPlayDelay = 4000,
  showArrows = true,
  showDots = true,
  className = ''
}: TestimonialSliderProps) {
  const [currentIndex, setCurrentIndex] = useState(0);

  const activeTestimonials = testimonials.filter(t => t.isActive).sort((a, b) => a.order - b.order);

  // Auto-play functionality
  useEffect(() => {
    if (autoPlay && activeTestimonials.length > 1) {
      const interval = setInterval(() => {
        setCurrentIndex(prev => 
          prev >= activeTestimonials.length - 1 ? 0 : prev + 1
        );
      }, autoPlayDelay);

      return () => clearInterval(interval);
    }
  }, [autoPlay, autoPlayDelay, activeTestimonials.length]);

  const nextTestimonial = () => {
    setCurrentIndex(prev => 
      prev >= activeTestimonials.length - 1 ? 0 : prev + 1
    );
  };

  const prevTestimonial = () => {
    setCurrentIndex(prev => 
      prev <= 0 ? activeTestimonials.length - 1 : prev - 1
    );
  };

  const goToTestimonial = (index: number) => {
    setCurrentIndex(index);
  };

  if (activeTestimonials.length === 0) {
    return null;
  }

  // Show 3 testimonials at once on larger screens, 1 on mobile
  const testimonialsToShow = activeTestimonials.length >= 3 ? 3 : activeTestimonials.length;
  const maxIndex = Math.max(0, activeTestimonials.length - testimonialsToShow);

  const getVisibleTestimonials = () => {
    const start = Math.min(currentIndex, maxIndex);
    return activeTestimonials.slice(start, start + testimonialsToShow);
  };

  const visibleTestimonials = getVisibleTestimonials();

  return (
    <div className={`relative ${className}`}>
      {/* Testimonials Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-8">
        {visibleTestimonials.map((testimonial, index) => (
          <Card key={testimonial.id} className="text-center h-full">
            <CardHeader>
              <div className="flex justify-center mb-4">
                {testimonial.avatar ? (
                  <Image
                    src={testimonial.avatar}
                    alt={testimonial.customerName}
                    width={80}
                    height={80}
                    className="rounded-full"
                  />
                ) : (
                  <div className="w-20 h-20 bg-blue-100 rounded-full flex items-center justify-center">
                    <Users className="h-8 w-8 text-blue-600" />
                  </div>
                )}
              </div>
              <div className="flex justify-center mb-4">
                {[...Array(5)].map((_, i) => (
                  <Star
                    key={i}
                    className={`h-4 w-4 ${
                      i < testimonial.rating ? 'text-yellow-400 fill-current' : 'text-gray-300'
                    }`}
                  />
                ))}
              </div>
            </CardHeader>
            <CardContent className="flex flex-col justify-between flex-1">
              <div>
                <p className="text-gray-700 mb-6 italic">"{testimonial.content}"</p>
              </div>
              <div>
                <p className="font-semibold text-gray-900">{testimonial.customerName}</p>
                <p className="text-sm text-gray-600">{testimonial.position}</p>
                <p className="text-sm text-gray-600">{testimonial.company}</p>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Navigation Controls */}
      {activeTestimonials.length > testimonialsToShow && (
        <>
          {/* Navigation Arrows */}
          {showArrows && (
            <div className="flex justify-center gap-4 mb-6">
              <button
                onClick={prevTestimonial}
                className="bg-blue-600 hover:bg-blue-700 text-white p-2 rounded-full transition-colors"
                aria-label="Previous testimonials"
                disabled={currentIndex === 0}
              >
                <ChevronLeft className="h-5 w-5" />
              </button>
              <button
                onClick={nextTestimonial}
                className="bg-blue-600 hover:bg-blue-700 text-white p-2 rounded-full transition-colors"
                aria-label="Next testimonials"
                disabled={currentIndex >= maxIndex}
              >
                <ChevronRight className="h-5 w-5" />
              </button>
            </div>
          )}

          {/* Dots Indicator */}
          {showDots && (
            <div className="flex justify-center space-x-2">
              {Array.from({ length: maxIndex + 1 }, (_, index) => (
                <button
                  key={index}
                  onClick={() => goToTestimonial(index)}
                  className={`w-3 h-3 rounded-full transition-colors ${
                    index === currentIndex
                      ? 'bg-blue-600'
                      : 'bg-gray-300 hover:bg-gray-400'
                  }`}
                  aria-label={`Go to testimonial group ${index + 1}`}
                />
              ))}
            </div>
          )}
        </>
      )}

      {/* Progress Indicator */}
      {activeTestimonials.length > testimonialsToShow && (
        <div className="text-center text-sm text-gray-500 mt-4">
          Showing {currentIndex + 1}-{Math.min(currentIndex + testimonialsToShow, activeTestimonials.length)} of {activeTestimonials.length} testimonials
        </div>
      )}
    </div>
  );
}