import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Star, Quote, ChevronLeft, ChevronRight } from 'lucide-react';

interface TestimonialItem {
    id: number;
    customer_name: string;
    designation: string;
    company?: string;
    rating: number;
    testimonial: string;
}

interface TestimonialProps {
    testimonials: TestimonialItem[];
}

export const TestimonialSlider: React.FC<TestimonialProps> = ({ testimonials }) => {
    const [current, setCurrent] = useState(0);
    const [isAnimating, setIsAnimating] = useState(false);
    const [direction, setDirection] = useState<'left' | 'right'>('left');
    const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);

    if (!testimonials || testimonials.length === 0) return null;

    // How many cards visible based on screen (handled via CSS grid)
    const total = testimonials.length;

    const go = useCallback(
        (dir: 'prev' | 'next') => {
            if (isAnimating) return;
            setDirection(dir === 'next' ? 'left' : 'right');
            setIsAnimating(true);
            setTimeout(() => {
                setCurrent((prev) => (dir === 'next' ? (prev + 1) % total : (prev - 1 + total) % total));
                setIsAnimating(false);
            }, 400);
        },
        [isAnimating, total],
    );

    // Auto-advance every 4.5s
    const resetTimer = useCallback(() => {
        if (timerRef.current) clearInterval(timerRef.current);
        timerRef.current = setInterval(() => go('next'), 4500);
    }, [go]);

    useEffect(() => {
        if (total > 1) resetTimer();
        return () => {
            if (timerRef.current) clearInterval(timerRef.current);
        };
    }, [total, resetTimer]);

    // Build a circular window of visible testimonials
    // Desktop: 3, tablet: 2, mobile: 1
    const getVisible = () => {
        const indices: number[] = [];
        for (let i = 0; i < Math.min(3, total); i++) {
            indices.push((current + i) % total);
        }
        return indices;
    };

    const visibleIndices = getVisible();

    const Card = ({ t }: { t: TestimonialItem }) => (
        <div className="glass-card rounded-2xl p-6 sm:p-7 flex flex-col justify-between relative h-full w-full border border-slate-800/80 bg-[#0B132B]/60 backdrop-blur-md">
            <Quote className="w-8 h-8 text-[#00F2FE]/20 absolute top-4 right-4 flex-shrink-0" />
            <div>
                <div className="flex items-center gap-1 mb-4 text-amber-400">
                    {[...Array(t.rating || 5)].map((_, i) => (
                        <Star key={i} className="w-4 h-4 fill-amber-400" />
                    ))}
                </div>
                <p className="text-sm sm:text-base text-slate-300 italic mb-6 leading-relaxed">"{t.testimonial}"</p>
            </div>
            <div className="pt-4 border-t border-slate-800">
                <h4 className="text-sm sm:text-base font-bold text-white">{t.customer_name}</h4>
                <p className="text-xs text-[#00F2FE]">
                    {t.designation}
                    {t.company ? ` • ${t.company}` : ''}
                </p>
            </div>
        </div>
    );

    const gridColsClass =
        total === 1
            ? 'grid-cols-1 max-w-xl mx-auto'
            : total === 2
              ? 'grid-cols-1 md:grid-cols-2 max-w-4xl mx-auto'
              : 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3';

    return (
        <div className="relative w-full" onMouseEnter={() => { if (timerRef.current) clearInterval(timerRef.current); }} onMouseLeave={resetTimer}>
            {/* Cards grid */}
            <div
                className={`grid ${gridColsClass} gap-6 transition-all duration-500 ease-in-out ${
                    isAnimating
                        ? direction === 'left'
                            ? 'opacity-0 translate-x-[-20px]'
                            : 'opacity-0 translate-x-[20px]'
                        : 'opacity-100 translate-x-0'
                }`}
            >
                {/* Mobile: 1 card full width; tablet: 2 cards; desktop: 3 cards */}
                <div className="w-full">
                    <Card t={testimonials[visibleIndices[0]]} />
                </div>
                {total > 1 && (
                    <div className="hidden md:block w-full">
                        <Card t={testimonials[visibleIndices[1]]} />
                    </div>
                )}
                {total > 2 && (
                    <div className="hidden lg:block w-full">
                        <Card t={testimonials[visibleIndices[2]]} />
                    </div>
                )}
            </div>


            {/* Controls — only when more than 1 card */}
            {total > 1 && (
                <div className="flex items-center justify-center gap-4 mt-8">
                    {/* Prev */}
                    <button
                        onClick={() => { go('prev'); resetTimer(); }}
                        aria-label="Previous"
                        className="w-9 h-9 rounded-full bg-[#0B132B] border border-[#00F2FE]/30 text-[#00F2FE] flex items-center justify-center hover:bg-[#00F2FE]/10 transition-colors"
                    >
                        <ChevronLeft className="w-5 h-5" />
                    </button>

                    {/* Dots */}
                    <div className="flex items-center gap-2">
                        {testimonials.map((_, idx) => (
                            <button
                                key={idx}
                                onClick={() => {
                                    if (isAnimating) return;
                                    setDirection(idx > current ? 'left' : 'right');
                                    setIsAnimating(true);
                                    setTimeout(() => { setCurrent(idx); setIsAnimating(false); }, 400);
                                    resetTimer();
                                }}
                                aria-label={`Go to slide ${idx + 1}`}
                                className="transition-all duration-300 rounded-full"
                                style={{
                                    width: idx === current ? '20px' : '6px',
                                    height: '6px',
                                    background: idx === current ? '#00F2FE' : 'rgba(148,163,184,0.3)',
                                }}
                            />
                        ))}
                    </div>

                    {/* Next */}
                    <button
                        onClick={() => { go('next'); resetTimer(); }}
                        aria-label="Next"
                        className="w-9 h-9 rounded-full bg-[#0B132B] border border-[#00F2FE]/30 text-[#00F2FE] flex items-center justify-center hover:bg-[#00F2FE]/10 transition-colors"
                    >
                        <ChevronRight className="w-5 h-5" />
                    </button>
                </div>
            )}
        </div>
    );
};
