'use client'
import React, { useEffect, useState } from 'react'
import { Swiper, SwiperSlide } from 'swiper/react';
import { Autoplay } from 'swiper/modules';
import 'swiper/css';
import { collection, getDocs } from 'firebase/firestore';
import { db } from '@/utils/firebase';
import { getImageFallback, isFirebaseUrl } from '@/utils/imageFallback';

const CustomSlider = () => {
    const [clients, setClients] = useState([]);
    const [imageErrors, setImageErrors] = useState({});
    const [fallbackImages, setFallbackImages] = useState({});

    const fetchClients = async () => {
        const clientsCollection = collection(db, "OurClients");
        const clientsSnapshot = await getDocs(clientsCollection);
        const clientList = clientsSnapshot.docs.map(doc => ({
            ...doc.data()
        }))?.filter((item) => item?.status == true)
        setClients(clientList);
    };

    // Get the original image source - prioritize Firebase first
    const getImageSrc = (item, index) => {
        const originalUrl = item?.company_url;
        // If we already have a fallback set, use it
        if (fallbackImages[index]) {
            return fallbackImages[index];
        }
        // Otherwise, use the original URL (Firebase or otherwise)
        return originalUrl;
    };

    const handleImageError = (index) => {
        const originalUrl = clients[index]?.company_url;
        if (isFirebaseUrl(originalUrl)) {
            // Firebase image failed, use fallback from public/logos folder
            const fallback = getImageFallback(originalUrl, 'logo', index);
            setFallbackImages(prev => ({ ...prev, [index]: fallback }));
        } else {
            setImageErrors(prev => ({ ...prev, [index]: true }));
        }
    };

    useEffect(() => {
        fetchClients();
    }, []);

    return (
        <div id="slider-wrapper" className='company-slider'>
            <Swiper
                modules={[Autoplay]}
                spaceBetween={30}
                slidesPerView={6}
                autoplay={{
                    delay: 3000,
                    disableOnInteraction: false,
                }}
                loop={true}
                breakpoints={{
                    320: {
                        slidesPerView: 2,
                        spaceBetween: 20,
                    },
                    640: {
                        slidesPerView: 3,
                        spaceBetween: 20,
                    },
                    768: {
                        slidesPerView: 3,
                        spaceBetween: 30,
                    },
                    1024: {
                        slidesPerView: 6,
                        spaceBetween: 30,
                    },
                }}
                className="company-swiper"
            >
                {
                    clients?.map((item, index) => (
                        <SwiperSlide key={index}>
                            {imageErrors[index] && !fallbackImages[index] ? (
                                <div className="w-[60px] h-[60px] bg-gray-200 flex items-center justify-center rounded">
                                    <span className="text-xs text-gray-500">N/A</span>
                                </div>
                            ) : (
                                <img
                                    className="w-[60px] h-[60px] object-contain transition ease-in-out delay-150 hover:-translate-y-1 hover:scale-110 duration-300"
                                    src={getImageSrc(item, index)}
                                    alt="Best Service provider in Saudia Arabia"
                                    onError={() => handleImageError(index)}
                                    loading="lazy"
                                />
                            )}
                        </SwiperSlide>
                    ))
                }
            </Swiper>
        </div>
    )
}

export default CustomSlider