import { createPortal } from "react-dom";
import { useEffect, useState } from "react";
import { X, ChevronLeft, ChevronRight } from "lucide-react";

export type ImageItem = {
    url: string;
    alt_text?: string;
};

type Props = {
    images: ImageItem[];
    open: boolean;
    setOpen: (v: boolean) => void;
    initialIndex?: number;
};

export default function FullscreenImageCarousel({
    images,
    open,
    setOpen,
    initialIndex = 0,
}: Props) {
    const [index, setIndex] = useState(initialIndex);

    useEffect(() => {
        if (open) setIndex(initialIndex);
    }, [open, initialIndex]);

    useEffect(() => {
        if (!open) return;

        const onKeyDown = (e: KeyboardEvent) => {
            if (e.key === "Escape") setOpen(false);
            if (e.key === "ArrowRight") next();
            if (e.key === "ArrowLeft") prev();
        };

        window.addEventListener("keydown", onKeyDown);
        return () => window.removeEventListener("keydown", onKeyDown);
    }, [open, index]);

    if (!open) return null;

    const prev = () =>
        setIndex((i) => (i - 1 + images.length) % images.length);

    const next = () =>
        setIndex((i) => (i + 1) % images.length);

    return createPortal(
        <div className="fixed inset-0 z-9999 bg-black/95 flex flex-col items-center justify-center">

            {/* CLOSE */}
            <button
                onClick={() => setOpen(false)}
                className="absolute top-5 right-5 text-white "
            >
                <X className="w-8 h-8" />
            </button>

            {/* MAIN IMAGE */}
            <div className="relative w-full max-w-6xl h-[75vh] flex items-center justify-center px-4">

                <button onClick={prev} className="absolute left-3 text-white"      >        <ChevronLeft size={40} />      </button>

                <img
                    src={images[index].url}
                    alt={images[index].alt_text}
                    className="max-h-full max-w-full object-contain rounded-lg"
                />

                <button onClick={next} className="absolute right-3 text-white"      >  <ChevronRight size={40} />     </button>
            </div>

            {/* THUMBNAILS */}
            <div className="flex gap-3 mt-6 overflow-x-auto overflow-y-hidden px-4">
                {images.map((img, i) => (
                    <img
                        key={i}
                        src={img.url}
                        onClick={() => setIndex(i)}
                        className={`h-16 w-24 object-contain rounded-md cursor-pointer transition
                        ${i === index ? "scale-105 opacity-100" : "opacity-50"}`}
                    />
                ))}
            </div>
        </div>,
        document.body
    );
}