'use client'
import { useLocale } from 'next-intl';
import Image from 'next/image';
import Link from 'next/link';
import React, { useState } from 'react'
import { Carousel } from 'react-bootstrap'
import { getImageFallback, isFirebaseUrl } from '@/utils/imageFallback';

const CustomCarousel = ({ banners }) => {
    const locale = useLocale();
    const [imageErrors, setImageErrors] = useState({});
    const [fallbackImages, setFallbackImages] = useState({});

    const convertSecToMilli = (sec) => {
        return sec * 1000;
    }

    // Get the original image source - prioritize Firebase first
    const getImageSrc = (item, index) => {
        const originalUrl = locale == 'en' ? item?.media_url_en : item?.media_url_ar;
        // 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 = locale == 'en' ? banners[index]?.media_url_en : banners[index]?.media_url_ar;
        if (isFirebaseUrl(originalUrl)) {
            // Firebase image failed, use fallback from public folder
            const fallback = getImageFallback(originalUrl, 'banner', index);
            setFallbackImages(prev => ({ ...prev, [index]: fallback }));
        } else {
            setImageErrors(prev => ({ ...prev, [index]: true }));
        }
    }

    return (
        <Carousel className='banner'>
            {
                banners?.map((item, index) => (
                    <Carousel.Item key={index} interval={convertSecToMilli(item?.interval)}>
                        <Link href={locale == 'en' ? item?.on_click_url_en : item?.on_click_url_ar} target='_blank' >
                            {
                                item?.type == 'image' ?
                                    <div className="relative w-full h-[400px] md:h-[500px] lg:h-[600px]">
                                        {imageErrors[index] && !fallbackImages[index] ? (
                                            <div className="w-full h-full bg-gray-200 flex items-center justify-center">
                                                <span className="text-gray-500">Image unavailable</span>
                                            </div>
                                        ) : (
                                            <Image
                                                src={getImageSrc(item, index)}
                                                alt="New car prices in GCC"
                                                fill
                                                className="object-contain"
                                                loading='eager'
                                                placeholder="blur"
                                                blurDataURL="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MDAiIGhlaWdodD0iMzAwIj48cmVjdCB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgZmlsbD0iI2VlZWVlZSIvPjwvc3ZnPg=="
                                                onError={() => handleImageError(index)}
                                                unoptimized={isFirebaseUrl(locale == 'en' ? item?.media_url_en : item?.media_url_ar)}
                                            />
                                        )}
                                    </div>
                                    :
                                    <video src={locale == 'en' ? item?.media_url_en : item?.media_url_ar} type="video/mp4" className='w-full' autoPlay muted loop />
                            }
                        </Link>
                    </Carousel.Item>
                ))
            }
        </Carousel>
    )
}

export default CustomCarousel