"use client";

import { useState, useRef, useEffect } from "react";
import Image from "next/image";
import Link from "next/link";
import { Swiper, SwiperSlide } from "swiper/react";
import { Autoplay, Navigation } from "swiper/modules";

import "swiper/css";
import "swiper/css/navigation";
import { routes } from "@/src/config/routes";
import { isVideo } from "@/src/utils/helpers";

interface SliderItem {
    type?: "image" | "video";
    src?: string;
    poster?: string;
    title: string;
    link?: string;
    imageUrl: string;
    additionalFields?: any[];
}

interface ProductMediaSliderProps {
    items: SliderItem[];
    title?: any;
}

const ProductMediaSlider = ({ items, title }: ProductMediaSliderProps) => {
    const swiperRef = useRef<any>(null);
    const [activeMedia, setActiveMedia] = useState<{
        type: "image" | "video";
        src: string;
        title: string;
    } | null>(null);

    // Duplicate items if count is small to ensure smooth infinite seamless loop
    const displayItems =
        items && items.length > 0 && items.length < 6
            ? [...items, ...items, ...items]
            : items || [];

    const getMediaUrl = (url: string) => {
        if (!url) return "";
        if (url.startsWith("http://") || url.startsWith("https://")) {
            return url;
        }
        return `${process.env.NEXT_PUBLIC_API_IMAGE_URL || ""}${url}`;
    };

    const resumeSlider = () => {
        if (swiperRef.current) {
            const swiper = swiperRef.current;
            if (swiper.autoplay) {
                swiper.autoplay.stop();
                swiper.autoplay.start();
            }
            if (typeof swiper.slideNext === "function") {
                swiper.slideNext(3000, false);
            }
        }
    };

    const handleCloseModal = () => {
        setActiveMedia(null);
        setTimeout(resumeSlider, 50);
    };

    // Ensure autoplay resumes whenever activeMedia becomes null
    useEffect(() => {
        if (!activeMedia && swiperRef.current) {
            const timer = setTimeout(resumeSlider, 100);
            return () => clearTimeout(timer);
        }
    }, [activeMedia]);

    return (
        <>
            {title && (
                <section className="w-full pt-5">
                    <div className="container mx-auto px-5">
                        <div className="flex justify-center">
                            <h3
                                className="
                                    text-center
                                    bg-gradient-to-r
                                    from-[#d94cd2]
                                    via-[#ff6b9d]
                                    to-[#780e46]
                                    bg-clip-text
                                    text-transparent
                                    font-semibold
                                    sm:text-3xl
                                    lg:text-4xl
                                    pb-5
                                "
                            >
                                {title}
                            </h3>
                        </div>
                    </div>
                </section>
            )}

            <div className="w-full overflow-hidden">
                <Swiper
                    onSwiper={(swiper) => {
                        swiperRef.current = swiper;
                    }}
                    onTouchEnd={() => {
                        setTimeout(resumeSlider, 150);
                    }}
                    modules={[Autoplay, Navigation]}
                    autoplay={{
                        delay: 0,
                        disableOnInteraction: false,
                        pauseOnMouseEnter: false,
                    }}
                    loop={true}
                    speed={3000}
                    spaceBetween={0}
                    slidesPerView={1}
                    breakpoints={{
                        640: {
                            slidesPerView: 2,
                        },
                        1024: {
                            slidesPerView: 3,
                        },
                    }}
                    className="product-media-swiper [&_.swiper-wrapper]:!ease-linear"
                >
                    {displayItems?.map((item, index) => {
                        const mediaUrl = getMediaUrl(item?.imageUrl);
                        const itemIsVideo = isVideo(item?.imageUrl) || item?.type === "video";

                        return (
                            <SwiperSlide key={index}>
                                <div
                                    className="
                                        relative
                                        aspect-[1/1]
                                        min-h-[170px]
                                        cursor-pointer
                                        overflow-hidden
                                        rounded-xl
                                        p-1
                                    "
                                    onClick={() =>
                                        setActiveMedia({
                                            type: itemIsVideo ? "video" : "image",
                                            src: mediaUrl,
                                            title: item?.title || "",
                                        })
                                    }
                                >
                                    <div
                                        className="
                                            relative
                                            h-[260px]
                                            overflow-hidden
                                            rounded-xl
                                            bg-white
                                            flex
                                            items-center
                                            justify-center
                                        "
                                    >
                                        {itemIsVideo ? (
                                            <video
                                                src={mediaUrl}
                                                autoPlay
                                                muted
                                                loop
                                                playsInline
                                                className="
                                                    h-full
                                                    w-full
                                                    object-cover
                                                    p-2
                                                    transition-transform
                                                    duration-300
                                                    hover:scale-105
                                                "
                                            />
                                        ) : (
                                            <Image
                                                src={mediaUrl}
                                                alt={item?.title || "Product media"}
                                                fill
                                                className="
                                                    object-cover
                                                    p-2
                                                    transition-transform
                                                    duration-300
                                                    hover:scale-105
                                                "
                                            />
                                        )}

                                        <Link
                                            href={item?.additionalFields?.[0]?.customUrl || "#"}
                                            onClick={(e) => e.stopPropagation()}
                                            className="
                                                absolute
                                                bottom-5
                                                left-1/2
                                                -translate-x-1/2
                                                rounded-full
                                                bg-[#780e46]
                                                px-6
                                                py-2
                                                text-sm
                                                font-medium
                                                text-white
                                                transition
                                                hover:bg-white
                                                hover:text-[#780e46]
                                                z-10
                                            "
                                        >
                                            {item?.title}
                                        </Link>
                                    </div>
                                </div>
                            </SwiperSlide>
                        );
                    })}
                </Swiper>
            </div>

            {/* Fullscreen Preview */}
            {activeMedia && (
                <div
                    className="
                        fixed
                        inset-0
                        z-[9999]
                        flex
                        items-center
                        justify-center
                        bg-black/90
                        p-5
                    "
                    onClick={handleCloseModal}
                >
                    <div
                        className="
                            relative
                            max-h-[90vh]
                            max-w-[90vw]
                            flex
                            items-center
                            justify-center
                        "
                        onClick={(e) => e.stopPropagation()}
                    >
                        {activeMedia.type === "image" ? (
                            <Image
                                src={activeMedia.src}
                                alt={activeMedia.title}
                                width={1200}
                                height={900}
                                className="
                                    max-h-[90vh]
                                    w-auto
                                    object-contain
                                    rounded-xl
                                "
                            />
                        ) : (
                            <video
                                controls
                                autoPlay
                                className="
                                    max-h-[90vh]
                                    max-w-[90vw]
                                    rounded-xl
                                "
                            >
                                <source
                                    src={activeMedia.src}
                                    type="video/mp4"
                                />
                            </video>
                        )}

                        <button
                            onClick={handleCloseModal}
                            className="
                                absolute
                                -right-4
                                -top-4
                                rounded-full
                                bg-black/80
                                px-4
                                py-2
                                text-xl
                                text-white
                                hover:bg-black
                                z-20
                            "
                        >
                            ✕
                        </button>
                    </div>
                </div>
            )}
        </>
    );
};

export default ProductMediaSlider;