import React, { useEffect, useRef, useState } from 'react';
import Swiper from 'swiper/bundle';
import 'swiper/swiper-bundle.css';

interface Review {
    title: string;
    date: string;
    content: string;
    banner?: string;
}

interface ApiResponse {
    rating: number;
    totalReviews: number;
    review_text: string;
    reviews: Review[];
}

interface TestimonialSliderProps {
    apiUrl: string;
}

const getInitialColor = (name: string | undefined): string => {
    const colors: Record<string, string> = {
        A: '#4285F4', N: '#4285F4',
        B: '#DB4437', O: '#DB4437',
        C: '#F4B400', P: '#F4B400',
        D: '#0F9D58', Q: '#0F9D58',
        E: '#A142F4', R: '#A142F4',
        F: '#00ACC1', S: '#00ACC1',
        G: '#FF6D00', T: '#FF6D00',
        H: '#8E24AA', U: '#8E24AA',
        I: '#00BCD4', V: '#00BCD4',
        J: '#E91E63', W: '#E91E63',
        K: '#C0CA33', X: '#C0CA33',
        L: '#3F51B5', Y: '#3F51B5',
        M: '#F4511E', Z: '#F4511E',
    };

    const initial = name?.charAt(0).toUpperCase() || '';
    return colors[initial] || '#999';
};

const renderStarRating = (rating: number) => {
    const full = Math.floor(rating);
    const half = rating - full >= 0.5;
    const empty = 5 - full - (half ? 1 : 0);

    return (
        <div className="google-stars">
            {'★'.repeat(full)}
            {half && (
                <span className="half-star">
                    <span className="half">★</span>
                    <span className="empty">★</span>
                </span>
            )}
            {Array(empty)
                .fill(null)
                .map((_, i) => (
                    <span key={i} className="empty">
                        ★
                    </span>
                ))}
        </div>
    );
};

const TestimonialSlider: React.FC<TestimonialSliderProps> = ({ apiUrl }) => {
    const [data, setData] = useState<ApiResponse | null>(null);
    const [loading, setLoading] = useState(true);
    const swiperRef = useRef<Swiper | null>(null);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await fetch(apiUrl);
                if (!response.ok) throw new Error('Failed to fetch testimonials');
                const result: ApiResponse = await response.json();
                setData(result);
            } catch (error) {
                console.error(error);
                setData(null);
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, [apiUrl]);

    useEffect(() => {
        if (!data?.reviews?.length) return;

        swiperRef.current = new Swiper('.mySwiper', {
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
            slidesPerView: 1,
            spaceBetween: 20,
            loop: true,
            autoplay: {
                delay: 3000,   // 3 seconds delay
                disableOnInteraction: false, // autoplay won't stop after user interaction
            },
            breakpoints: {
                768: { slidesPerView: 2 },
                992: { slidesPerView: 3 },
            },
        });

        document.querySelectorAll('.testimonial-card').forEach((card) => {
            const textEl = card.querySelector<HTMLDivElement>('.review-text');
            const readMoreBtn = card.querySelector<HTMLDivElement>('.read-more');

            if (textEl && readMoreBtn) {
                if (textEl.scrollHeight <= textEl.clientHeight + 1) {
                    readMoreBtn.style.display = 'none';
                }

                readMoreBtn.onclick = () => {
                    textEl.classList.toggle('expanded');
                    readMoreBtn.textContent = textEl.classList.contains('expanded') ? 'Read less' : 'Read more';
                };
            }
        });

        return () => {
            swiperRef.current?.destroy();
            swiperRef.current = null;
        };
    }, [data]);

    if (loading) return <div>Loading testimonials...</div>;
    if (!data || !data.reviews.length) return <div></div>;

    return (
        <div className="section testimonial-wrapper">
            <div className="container">
                <h2 className="subscribe__title"></h2>
                <div className="featured-title-hold text-center clearfix">
                    <div className="line-container-parent">
                        <div className="lines-container flex-end">
                            <div className="line small-line"></div>
                            <div className="line big-line"></div>
                        </div>

                        <h5 className="line-text heading-primary-text dark-bg-light">Testimonials</h5>

                        <div className="lines-container">
                            <div className="line small-line"></div>
                            <div className="line big-line"></div>
                        </div>
                    </div>

                    <p className="site-h4">Our Client Reviews</p>
                </div>

                 <div className="row">
                    {/* Summary */}
                    <div className="col-md-3">
                        <div className="google-summary">
                            <h5>
                                <strong>{data.review_text}</strong>
                            </h5>
                            {renderStarRating(data.rating)}
                            <div className="mt-2">
                                Based on <strong>{data.totalReviews} reviews</strong>
                            </div>
                            <div className="mt-3">
                                <img
                                    src="https://cdn.trustindex.io/assets/platform/Google/logo.svg"
                                    alt="Google Logo"
                                    width="140"
                                />
                            </div>
                        </div>
                    </div>

                    {/* Swiper */}
                    <div className="col-md-9">
                        <div className="swiper mySwiper">
                            <div className="swiper-wrapper">
                                {data.reviews.map((v, i) => (
                                    <div className="swiper-slide" key={i}>
                                        <div className="testimonial-card bg-white">
                                            <div className="d-flex-itm align-items-center mb-2">
                                                <div
                                                    className="initial-circle"
                                                    style={{ backgroundColor: getInitialColor(v.title) }}
                                                >
                                                    {!v.banner ? v.title.charAt(0).toUpperCase() : <img src={v.banner} alt={v.title} />}
                                                </div>
                                                <div className="ms-2">
                                                    <strong>{v.title}</strong>
                                                    <small>{v.date}</small>
                                                </div>
                                            </div>
                                            <div className="star-rating">★★★★★</div>
                                            <div className="review-text">{v.content}</div>
                                            <div className="read-more">Read more</div>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                        <div className="swiper-button-next"></div>
                        <div className="swiper-button-prev"></div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default TestimonialSlider;