"use client";

import React, { useEffect, useState } from "react";
import { X, ChevronLeft, ChevronRight } from "lucide-react";
import { getValidImage } from "@/lib/utils";
import { motion, AnimatePresence } from "framer-motion";

interface ImagePreviewModalProps {
    isOpen: boolean;
    onClose: () => void;
    images: any[];
    initialIndex: number;
}

const ImagePreviewModal: React.FC<ImagePreviewModalProps> = ({
    isOpen,
    onClose,
    images,
    initialIndex,
}) => {
    const [currentIndex, setCurrentIndex] = useState(initialIndex);

    useEffect(() => {
        if (isOpen) {
            setCurrentIndex(initialIndex);
        }
    }, [isOpen, initialIndex]);

    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === "Escape") onClose();
            if (e.key === "ArrowRight") handleNext(e as any);
            if (e.key === "ArrowLeft") handlePrev(e as any);
        };

        if (isOpen) {
            window.addEventListener("keydown", handleKeyDown);
            document.body.style.overflow = "hidden";
        }

        return () => {
            window.removeEventListener("keydown", handleKeyDown);
            document.body.style.overflow = "unset";
        };
    }, [isOpen]);

    if (!isOpen || !images.length) return null;

    const handleNext = (e: React.MouseEvent | KeyboardEvent) => {
        e.stopPropagation();
        setCurrentIndex((prev) => (prev + 1) % images.length);
    };

    const handlePrev = (e: React.MouseEvent | KeyboardEvent) => {
        e.stopPropagation();
        setCurrentIndex((prev) => (prev - 1 + images.length) % images.length);
    };

    return (
        <AnimatePresence>
            <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="fixed inset-0 bg-black/90 backdrop-blur-sm z-[9999] flex items-center justify-center p-4 transition-all"
                onClick={onClose}
            >
                <button
                    onClick={onClose}
                    className="absolute top-6 right-6 text-white hover:text-primary transition-colors z-[10000] p-2 bg-black/50 rounded-full"
                >
                    <X size={28} />
                </button>

                {images.length > 1 && (
                    <>
                        <button
                            onClick={handlePrev}
                            className="absolute left-6 top-1/2 -translate-y-1/2 text-white hover:text-primary transition-all z-[10000] p-3 bg-black/50 hover:bg-black/80 rounded-full group"
                        >
                            <ChevronLeft size={36} className="group-hover:-translate-x-1 transition-transform" />
                        </button>
                        <button
                            onClick={handleNext}
                            className="absolute right-6 top-1/2 -translate-y-1/2 text-white hover:text-primary transition-all z-[10000] p-3 bg-black/50 hover:bg-black/80 rounded-full group"
                        >
                            <ChevronRight size={36} className="group-hover:translate-x-1 transition-transform" />
                        </button>
                    </>
                )}

                <motion.div
                    key={currentIndex}
                    initial={{ scale: 0.9, opacity: 0 }}
                    animate={{ scale: 1, opacity: 1 }}
                    exit={{ scale: 0.9, opacity: 0 }}
                    transition={{ type: "spring", damping: 25, stiffness: 200 }}
                    className="max-w-full max-h-full flex items-center justify-center relative"
                    onClick={(e) => e.stopPropagation()}
                >
                    <img
                        src={getValidImage(images[currentIndex])}
                        alt={`Preview ${currentIndex + 1}`}
                        className="max-w-[90vw] max-h-[80vh] object-contain rounded-xl shadow-2xl border border-white/10"
                        onError={(e) => {
                            const target = e.target as HTMLImageElement;
                            target.src = "/placeholder-restaurant.jpg";
                        }}
                    />
                </motion.div>

                {images.length > 1 && (
                    <div className="absolute bottom-6 left-1/2 -translate-x-1/2 flex flex-col items-center gap-3">
                        <div className="text-white bg-black/50 px-6 py-2 rounded-full text-sm font-medium backdrop-blur-md border border-white/10">
                            {currentIndex + 1} / {images.length}
                        </div>
                    </div>
                )}
            </motion.div>
        </AnimatePresence>
    );
};

export default ImagePreviewModal;
