"use client";

import {X, Edit, Minus, Plus} from "lucide-react";
import {useEffect, useState} from "react";

type YearlyCalendarImage = {
    id: number | string;
    image?: string;
    cropped_image?: string | null;
    selected_crop_image?: string | null;
    updated_at?: string;
};

type Props = {
    isOpen: boolean;
    images: YearlyCalendarImage[];
    addingToCart?: boolean;
    onClose: () => void;
    onConfirm: (orderedImages: YearlyCalendarImage[], qty: number) => void;
    onEditImage?: (image: YearlyCalendarImage) => void;
};

const calendarTemplateUrl =
    "https://s3.eu-west-1.amazonaws.com/uploads.yallacheese.com/Calenders/Yearly/yearly-container.png";

const imageAreaStyle = {
    top: "3%",
    left: "4%",
    width: "92%",
    height: "48%",
};

const imageSlots = [
    // A
    {
        key: "A",
        style: {left: "0%", top: "0%", width: "34%", height: "49%"},
    },

    // B
    {
        key: "B",
        style: {left: "34%", top: "0%", width: "33%", height: "49%"},
    },

    // C
    {
        key: "C",
        style: {left: "67%", top: "0%", width: "33%", height: "81%"},
    },

    // D
    {
        key: "D",
        style: {left: "0%", top: "48%", width: "34%", height: "32%"},
    },

    // E
    {
        key: "E",
        style: {left: "34%", top: "48%", width: "33%", height: "64%"},
    },

    // F
    {
        key: "F",
        style: {left: "0%", top: "80%", width: "34%", height: "32%"},
    },

    // G
    {
        key: "G",
        style: {left: "67%", top: "80%", width: "33%", height: "32%"},
    },
];

export default function YearlyCalendarModal({
                                                isOpen,
                                                images,
                                                addingToCart = false,
                                                onClose,
                                                onConfirm,
                                                onEditImage,
                                            }: Props) {
    if (!isOpen) return null;
    const getImageSrc = (img: YearlyCalendarImage) => {
        return img.cropped_image || img.selected_crop_image || img.image || "";
    };
    const [slotImages, setSlotImages] = useState<YearlyCalendarImage[]>([]);
    const [selectedSlotIndex, setSelectedSlotIndex] = useState<number | null>(null);

    const [qty, setQty] = useState(1);

    const increaseQty = () => {
        setQty((prev) => prev + 1);
    };

    const decreaseQty = () => {
        setQty((prev) => (prev > 1 ? prev - 1 : 1));
    };

    useEffect(() => {
        if (!isOpen) return;
        setQty(1);
        setSlotImages((prev) => {
            if (prev.length === 0) {
                return images.slice(0, 7);
            }

            // بعد القص، نحدّث نفس الصور بدون ما نخرب ترتيب المستخدم
            return prev.map((oldImg) => {
                return (
                    images.find((newImg) => String(newImg.id) === String(oldImg.id)) ??
                    oldImg
                );
            });
        });

        setSelectedSlotIndex(null);
    }, [isOpen, images]);

    const swapSlots = (index: number) => {
        if (selectedSlotIndex === null) {
            setSelectedSlotIndex(index);
            return;
        }

        if (selectedSlotIndex === index) {
            setSelectedSlotIndex(null);
            return;
        }

        setSlotImages((prev) => {
            const next = [...prev];
            const temp = next[selectedSlotIndex];
            next[selectedSlotIndex] = next[index];
            next[index] = temp;
            return next;
        });

        setSelectedSlotIndex(null);
    };

    const selectedImages = slotImages;

    return (
        <div
            className="fixed inset-0 z-[80] bg-black/60 flex items-center justify-center p-3"
            onClick={onClose}
        >
            <div
                className="bg-white rounded-2xl w-full max-w-[760px] max-h-[96vh] overflow-hidden shadow-2xl flex flex-col"
                onClick={(e) => e.stopPropagation()}
            >

                <div className="shrink-0 flex items-center justify-between px-4 py-3 border-b">
                    <button
                        type="button"
                        onClick={onClose}
                        className="w-9 h-9 rounded-full flex items-center justify-center bg-gray-100"
                    >
                        <X size={18}/>
                    </button>

                    <h2 className="text-base font-bold text-gray-800">
                        تصميم الرزنامة السنوية
                    </h2>
                    <button
                        type="button"
                        disabled={addingToCart}
                        onClick={() => onConfirm(slotImages, qty)}
                        className="font-bold cursor-pointer fixed bottom-2 left-1/2 transform -translate-x-1/2 block login-btn transition mt-8 bg-primary text-white px-6 w-[343px] h-[48px] py-3 rounded-full z-20 disabled:opacity-60 disabled:cursor-not-allowed"
                    >
                        {addingToCart ? "جاري الإضافة..." : "تأكيد"}
                    </button>
                </div>
                <p className="text-center text-xs text-gray-500 mt-3">
                    اضغط على صورة ثم صورة أخرى لتبديل أماكنهما، أو اضغط على أيقونة التعديل لقص الصورة
                </p>
                <div className="flex items-center justify-center gap-4 mt-4">
                    <button
                        type="button"
                        onClick={decreaseQty}
                        className="w-8 h-8 rounded-full bg-[#FFE7F0] text-[#FF2B77] flex items-center justify-center"
                    >
                        <Minus size={16}/>
                    </button>

                    <div className="flex flex-col items-center">
                        <span className="text-xs text-gray-500">الكمية</span>
                        <span className="text-lg font-bold text-gray-800">{qty}</span>
                    </div>

                    <button
                        type="button"
                        onClick={increaseQty}
                        className="w-8 h-8 rounded-full bg-[#FF2B77] text-white flex items-center justify-center"
                    >
                        <Plus size={16}/>
                    </button>
                </div>

                <div className="flex-1 overflow-y-auto bg-[#f4f4f4] p-4">
                    <div className="relative mx-auto w-full max-w-[620px] bg-white shadow-lg">
                        <img
                            src={calendarTemplateUrl}
                            alt="Yearly calendar template"
                            className="block w-full select-none pointer-events-none"
                        />

                        <div
                            className="absolute"
                            style={imageAreaStyle}
                        >
                            {selectedImages.map((img, index) => (
                                <div
                                    key={img.id}
                                    onClick={() => swapSlots(index)}
                                    className={`absolute overflow-hidden bg-gray-100 cursor-pointer transition-all ${
                                        selectedSlotIndex === index
                                            ? "ring-4 ring-[#FF2B77] z-20"
                                            : "ring-1 ring-white"
                                    }`}
                                    style={imageSlots[index].style}
                                >
                                    <img
                                        src={`${getImageSrc(img)}?t=${img.updated_at || Date.now()}`}
                                        alt={`calendar-photo-${index + 1}`}
                                        className="w-full h-full object-cover"
                                        draggable={false}
                                    />

                                    <button
                                        type="button"
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            onEditImage?.(img);
                                        }}
                                        className="absolute top-2 right-2 z-30 w-8 h-8 rounded-full bg-white/90 flex items-center justify-center shadow"
                                        title="قص الصورة"
                                    >
                                        <Edit size={16} className="text-[#FF2B77]"/>
                                    </button>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}