"use client";

import Image from "next/image";
import { Edit, Trash2 } from "lucide-react";
import { useEffect, useState } from "react";
import {toast} from "sonner";
import api from "@/api/axios";

type YearlyCalendarImage = {
    id: number | string;
    image?: string;
    cropped_image?: string | null;
    selected_crop_image?: string | null;
    updated_at?: string;
    uploadStatus?: "pending" | "uploading" | "success" | "failed";

    monthIndex?: number;
    sort_order?: number;
    calendar_slot?: string;
    calendar_type?: string;
};

type YearlyCalendarProps = {
    images: YearlyCalendarImage[];
    selectedEffect: string;
    backgroundColor: string;
    effects: any;
    isUploadingImage: (img: any) => boolean;
    removeImage: (id: string) => void;
    onOpenUpload: (slotIndex?: number) => void;
    onEditImage?: (image: YearlyCalendarImage) => void;

    qty: number;
    increaseQty: () => void;
    decreaseQty: () => void;

    /**
     * مهم:
     * نحتاج نرجع الترتيب الجديد للأب حتى عند add to cart
     * validImages يكون بنفس ترتيب السحب والإفلات.
     */
    setImages?: (value: any) => void;
};

const calendarTemplateUrl =
    `${process.env.NEXT_PUBLIC_STORAGE_URL}/yearly-template/yearly-template.png`;

const imageAreaStyle = {
    top: "3%",
    left: "4%",
    width: "92%",
    height: "48%",
};


const imageSlots = [
    // العمود الأول
    {
        key: "A",
        style: { left: "0%", top: "0%", width: "34%", height: "49%" },
    },
    {
        key: "B",
        style: { left: "0%", top: "48%", width: "34%", height: "32%" },
    },
    {
        key: "C",
        style: { left: "0%", top: "80%", width: "34%", height: "32%" },
    },

    // العمود الثاني
    {
        key: "D",
        style: { left: "34%", top: "0%", width: "33%", height: "49%" },
    },
    {
        key: "E",
        style: { left: "34%", top: "48%", width: "33%", height: "64%" },
    },

    // العمود الثالث
    {
        key: "F",
        style: { left: "67%", top: "0%", width: "33%", height: "81%" },
    },
    {
        key: "G",
        style: { left: "67%", top: "80%", width: "33%", height: "32%" },
    },
];

