'use client'

import useDeviceType from '@/utils/getDeviceType';
import React, { useContext, useEffect, useRef, useState } from 'react';
import Carousel from 'react-multi-carousel';
import "react-multi-carousel/lib/styles.css";
import ArrowRithCarrousel from "../../../public/assets/Images/Icons/ArrowRithCarroussel.svg";
import ArrowLeftCarroussel from "../../../public/assets/Images/Icons/ArrowLeftCarroussel.svg";
import Image from 'next/image';


interface CarouselImageI {
    itemDesktop?: number;
    itemTablet?: number;
    itemMobile?: number;
    slidesDesktop?: number;
    slidesTablet?: number;
    slidesMobile?: number;
    transition?: number;
    playSpeed?: number;
    children?: React.ReactNode;
    containerClassCustom?: string;
    itemClassCuston?: string;
    showDotsButton?: boolean;
    showarrows?: boolean;
    draggableAndSwipeable?: boolean;
    partialVisible?: boolean;
    partialVisibilityGutterDesktop?: number;
    partialVisibilityGutterTablet?: number;
    partialVisibilityGutterMobile?: number;
    activeBlue?: boolean;
}

export default function CarouselImage(props: CarouselImageI) {
    const deviceType = useDeviceType();
    const [mounted, setMounted] = useState(false);
    const [activeSlide, setActiveSlide] = useState(0); // Novo estado para rastrear o slide ativo
    const carouselRef = useRef<Carousel | null>(null);

    useEffect(() => {
        setMounted(true);
    }, []);

    // Força o react-multi-carousel a recalcular offsetWidth após layout (fix iOS Safari)
    useEffect(() => {
        if (!mounted) return;
        const raf = requestAnimationFrame(() => {
            window.dispatchEvent(new Event('resize'));
        });
        return () => cancelAnimationFrame(raf);
    }, [mounted]);

    const handleNext = () => {
        if (carouselRef.current && typeof carouselRef.current.next === 'function') {
            carouselRef.current.next(1);
        }
    };

    const handlePrev = () => {
        if (carouselRef.current && typeof carouselRef.current.previous === 'function') {
            carouselRef.current.previous(1);
        }
    };

    const CustomDot: React.FC<{ onClick?: () => void; active?: boolean; activeBlue?: boolean}> = ({ onClick, active, activeBlue }) => (
        <div
            onClick={onClick}
            className={`mx-1 h-1 ${activeBlue ? 'w-10' : 'w-6'} rounded-full transition ${activeBlue && !active ? 'bg-[#1A93B1]' : 'bg-white'} ${active && !activeBlue ? 'bg-gray-500' : 'bg-gray-200'}}`}
            style={{ cursor: 'pointer' }}
        />
    );

    const responsive = {
        desktop: {
            breakpoint: { max: 3000, min: 1024 },
            items: props.itemDesktop ?? 1,
            slidesToSlide: props.slidesDesktop ?? 1,
            partialVisibilityGutter: props.partialVisibilityGutterDesktop ?? 0
        },
        tablet: {
            breakpoint: { max: 1024, min: 464 },
            items: props.itemTablet ?? 1,
            slidesToSlide: props.slidesTablet ?? 1,
            partialVisibilityGutter: props.partialVisibilityGutterTablet ?? 0
        },
        mobile: {
            breakpoint: { max: 480, min: 0 },
            items: props.itemMobile ?? 1,
            slidesToSlide: props.slidesMobile ?? 1,
            partialVisibilityGutter: props.partialVisibilityGutterMobile ?? 0
        }
    };

    if (!mounted) return null;

    return (
        <div className="w-full">
            <Carousel
                ref={(ref) => {
                    carouselRef.current = ref;
                }}
                swipeable={props.draggableAndSwipeable ?? true}
                draggable={props.draggableAndSwipeable ?? true}
                showDots={false} // Desativamos os dots padrão do componente
                responsive={responsive}
                infinite={true}
                autoPlay={false}
                autoPlaySpeed={props.playSpeed ?? 0}
                keyBoardControl={true}
                customTransition="all .5"
                transitionDuration={props.transition ?? 500}
                containerClass={`${props.containerClassCustom}`}
                itemClass={`${props.itemClassCuston ?? 'pr-4'}`}
                arrows={false}
                partialVisible={props.partialVisible ?? true}
                afterChange={(previousSlide, { currentSlide }) => {
                    setActiveSlide(currentSlide); // Atualiza o slide ativo quando o carrossel muda
                }}
            >
                {props.children}
            </Carousel>

            {!!deviceType && deviceType == 'mobile' && (
                <div className="flex justify-around items-center mt-4 mb-4 space-x-4">

                    <div className="flex space-x-2">
                        {React.Children.map(props.children, (child, index) => (
                            child && 
                            <CustomDot
                                onClick={() => carouselRef.current?.goToSlide(index) }
                                active={activeSlide === index || (activeSlide % (React.Children.map.length) === index) }
                                activeBlue={ (props.activeBlue ?? false) }
                            />
                        ))}
                    </div>

                    <div className='flex justify-center items-center gap-4'>
                        <button
                            onClick={handlePrev}
                            className="bg-slate-50 border w-[42px] h-[42px] border-plamev-blue-600 text-white p-2 rounded-full hover:bg-opacity-75 transition flex justify-center items-center"
                        >
                            <Image src={ArrowLeftCarroussel} alt='' />
                        </button>

                        <button
                            onClick={handleNext}
                            className="bg-slate-50 border w-[42px] h-[42px] border-plamev-blue-600 text-white p-2 rounded-full hover:bg-opacity-75 transition flex justify-center items-center"
                        >
                            <Image src={ArrowRithCarrousel} alt='' />
                        </button>
                    </div>
                </div>
            )}
        </div>
    );
}