export default function YearlyCalendar({
                                           images,
                                           selectedEffect,
                                           backgroundColor,
                                           effects,
                                           isUploadingImage,
                                           removeImage,
                                           onOpenUpload,
                                           onEditImage,
                                           qty,
                                           increaseQty,
                                           decreaseQty,
                                           setImages,
                                       }: YearlyCalendarProps) {

    const [slotImages, setSlotImages] = useState<Array<YearlyCalendarImage | null>>(
        new Array(7).fill(null)
    );

    useEffect(() => {
        setSlotImages(() => {
            const currentImages = images.filter((img) => img?.id).slice(0, 7);

            const next = new Array(7).fill(null) as Array<YearlyCalendarImage | null>;

            currentImages.forEach((img, fallbackIndex) => {
                const slotIndexFromCalendarSlot = imageSlots.findIndex(
                    (slot) => slot.key === String(img.calendar_slot || "").trim()
                );

                const index =
                    typeof img.monthIndex === "number" && img.monthIndex >= 0 && img.monthIndex < 7
                        ? img.monthIndex
                        : slotIndexFromCalendarSlot >= 0
                            ? slotIndexFromCalendarSlot
                            : img.sort_order && Number(img.sort_order) >= 1 && Number(img.sort_order) <= 7
                                ? Number(img.sort_order) - 1
                                : fallbackIndex;

                next[index] = {
                    ...img,
                    monthIndex: index,
                    sort_order: index + 1,
                    calendar_slot: imageSlots[index].key,
                    calendar_type: "yearly",
                };
            });

            return next;
        });
    }, [images]);

    const syncParentImages = (nextSlots: Array<YearlyCalendarImage | null>) => {
        const ordered = nextSlots
            .map((img, index) => {
                if (!img?.id) return null;

                return {
                    ...img,
                    monthIndex: index,
                    sort_order: index + 1,
                    calendar_slot: imageSlots[index].key,
                    calendar_type: "yearly",
                };
            })
            .filter(Boolean);

        setImages?.(ordered);
    };

    const [dragIndex, setDragIndex] = useState<number | null>(null);
    const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);

    /*const selectedImages = images.slice(0, 7);*/

    const getImageSrc = (img: YearlyCalendarImage) => {
        return img.cropped_image || img.selected_crop_image || img.image || "";
    };

    const swapImages = async (
        fromIndex: number,
        toIndex: number
    ) => {
        if (fromIndex === toIndex) return;

        const fromImg = slotImages[fromIndex];
        const toImg = slotImages[toIndex];

        if (!fromImg?.id || !toImg?.id) return;

        const previousSlots = [...slotImages];
        const next = [...slotImages];

        next[fromIndex] = {
            ...toImg,
            monthIndex: fromIndex,
            sort_order: fromIndex + 1,
            calendar_slot: imageSlots[fromIndex].key,
            calendar_type: "yearly",
        };

        next[toIndex] = {
            ...fromImg,
            monthIndex: toIndex,
            sort_order: toIndex + 1,
            calendar_slot: imageSlots[toIndex].key,
            calendar_type: "yearly",
        };

        // تحديث فوري للواجهة
        setSlotImages(next);
        syncParentImages(next);

        try {
            const response = await api.post(
                "account-images/yearly-calendar/swap",
                {
                    first_image_id: Number(fromImg.id),
                    first_slot: imageSlots[toIndex].key,

                    second_image_id: Number(toImg.id),
                    second_slot: imageSlots[fromIndex].key,
                }
            );

            const firstUpdated =
                response.data.data.first_image;

            const secondUpdated =
                response.data.data.second_image;

            const finalSlots = next.map((image) => {
                if (String(image?.id) === String(firstUpdated.id)) {
                    return firstUpdated;
                }

                if (String(image?.id) === String(secondUpdated.id)) {
                    return secondUpdated;
                }

                return image;
            });

            setSlotImages(finalSlots);
            syncParentImages(finalSlots);
        } catch (error: any) {
            setSlotImages(previousSlots);
            syncParentImages(previousSlots);

            console.error("Swap yearly images error:", error);
            console.error("Status:", error?.response?.status);
            console.error("Response data:", error?.response?.data);

            toast.error(
                error?.response?.data?.message ||
                error?.response?.data?.error ||
                error?.message ||
                "فشل تبديل الصور"
            );
        }
    };

    const handleDragStart = (index: number) => {
        setDragIndex(index);
    };

    const handleDragOver = (
        e: React.DragEvent<HTMLDivElement>,
        index: number
    ) => {
        e.preventDefault();

        // لا تعمل highlight على خانة فارغة
        if (!slotImages[index]?.id) {
            setDragOverIndex(null);
            return;
        }

        setDragOverIndex(index);
    };

    const handleDrop = (
        e: React.DragEvent<HTMLDivElement>,
        dropIndex: number
    ) => {
        e.preventDefault();

        if (dragIndex === null) return;

        const fromImg = slotImages[dragIndex];
        const toImg = slotImages[dropIndex];

        if (!fromImg?.id || !toImg?.id) {
            setDragIndex(null);
            setDragOverIndex(null);
            return;
        }

        swapImages(dragIndex, dropIndex);

        setDragIndex(null);
        setDragOverIndex(null);
    };

    const handleDragEnd = () => {
        setDragIndex(null);
        setDragOverIndex(null);
    };

    const handleRemoveSlotImage = (index: number, imageId: string) => {
        const next = [...slotImages];

        // نخلي نفس الخانة فارغة بدون تحريك باقي الصور
        next[index] = null;

        setSlotImages(next);
        syncParentImages(next);

        removeImage(imageId);
    };

    return (
        <div className="w-full max-w-5xl mx-auto mt-8 mb-28 flex flex-col items-center">
            <div className="w-full flex justify-center mb-4">
                <button
                    type="button"
                    onClick={() => {
                        const emptyIndex = slotImages.findIndex((img) => !img?.id);
                        onOpenUpload(emptyIndex >= 0 ? emptyIndex : undefined);
                    }}
                    className="flex items-center gap-2 bg-white border border-[#E2E2E2] rounded-full px-5 py-3 shadow-sm text-[#FF2B77] font-medium"
                >
                    <span className="text-xl leading-none">+</span>
                    <span>إضافة صور</span>
                    <span className="text-gray-500 text-sm">
                        {slotImages.filter((img) => img?.id).length}/7
                    </span>
                </button>
            </div>

            <div
                className="relative mx-auto w-full max-w-[720px] bg-white shadow-lg"
                style={{ backgroundColor }}
            >
                <img
                    src={calendarTemplateUrl}
                    alt="Yearly calendar template"
                    className="block w-full select-none pointer-events-none"
                />

                <div className="absolute" style={imageAreaStyle}>
                    {imageSlots.map((slot, index) => {
                        const img = slotImages[index];
                        const src = img ? getImageSrc(img) : "";

                        return (
                            <div
                                key={slot.key}
                                draggable={!!img?.id}
                                onDragStart={() => handleDragStart(index)}
                                onDragOver={(e) => handleDragOver(e, index)}
                                onDrop={(e) => handleDrop(e, index)}
                                onDragEnd={handleDragEnd}
                                className={`absolute overflow-hidden bg-gray-100 transition-all ${
                                    img ? "cursor-move" : "cursor-pointer"
                                } ${
                                    dragOverIndex === index
                                        ? "ring-4 ring-[#FF2B77] z-20"
                                        : "ring-1 ring-white"
                                }`}
                                style={slot.style}
                                onClick={() => {
                                    if (!img) onOpenUpload(index);
                                }}
                            >
                                {img && src ? (
                                    <>
                                        <img
                                            src={`${src}?t=${img.updated_at || ""}`}
                                            alt={`calendar-photo-${index + 1}`}
                                            className="w-full h-full object-cover"
                                            draggable={false}
                                            style={{
                                                filter:
                                                    effects?.[
                                                        selectedEffect as keyof typeof effects
                                                        ] ?? "none",
                                            }}
                                        />

                                        {isUploadingImage(img) && (
                                            <div className="absolute inset-0 bg-white/70 flex items-center justify-center text-xs text-gray-700 z-20">
                                                جاري الرفع...
                                            </div>
                                        )}

                                        <div className="absolute top-2 right-2 z-30 flex gap-2">
                                            <button
                                                type="button"
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    onEditImage?.(img);
                                                }}
                                                className="w-8 h-8 rounded-full bg-white/90 flex items-center justify-center shadow"
                                                title="تعديل الصورة"
                                            >
                                                <Edit
                                                    size={16}
                                                    className="text-[#FF2B77]"
                                                />
                                            </button>

                                            <button
                                                type="button"
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    handleRemoveSlotImage(index, String(img.id));
                                                }}
                                                className="w-8 h-8 rounded-full bg-white/90 flex items-center justify-center shadow"
                                                title="حذف الصورة"
                                            >
                                                <Trash2
                                                    size={15}
                                                    className="text-red-500"
                                                />
                                            </button>
                                        </div>
                                    </>
                                ) : (
                                    <button
                                        type="button"
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            onOpenUpload(index);
                                        }}
                                        className="w-full h-full flex flex-col items-center justify-center text-gray-400 hover:text-[#FF2B77] bg-gray-100"
                                    >
                                        <span className="text-2xl leading-none">+</span>
                                        <span className="text-[11px] mt-1">
                                            صورة {slot.key}
                                        </span>
                                    </button>
                                )}
                            </div>
                        );
                    })}
                </div>
            </div>

            <div className="bg-white content-ltr rounded-2xl shadow-lg flex items-center justify-around w-[390px] py-4 px-3 mt-6 mb-4">
                <button
                    className="flex flex-col items-center text-pink-500 cursor-pointer"
                    onClick={() => {
                        const emptyIndex = slotImages.findIndex((img) => !img?.id);
                        onOpenUpload(emptyIndex >= 0 ? emptyIndex : undefined);
                    }}
                    type="button"
                >
                    <div className="bg-pink-100 p-3 rounded-[16px] mb-2">
                        <Image
                            src="/icons/plus.svg"
                            alt="plus"
                            width={24}
                            height={24}
                        />
                    </div>
                    <span className="text-xs">إضافة صور</span>
                </button>

                <div className="flex flex-col items-center text-gray-700">
                    <span className="text-xs mb-2">الكمية</span>

                    <div className="flex items-center gap-3">
                        <button
                            type="button"
                            onClick={decreaseQty}
                            className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center"
                        >
                            -
                        </button>

                        <span className="min-w-6 text-center font-semibold">
                            {qty}
                        </span>

                        <button
                            type="button"
                            onClick={increaseQty}
                            className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center"
                        >
                            +
                        </button>
                    </div>
                </div>

                <div className="flex flex-col items-center text-gray-600">
                    <div className="border border-[#F1F2F9] p-3 rounded-[16px] mb-2">
                        <span className="text-sm font-semibold">
                            {slotImages.filter((img) => img?.id).length}/7
                        </span>
                    </div>
                    <span className="text-xs">الصور</span>
                </div>
            </div>

            <p className="text-xs text-gray-500 text-center -mt-2">
                اسحب الصورة وضعها فوق صورة أخرى لتبديل الترتيب
            </p>
        </div>
    );
}