"use client";

import {useState, useEffect, useRef, useMemo, useCallback} from "react";
import {useRouter, useSearchParams, usePathname} from "next/navigation";
import {useCrop} from "@/context/CropContext";
import api from "@/api/axios";
import {toast} from "sonner";
import AppLoader from "@/components/Loading";
import {setCountryCode, getCountryCode} from '@/utils/countryCode';
import {useLanguage} from "@/context/LanguageContext";
import {
    UploadedImage,
} from "@/features/products/types/product";
import {effects} from "@/features/products/constants/effects";
import {
    PRODUCT_PREVIEW_SIZES,
    getProductVariationPreviewSize,
} from "@/features/products/constants/previewSizes";
import ProductHeader from "@/features/products/components/ProductHeader";
import ProductImagesSummary from "@/features/products/components/ProductImagesSummary";
import ProductStartButton from "@/features/products/components/ProductStartButton";
import CropPreparingOverlay from "@/features/products/components/CropPreparingOverlay";
import ProductCropModal from "@/features/products/components/ProductCropModal";
/*import ProductYearlyCalendarModal from "@/features/products/components/ProductYearlyCalendarModal";*/
import {
    isDarkBackground,
    getImageKey,
} from "@/features/products/utils/imageHelpers";

import {useImageMeta} from "@/features/products/hooks/useImageMeta";
import {useProductImageStyles} from "@/features/products/hooks/useProductImageStyles";
import ProductUploadModal from "@/features/products/components/ProductUploadModal";
import ProductAddToCartBar from "@/features/products/components/ProductAddToCartBar";
import ProductBottomControls from "@/features/products/components/ProductBottomControls";
import ProductPricingModal from "@/features/products/components/ProductPricingModal";
import ProductDesignArea from "@/features/products/components/ProductDesignArea";
import {useProductData} from "@/features/products/hooks/useProductData";
import {useProductImages} from "@/features/products/hooks/useProductImages";
import {useProductImageQuantities} from "@/features/products/hooks/useProductImageQuantities";
import {useProductUploadAccess} from "@/features/products/hooks/useProductUploadAccess";
import {useProductCrop} from "@/features/products/hooks/useProductCrop";
import {useProductImageDelete} from "@/features/products/hooks/useProductImageDelete";
import {useProductImageTexts} from "@/features/products/hooks/useProductImageTexts";

import {getGuestUuid} from "@/utils/guestUuid";

export default function ProductPage({
                                        params,
                                    }: {
    params: { id: string; slug: string };
}) {
    /*const [showYearlyCalendarModal, setShowYearlyCalendarModal] = useState(false);*/

    const [yearlyQty, setYearlyQty] = useState(1);

    const increaseYearlyQty = () => {
        setYearlyQty((prev) => prev + 1);
    };

    const decreaseYearlyQty = () => {
        setYearlyQty((prev) => (prev > 1 ? prev - 1 : 1));
    };

    const [showUpload, setShowUpload] = useState(false);
    const [captions, setCaptions] = useState<string[]>([]);
    const [showEffectsBar, setShowEffectsBar] = useState(false);
    const [showColorBar, setShowColorBar] = useState(false);
    const [selectedEffect, setSelectedEffect] = useState<string>("normal");
    const [backgroundColor, setBackgroundColor] = useState<string>("#FFFFFF");
    const [uploading, setUploading] = useState(false);
    const [addingToCart, setAddingToCart] = useState(false);
    const [showPricingModal, setShowPricingModal] = useState(false);
    const [selectedPriceItem, setSelectedPriceItem] = useState<any>(null);
    const [isNewCalendar, setIsNewCalendar] = useState(false);
    const {
        imageMeta,
        setImageMeta,
        registerImageMeta,
        registerOriginalImageMeta,
    } = useImageMeta();
    const {
        isCropOpen,
        setIsCropOpen,

        cropFile,
        setCropFile,

        cropPreparing,

        cropImageId,
        setCropImageId,

        setCropSourceMeta,

        openCropModal,
        closeCropModal,
    } = useProductCrop();

    const uploadQueueRef = useRef<Set<string>>(new Set());
    const retryAttemptsRef = useRef<{ [key: string]: number }>({});

    const router = useRouter();
    const searchParams = useSearchParams();
    const pathname = usePathname();
    const editCartGroupId = searchParams.get("edit_cart_group");
    const isEditMode = Boolean(editCartGroupId);
    const [editLoading, setEditLoading] = useState(false);
    const {setImageUrl} = useCrop();

    /*const isCalendar = Number(params.id) === 5 || Number(params.id) === 6;*/
    const isCalendar = [1, 5, 6].includes(Number(params.id));
    const isRegularPhotos = Number(params.id) === 3;

    const {lang} = useLanguage();
    const {
        product,
        loading,
        selectedVariation,
        setSelectedVariation,

        colorsArray,

        frames,


        selectedFrame,
        setSelectedFrame,

    } = useProductData({
        productId: params.id,
        lang,
    });

    const {
        isLoggedIn,
        openLoginPopup,
        handleOpenUpload,
    } = useProductUploadAccess({
        product,
        setShowUpload,
        setShowPricingModal,
    });

    const {
        uploadedImages,
        setUploadedImages,

        fetchedImages,
        setFetchedImages,

        images,
        visibleImages,
        visibleImageMetaKey,

        fetchImages,
        clearImages,
    } = useProductImages({
        productId: params.id,
        product,
        selectedVariation,
        isNewCalendar,
        isEditMode,
    });

    const loadedEditGroupRef = useRef<string | null>(null);

    useEffect(() => {
        if (!editCartGroupId) return;
        if (!product) return;

        const editKey = `${params.id}-${editCartGroupId}`;

        if (loadedEditGroupRef.current === editKey) {
            return;
        }

        loadedEditGroupRef.current = editKey;

        const loadCartGroupForEdit = async () => {
            try {
                setEditLoading(true);

                const guestUuid = getGuestUuid();

                const response = await api.get(
                    `cart/groups/${editCartGroupId}/edit?country_code=${getCountryCode()}`,
                    {
                        headers: {
                            "X-Guest-Uuid": guestUuid,
                        },
                    }
                );

                if (!response.data.success) {
                    toast.error(response.data.message || "تعذر تحميل المنتج للتعديل");
                    return;
                }

                const data = response.data.data;
                const cartGroup = data.cart_group;
                const items = data.items || [];

                if (!cartGroup || Number(cartGroup.product_id) !== Number(params.id)) {
                    toast.error("بيانات التعديل لا تطابق المنتج الحالي");
                    return;
                }

                const normalizedImages = items.map((item: any, index: number) => {
                    const slotIndex = getCalendarSlotIndex(item, index);
                    const editCropImage =
                        item.selected_crop_image ||
                        item.cropped_image ||
                        item.crop_image ||
                        null;

                    return {
                        id: item.image_id,
                        image: item.image,
                        cropped_image: editCropImage,
                        selected_crop_image: editCropImage,

                        product_id: item.product_id,
                        variation_id: item.variation_id,
                        frame_id: item.frame_id,
                        color_code_id: item.color_code_id,
                        effect: item.effect,

                        qty: item.qty || 1,
                        sort_order:
                            [1, 5, 6].includes(Number(params.id)) && typeof slotIndex === "number"
                                ? slotIndex + 1
                                : item.sort_order ?? index + 1,

                        caption_text: item.caption_text ?? item.text ?? "",
                        calendar_slot: item.calendar_slot,
                        calendar_type: item.calendar_type,

                        uploadStatus: "success",
                        isFromCartEdit: true,

                        monthIndex: slotIndex,
                    };
                });

                if ([1, 5, 6].includes(Number(params.id))) {
                    setFetchedImages(normalizedImages);
                    setIsNewCalendar(false);
                } else {
                    setUploadedImages(normalizedImages);
                }

                const nextTexts: { [key: string]: string } = {};
                const nextQuantities: { [key: string]: number } = {};

                normalizedImages.forEach((img: any) => {
                    nextTexts[String(img.id)] = img.caption_text || "";
                    nextQuantities[String(img.id)] = Number(img.qty || 1);
                });

                setImageTexts(nextTexts);
                setImageQuantities(nextQuantities);

                const editFrameId =
                    cartGroup.frame_id ??
                    items.find((item: any) => item.frame_id)?.frame_id ??
                    null;

                if (editFrameId) {
                    setSelectedFrame(Number(editFrameId));
                }

                const editVariationId =
                    cartGroup.variation_id ??
                    items.find((item: any) => item.variation_id)?.variation_id ??
                    null;

                if (editVariationId && product?.variations?.length) {
                    const foundVariation = product.variations.find(
                        (variation: any) =>
                            Number(variation.id) === Number(editVariationId)
                    );

                    if (foundVariation) {
                        setSelectedVariation(foundVariation);
                    }
                }

                if (cartGroup.qty) {
                    setYearlyQty(Number(cartGroup.qty || 1));
                }
            } catch (error) {
                console.error("Error loading cart group for edit:", error);
                toast.error("حدث خطأ أثناء تحميل بيانات التعديل");

                loadedEditGroupRef.current = null;
            } finally {
                setEditLoading(false);
            }
        };

        loadCartGroupForEdit();
    }, [
        editCartGroupId,
        params.id,
        product,
    ]);

    const {
        imageQuantities,
        setImageQuantities,

        increaseQuantity,
        decreaseQuantity,
        getImageQuantity,

        getDisplayedImages,
        getTotalPhotos,
        getTotalQuantity,

        clearImageQuantities,
        removeImageQuantities,
    } = useProductImageQuantities(visibleImages);

    const {
        imageTexts,
        setImageTexts,
        updateImageText,
        clearImageTexts,
        removeImageTexts,
    } = useProductImageTexts();

    const finishCartEditMode = useCallback(() => {
        setFetchedImages([]);
        setUploadedImages([]);
        setCaptions([]);
        setImageTexts({});
        setImageQuantities({});
        setCalendarUploadSlotIndex(null);

        loadedEditGroupRef.current = null;

        window.dispatchEvent(new Event("cart-updated"));
        window.dispatchEvent(new Event("open-cart"));

        router.replace(pathname, { scroll: false });
    }, [
        pathname,
        router,
        setFetchedImages,
        setUploadedImages,
        setImageTexts,
        setImageQuantities,
    ]);

    useEffect(() => {
        if (!isEditMode || !editCartGroupId) return;

        const handleCartGroupDeleted = (event: Event) => {
            const customEvent = event as CustomEvent<{ cart_group_id?: number | string }>;
            const deletedGroupId = customEvent.detail?.cart_group_id;

            if (!deletedGroupId) return;

            if (Number(deletedGroupId) === Number(editCartGroupId)) {
                toast.info("تم حذف هذا المنتج من السلة");

                finishCartEditMode();
            }
        };

        window.addEventListener("cart-group-deleted", handleCartGroupDeleted);

        return () => {
            window.removeEventListener("cart-group-deleted", handleCartGroupDeleted);
        };
    }, [isEditMode, editCartGroupId, finishCartEditMode]);

    const {
        handleDeleteImage,
        handleDeleteAllImages,
        handleNewCalenderImages,
    } = useProductImageDelete({
        productId: params.id,
        images,
        setUploadedImages,
        setFetchedImages,
        setCaptions,
        clearImageQuantities,
        clearImageTexts
    });


    const FALLBACK_ASPECT = 420 / 292;

    const previewAspect = useMemo(() => {
        if (isRegularPhotos && selectedVariation?.width && selectedVariation?.height) {
            const w = Number(selectedVariation.width);
            const h = Number(selectedVariation.height);
            if (w > 0 && h > 0) return w / h;
        }
        return FALLBACK_ASPECT;
    }, [isRegularPhotos, selectedVariation]);

    const {
        getImageContainerStyle,
        getCardWrapperStyle,
        getUploadingBoxStyle,
    } = useProductImageStyles({
        imageMeta,
        isRegularPhotos,
        previewAspect,
    });


    const getPreviewAspect = () => {
        if (Number(params.id) === 3 && selectedVariation?.width && selectedVariation?.height) {
            const w = Number(selectedVariation.width);
            const h = Number(selectedVariation.height);
            if (w > 0 && h > 0) return w / h;
        }
        return FALLBACK_ASPECT;
    };


    const getOrientedSize = (
        base: { width: number; height: number; padding?: number } | null,
        img: any,
        rotateByImage: boolean = true
    ) => {
        if (!base) return null;

        let width = base.width;
        let height = base.height;

        const meta = imageMeta[getImageKey(img)];

        if (rotateByImage && meta) {
            const imageIsPortrait = meta.height > meta.width;
            const sizeIsLandscape = width > height;

            if (imageIsPortrait && sizeIsLandscape) {
                [width, height] = [height, width];
            }

            const imageIsLandscape = meta.width >= meta.height;
            const sizeIsPortrait = height > width;

            if (imageIsLandscape && sizeIsPortrait) {
                [width, height] = [height, width];
            }
        }

        return {
            ...base,
            width,
            height,
        };
    };

    const [calendarUploadSlotIndex, setCalendarUploadSlotIndex] = useState<number | null>(null);
    useEffect(() => {
        visibleImages.forEach((img: any) => {
            registerOriginalImageMeta(img);
        });
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [visibleImageMetaKey, selectedVariation?.id]);

    useEffect(() => {
        const handleCropComplete = () => {
            if (isEditMode) return;
            fetchImages(selectedVariation?.id);
        };

        window.addEventListener("crop-completed", handleCropComplete);
        return () => window.removeEventListener("crop-completed", handleCropComplete);
    }, [fetchImages, selectedVariation?.id, isEditMode]);

    useEffect(() => {
        const urlParams = new URLSearchParams(window.location.search);
        const newCalendarParam = urlParams.get("new");

        if (newCalendarParam === "true") {
            setIsNewCalendar(true);
            clearImages();
        }
    }, [clearImages]);


    const isImgUploading = (img: any) =>
        img?.uploadStatus === "uploading" || img?.uploadStatus === "pending";

    const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const files = e.target.files;
        if (!files || !product) return;
        /*if (!isLoggedIn()) {
            e.currentTarget.value = "";
            setShowUpload(false);
            openLoginPopup();
            return;
        }*/

        const arr = Array.from(files);

        if (isCalendar) {
            const maxCalendarImages = Number(params.id) === 1 ? 7 : 12;
            const activeImages = images.filter(
                (img: any) => img.uploadStatus !== "failed"
            );

            const isReplacingCalendarSlot =
                isCalendar &&
                calendarUploadSlotIndex !== null &&
                activeImages.some((img: any) => {
                    const imgSlotIndex =
                        typeof img?.monthIndex === "number"
                            ? Number(img.monthIndex)
                            : img?.sort_order
                                ? Number(img.sort_order) - 1
                                : img?.calendar_slot
                                    ? Number(params.id) === 1
                                        ? YEARLY_SLOTS.indexOf(String(img.calendar_slot))
                                        : MONTHS.indexOf(String(img.calendar_slot))
                                    : -1;

                    return imgSlotIndex === calendarUploadSlotIndex;
                });

            const remainingSlots = isReplacingCalendarSlot
                ? arr.length
                : maxCalendarImages - activeImages.length;

            if (remainingSlots <= 0) {
                toast.error(
                    Number(params.id) === 1
                        ? "وصلت للحد المطلوب! لا يمكن إضافة أكثر من 7 صور"
                        : "وصلت للحد المطلوب! لا يمكن إضافة أكثر من 12 صورة"
                );
                e.currentTarget.value = "";
                return;
            }

            if (arr.length > remainingSlots) {
                toast.warning(`سيتم تحميل ${remainingSlots} صورة فقط. وصلت للحد المطلوب!`);
                arr.splice(remainingSlots);
            }
        }

        const startSlotIndex =
            isCalendar && calendarUploadSlotIndex !== null
                ? calendarUploadSlotIndex
                : null;

        const newTempImages: UploadedImage[] = arr.map((file, index) => {
            const tempId = `temp-${Date.now()}-${index}-${Math.random().toString(36).slice(2, 9)}`;

            const slotIndex =
                startSlotIndex !== null
                    ? startSlotIndex + index
                    : images.filter((img: any) => img.uploadStatus !== "failed").length + index;

            return {
                id: tempId,
                image: URL.createObjectURL(file),
                cropped_image: null,
                product_id: params.id,
                isTemp: true,
                file,
                uploadStatus: "pending",
                retryCount: 0,

                // مهم جداً
                monthIndex: slotIndex,
                sort_order: slotIndex + 1,
                calendar_slot:
                    Number(params.id) === 1
                        ? YEARLY_SLOTS[slotIndex] || String(slotIndex + 1)
                        : MONTHS[slotIndex] || String(slotIndex + 1),
                calendar_type:
                    Number(params.id) === 1
                        ? "yearly"
                        : Number(params.id) === 5
                            ? "monthly"
                            : Number(params.id) === 6
                                ? "desk"
                                : undefined,
            };
        });

        if (isCalendar) {
            setFetchedImages((prev) => {
                const next = [...prev];

                newTempImages.forEach((tempImg: any) => {
                    const slotIndex = Number(tempImg.monthIndex);

                    const maxSlots = Number(params.id) === 1 ? 7 : 12;

                    if (Number.isInteger(slotIndex) && slotIndex >= 0 && slotIndex < maxSlots) {
                        const existingIndex = next.findIndex(
                            (img: any) =>
                                Number(img.monthIndex) === slotIndex ||
                                Number(img.sort_order) === slotIndex + 1 ||
                                img.calendar_slot === tempImg.calendar_slot
                        );

                        if (existingIndex >= 0) {
                            next[existingIndex] = tempImg;
                        } else {
                            next.push(tempImg);
                        }
                    } else {
                        next.push(tempImg);
                    }
                });

                return next;
            });
        } else {
            setUploadedImages((prev) => [...prev, ...newTempImages]);
        }

        setCaptions((prev) => [...prev, ...Array(newTempImages.length).fill("")]);

        e.currentTarget.value = "";
        setShowUpload(false);

        processUploadQueue(newTempImages);
        setCalendarUploadSlotIndex(null);
    };

    const processUploadQueue = async (imagesToUpload: UploadedImage[]) => {
        for (const tempImage of imagesToUpload) {
            if (uploadQueueRef.current.has(tempImage.id.toString())) continue;
            uploadQueueRef.current.add(tempImage.id.toString());
            await uploadSingleImage(tempImage);
        }
    };

    const uploadSingleImage = async (
        tempImage: UploadedImage,
        retry = false
    ): Promise<boolean> => {
        try {
            if (!retry) {
                if (isCalendar) {
                    setFetchedImages((prev) =>
                        prev.map((img: any) =>
                            img.id === tempImage.id ? {...img, uploadStatus: "uploading"} : img
                        )
                    );
                } else {
                    setUploadedImages((prev) =>
                        prev.map((img) =>
                            img.id === tempImage.id ? {...img, uploadStatus: "uploading"} : img
                        )
                    );
                }
            }

            const guestUuid = getGuestUuid();
            const formData = new FormData();
            formData.append("image", tempImage.file!);
            formData.append("product_id", params.id);
            formData.append("guest_uuid", guestUuid);
            const defaultVariation =
                selectedVariation ||
                product?.variations?.find((v: any) => Number(v.sort_order) === 1) ||
                product?.variations?.[0] ||
                null;

            if (product?.has_variation) {
                if (!selectedVariation?.id) {
                    toast.error("يرجى اختيار القياس أولاً");
                    return false;
                }

                formData.append("variation_id", String(selectedVariation.id));
            }

            if (isCalendar) {
                const currentIndex =
                    typeof (tempImage as any).monthIndex === "number"
                        ? Number((tempImage as any).monthIndex)
                        : fetchedImages.findIndex((img: any) => img.id === tempImage.id);

                if (currentIndex !== -1) {
                    formData.append("month_index", currentIndex.toString());
                    formData.append("sort_order", (currentIndex + 1).toString());

                    if (Number(params.id) === 1) {
                        formData.append("calendar_type", "yearly");
                        formData.append(
                            "calendar_slot",
                            YEARLY_SLOTS[currentIndex] || String(currentIndex + 1)
                        );
                    }

                    if (Number(params.id) === 5) {
                        formData.append("calendar_type", "monthly");
                        formData.append(
                            "calendar_slot",
                            MONTHS[currentIndex] || String(currentIndex + 1)
                        );
                    }

                    if (Number(params.id) === 6) {
                        formData.append("calendar_type", "desk");
                        formData.append(
                            "calendar_slot",
                            MONTHS[currentIndex] || String(currentIndex + 1)
                        );
                    }
                }
            }

            const response = await api.post("account-images/upload", formData, {
                headers: {
                    "Content-Type": "multipart/form-data",
                    "X-Guest-Uuid": guestUuid,
                },
                timeout: 30000,
            });

            if (response.data.success) {

                const uploadedData = response.data.data || response.data;

                const rawSlotIndex = Number((tempImage as any).monthIndex);

                const slotIndex = Number.isInteger(rawSlotIndex)
                    ? rawSlotIndex
                    : Number(params.id) === 1
                        ? 0
                        : images.filter((img: any) => img.uploadStatus !== "failed").length;

                const serverImg = {
                    ...uploadedData,

                    id: uploadedData.id,
                    image: uploadedData.image || (tempImage as any).image,
                    cropped_image: uploadedData.cropped_image ?? null,
                    selected_crop_image: uploadedData.selected_crop_image ?? null,

                    uploadStatus: "success" as const,
                    is_added_to_cart: false,

                    // لا تأخذ sort_order من API هنا
                    monthIndex: slotIndex,
                    sort_order: slotIndex + 1,

                    calendar_slot:
                        Number(params.id) === 1
                            ? YEARLY_SLOTS[slotIndex] || String(slotIndex + 1)
                            : MONTHS[slotIndex] || String(slotIndex + 1),

                    calendar_type:
                        Number(params.id) === 1
                            ? "yearly"
                            : Number(params.id) === 5
                                ? "monthly"
                                : Number(params.id) === 6
                                    ? "desk"
                                    : undefined,
                };

                if (isCalendar) {
                    setFetchedImages((prev) => {
                        const next = [...prev];

                        const tempIndex = next.findIndex(
                            (img: any) => String(img.id) === String(tempImage.id)
                        );

                        if (tempIndex >= 0) {
                            next[tempIndex] = serverImg;
                            return next;
                        }

                        const sameSlotIndex = next.findIndex((img: any) => {
                            const imgSlotIndex =
                                typeof img?.monthIndex === "number"
                                    ? Number(img.monthIndex)
                                    : img?.calendar_slot
                                        ? Number(params.id) === 1
                                            ? YEARLY_SLOTS.indexOf(String(img.calendar_slot))
                                            : MONTHS.indexOf(String(img.calendar_slot))
                                        : img?.sort_order
                                            ? Number(img.sort_order) - 1
                                            : -1;

                            return imgSlotIndex === slotIndex;
                        });

                        if (sameSlotIndex >= 0) {
                            next[sameSlotIndex] = serverImg;
                        } else {
                            next.push(serverImg);
                        }

                        return next;
                    });
                } else {
                    setUploadedImages((prev) => {
                        const tempIndex = prev.findIndex(
                            (img: any) => String(img.id) === String(tempImage.id)
                        );

                        if (tempIndex >= 0) {
                            const next = [...prev];
                            next[tempIndex] = serverImg;
                            return next;
                        }

                        return [...prev, serverImg];
                    });
                }

                URL.revokeObjectURL(tempImage.image);
                uploadQueueRef.current.delete(tempImage.id.toString());
                delete retryAttemptsRef.current[tempImage.id.toString()];

                return true;
            }

            throw new Error("Upload failed");
        } catch (error: any) {
            console.error("Upload failed for:", tempImage.file?.name, error);

            const currentRetryCount = retryAttemptsRef.current[tempImage.id.toString()] || 0;

            if (currentRetryCount < 2) {
                retryAttemptsRef.current[tempImage.id.toString()] = currentRetryCount + 1;

                setTimeout(() => {
                    uploadSingleImage(tempImage, true);
                }, 2000 * (currentRetryCount + 1));

                return false;
            }

            if (isCalendar) {
                setFetchedImages((prev) =>
                    prev.map((img: any) =>
                        img.id === tempImage.id ? {...img, uploadStatus: "failed"} : img
                    )
                );
            } else {
                setUploadedImages((prev) =>
                    prev.map((img) =>
                        img.id === tempImage.id ? {...img, uploadStatus: "failed"} : img
                    )
                );
            }

            toast.error(`فشل في رفع الصورة: ${tempImage.file?.name}`);
            uploadQueueRef.current.delete(tempImage.id.toString());

            setTimeout(() => {
                if (isCalendar) {
                    setFetchedImages((prev) => prev.filter((img: any) => img.id !== tempImage.id));
                } else {
                    setUploadedImages((prev) => prev.filter((img) => img.id !== tempImage.id));
                }
            }, 3000);

            return false;
        }
    };


    const saveImageAttributes = async (imageId: number, frameId?: number | null) => {
        try {
            const effectMap: { [key: string]: string } = {
                normal: "none",
                bright: "brightness",
                dark: "darkness",
                dramatic: "contrast",
                silver: "grayscale",
            };

            const frameToSend = frameId ?? selectedFrame ?? null;

            await api.post("account-images/attributes/save", {
                image_id: imageId,
                color_code: backgroundColor,
                effect: effectMap[selectedEffect] || "none",
                frame_id: frameToSend,
            });
        } catch (error) {
            console.error("Error saving attributes:", error);
        }
    };


    const handleAddToCart = async () => {
        if (!isLoggedIn()) {
            openLoginPopup();
            return;
        }
        const validImages = getDisplayedImages().filter(
            (img) => img.uploadStatus === "success" || !img.uploadStatus
        );
        if (Number(params.id) === 1 && validImages.length !== 7) {
            toast.error("يجب اختيار 7 صور للرزنامة السنوية");
            return;
        }
        const totalValidImagesQuantity = validImages.reduce(
            (total, img) => total + getImageQuantity(img.id),
            0
        );

        if (Number(product?.id) === 2 && totalValidImagesQuantity < 6) {
            toast.error("يجب أن يكون مجموع الصور والنسخ 6 على الأقل");
            return;
        }
        if ([5, 6].includes(Number(params.id)) && validImages.length !== 12) {
            toast.error(
                Number(params.id) === 6
                    ? "يجب اختيار 12 صورة لتقويم المكتب"
                    : "يجب اختيار 12 صورة للرزنامة الشهرية"
            );
            return;
        }


        if (validImages.length === 0) {
            toast.info("يرجى تحميل صورة أولاً");
            return;
        }

        const pendingUploads = getDisplayedImages().filter(
            (img) => img.uploadStatus === "uploading" || img.uploadStatus === "pending"
        );

        if (pendingUploads.length > 0) {
            toast.warning("يرجى الانتظار حتى اكتمال تحميل جميع الصور");
            return;
        }

        if (Number(params.id) === 1) {
            await confirmYearlyCalendarDesign(validImages, yearlyQty);
            return;
        }


        if ([5, 6].includes(Number(params.id))) {
            await confirmMonthlyCalendarDesign(validImages, yearlyQty);
            return;
        }

        setAddingToCart(true);
        try {
            await Promise.all(validImages.map((img) => saveImageAttributes(Number(img.id))));

            const defaultVariation =
                selectedVariation ||
                product?.variations?.find((v: any) => Number(v.sort_order) === 1) ||
                product?.variations?.[0] ||
                null;

            const selectedVariationId = selectedVariation?.id ?? null;

            if (product?.has_variation && !selectedVariationId) {
                toast.error("يرجى اختيار القياس أولاً");
                return;
            }
            const items = validImages.map((img) => ({
                image_id: img.id,
                variation_id: selectedVariationId,
                qty: getImageQuantity(img.id),
                text: imageTexts[String(img.id)] ?? img?.caption_text ?? "",
            }));

            const guestUuid = getGuestUuid();

            const endpoint = isEditMode
                ? `cart/groups/${editCartGroupId}/update`
                : "cart/add";

            const response = await api.post(
                endpoint,
                {
                    product_id: Number(params.id),
                    country_code: getCountryCode(),
                    guest_uuid: guestUuid,
                    items,
                },
                {
                    headers: {
                        "X-Guest-Uuid": guestUuid,
                    },
                }
            );

            if (response.data.success) {
                const addedIds = new Set(validImages.map((img) => Number(img.id)));
                if (!isEditMode) {
                    setFetchedImages((prev) =>
                        prev.filter((img: any) => !addedIds.has(Number(img.id)))
                    );

                    setUploadedImages((prev) =>
                        prev.filter((img: any) => !addedIds.has(Number(img.id)))
                    );

                    removeImageQuantities(Array.from(addedIds));
                    removeImageTexts(Array.from(addedIds));
                }

                toast.success(
                    isEditMode
                        ? "تم حفظ التعديلات بنجاح"
                        : "تم إضافة المنتج إلى السلة بنجاح!"
                );
                if (isEditMode) {
                    finishCartEditMode();
                    return;
                }
                window.dispatchEvent(new Event("cart-updated"));
                window.dispatchEvent(new Event("open-cart"));
            } else {
                toast.error(response.data.message || "لم يتم حفظ التعديلات");

                if (isEditMode) {
                    finishCartEditMode();
                }
            }
        } catch (error) {
            console.error("Error adding to cart:", error);
            toast.error("حدث خطأ أثناء إضافة المنتج إلى السلة");
        } finally {
            setAddingToCart(false);
        }
    };

    const confirmYearlyCalendarDesign = async (orderedImages: any[], qty: number = 1) => {
        if (orderedImages.length !== 7) {
            toast.error("يجب اختيار 7 صور للرزنامة السنوية");
            return;
        }

        const slots = ["A", "B", "C", "D", "E", "F", "G"];

        setAddingToCart(true);

        try {
            await Promise.all(
                orderedImages.map((img) => saveImageAttributes(Number(img.id)))
            );

            const defaultVariation =
                selectedVariation ||
                product?.variations?.find((v: any) => Number(v.sort_order) === 1) ||
                product?.variations?.[0] ||
                null;

            const selectedVariationId = selectedVariation?.id ?? null;

            if (product?.has_variation && !selectedVariationId) {
                toast.error("يرجى اختيار القياس أولاً");
                return;
            }

            const items = orderedImages
                .slice()
                .sort((a, b) => Number(a.sort_order || 0) - Number(b.sort_order || 0))
                .map((img) => {
                    const slotIndex =
                        typeof img?.monthIndex === "number"
                            ? Number(img.monthIndex)
                            : img?.sort_order
                                ? Number(img.sort_order) - 1
                                : slots.indexOf(String(img.calendar_slot));

                    return {
                        image_id: img.id,
                        variation_id: selectedVariationId,
                        qty,
                        text: imageTexts[String(img.id)] ?? img?.caption_text ?? "",
                        sort_order: slotIndex + 1,
                        calendar_slot: slots[slotIndex] || img.calendar_slot || "A",
                        calendar_type: "yearly",
                    };
                });

            const guestUuid = getGuestUuid();

            const endpoint = isEditMode
                ? `cart/groups/${editCartGroupId}/update`
                : "cart/add";

            const response = await api.post(
                endpoint,
                {
                    product_id: Number(params.id),
                    country_code: getCountryCode(),
                    guest_uuid: guestUuid,
                    items,
                },
                {
                    headers: {
                        "X-Guest-Uuid": guestUuid,
                    },
                }
            );

            if (response.data.success) {
                const addedIds = new Set(orderedImages.map((img) => Number(img.id)));

                if (!isEditMode) {
                    setFetchedImages((prev) =>
                        prev.filter((img: any) => !addedIds.has(Number(img.id)))
                    );

                    setUploadedImages((prev) =>
                        prev.filter((img: any) => !addedIds.has(Number(img.id)))
                    );

                    removeImageQuantities(Array.from(addedIds));
                    removeImageTexts(Array.from(addedIds));
                }


                toast.success(
                    isEditMode
                        ? "تم حفظ تعديلات الرزنامة بنجاح"
                        : "تم إضافة الرزنامة إلى السلة بنجاح"
                );
                if (isEditMode) {
                    finishCartEditMode();
                    return;
                }

                window.dispatchEvent(new Event("cart-updated"));
                window.dispatchEvent(new Event("open-cart"));
            } else {
                toast.error(response.data.message || "لم يتم حفظ التعديلات");

                if (isEditMode) {
                    finishCartEditMode();
                }
            }
        } catch (error) {
            console.error("Error adding yearly calendar to cart:", error);
            toast.error("حدث خطأ أثناء إضافة الرزنامة إلى السلة");
        } finally {
            setAddingToCart(false);
        }
    };

    const confirmMonthlyCalendarDesign = async (orderedImages: any[], qty: number = 1) => {
        if (orderedImages.length !== 12) {
            toast.error("يجب اختيار 12 صورة للرزنامة الشهرية");
            return;
        }

        const months = [
            "January",
            "February",
            "March",
            "April",
            "May",
            "June",
            "July",
            "August",
            "September",
            "October",
            "November",
            "December",
        ];

        setAddingToCart(true);

        try {
            await Promise.all(
                orderedImages.map((img) => saveImageAttributes(Number(img.id)))
            );

            const selectedVariationId = selectedVariation?.id ?? null;

            if (product?.has_variation && !selectedVariationId) {
                toast.error("يرجى اختيار القياس أولاً");
                return;
            }

            const calendarType = Number(params.id) === 6 ? "desk" : "monthly";

            const items = orderedImages
                .slice()
                .sort((a, b) => Number(a.sort_order || 0) - Number(b.sort_order || 0))
                .map((img, index) => {
                    const slotIndex =
                        typeof img?.monthIndex === "number"
                            ? Number(img.monthIndex)
                            : img?.sort_order
                                ? Number(img.sort_order) - 1
                                : img?.calendar_slot
                                    ? months.indexOf(String(img.calendar_slot))
                                    : index;

                    const safeIndex =
                        slotIndex >= 0 && slotIndex < 12
                            ? slotIndex
                            : index;

                    return {
                        image_id: img.id,
                        variation_id: selectedVariationId,
                        qty,
                        text: imageTexts[String(img.id)] ?? img?.caption_text ?? "",
                        sort_order: safeIndex + 1,
                        calendar_slot: months[safeIndex],
                        calendar_type: calendarType,
                    };
                });

            const guestUuid = getGuestUuid();

            const endpoint = isEditMode
                ? `cart/groups/${editCartGroupId}/update`
                : "cart/add";

            const response = await api.post(
                endpoint,
                {
                    product_id: Number(params.id),
                    country_code: getCountryCode(),
                    guest_uuid: guestUuid,
                    items,
                },
                {
                    headers: {
                        "X-Guest-Uuid": guestUuid,
                    },
                }
            );

            if (response.data.success) {
                const addedIds = new Set(orderedImages.map((img) => Number(img.id)));

                if (!isEditMode) {
                    setFetchedImages((prev) =>
                        prev.filter((img: any) => !addedIds.has(Number(img.id)))
                    );

                    setUploadedImages((prev) =>
                        prev.filter((img: any) => !addedIds.has(Number(img.id)))
                    );

                    removeImageQuantities(Array.from(addedIds));
                    removeImageTexts(Array.from(addedIds));
                }

                toast.success(
                    isEditMode
                        ? "تم حفظ تعديلات الرزنامة بنجاح"
                        : "تم إضافة الرزنامة إلى السلة بنجاح"
                );
                if (isEditMode) {
                    finishCartEditMode();
                    return;
                }

                window.dispatchEvent(new Event("cart-updated"));
                window.dispatchEvent(new Event("open-cart"));
            } else {
                toast.error(response.data.message || "لم يتم إضافة الرزنامة إلى السلة");
            }
        } catch (error) {
            console.error("Error adding monthly calendar to cart:", error);
            toast.error("حدث خطأ أثناء إضافة الرزنامة الشهرية إلى السلة");
        } finally {
            setAddingToCart(false);
        }
    };


    const darkBg = isDarkBackground(backgroundColor);
    const cardBg = backgroundColor;
    const textColor = darkBg ? "#FFFFFF" : "#222222";


    if (loading || editLoading) return <AppLoader/>;

    if (!product) {
        return (
            <div className="flex justify-center items-center h-screen text-white">
                المنتج غير موجود
            </div>
        );
    }


    const hasPreviewText = () => {
        if (Number(params.id) === 4) {
            return true;
        }
        const fixedSize = getProductVariationPreviewSize(
            params.id,
            selectedVariation?.id
        );

        return fixedSize?.hasText === true;
    };

    const getFixedPreviewBoxStyle = (uploadedImage: any) => {
        if (Number(params.id) === 3) {
            return getImageContainerStyle(uploadedImage);
        }

        const variationSize = getProductVariationPreviewSize(
            params.id,
            selectedVariation?.id
        );

        const productSize = PRODUCT_PREVIEW_SIZES[Number(params.id)] ?? null;

        const baseSize = variationSize ?? productSize;

        const productId = Number(params.id);

        const shouldRotatePreviewBox =
            ![1, 8].includes(productId) &&
            !(
                productId === 4 &&
                baseSize?.hasText === true
            );

        const fixedSize = getOrientedSize(
            baseSize,
            uploadedImage,
            shouldRotatePreviewBox
        );

        if (fixedSize) {
            return {
                width: `${fixedSize.width}px`,
                height: hasPreviewText()
                    ? "auto"
                    : `${fixedSize.height}px`,
                minHeight: `${fixedSize.height}px`,
                padding: `${fixedSize.padding ?? 0}px`,
                overflow: "visible",
                boxSizing: "border-box" as const,
                flex: "0 0 auto",
                backgroundColor: "#fff",
                border: Number(params.id) === 1 ? "none" : undefined,
            };
        }

        return {
            width: "100%",
            aspectRatio: String(previewAspect),
            minHeight: "310px",
        };
    };

    const getSelectedBaseCropSize = () => {
        if (selectedVariation?.crop_width && selectedVariation?.crop_height) {
            return {
                width: Number(selectedVariation.crop_width),
                height: Number(selectedVariation.crop_height),
            };
        }

        if (product?.crop_width && product?.crop_height) {
            return {
                width: Number(product.crop_width),
                height: Number(product.crop_height),
            };
        }

        return null;
    };

    const shouldRotateCropByImage = () => {
        const productId = Number(params.id);

        // المنتج رقم 1 لا نريد له تدوير حسب اتجاه الصورة نهائياً
        if (productId === 1) {
            return false;
        }
        if ([4, 2, 7, 3].includes(Number(params.id))) {
            return true;
        }
        if (selectedVariation?.crop_rotate_by_image !== undefined) {
            return Boolean(selectedVariation.crop_rotate_by_image);
        }

        if (product?.crop_rotate_by_image !== undefined) {
            return Boolean(product.crop_rotate_by_image);
        }

        return false;
    };

    const cropTargetImage =
        fetchedImages.find((img: any) => Number(img.id) === Number(cropImageId)) ||
        uploadedImages.find((img: any) => Number(img.id) === Number(cropImageId)) ||
        null;

    const YEARLY_SLOT_SIZES: Record<
        string,
        { width: number; height: number }
        > = {
        A: { width: 531, height: 531 },
        B: { width: 531, height: 383 },
        C: { width: 531, height: 383 },
        D: { width: 531, height: 531 },
        E: { width: 531, height: 792 },
        F: { width: 531, height: 946 },
        G: { width: 531, height: 383 },
    };

    const selectedCropSize = (() => {
        if (Number(params.id) === 1 && cropTargetImage?.calendar_slot) {
            const slot = String(
                cropTargetImage.calendar_slot
            ).trim().toUpperCase();

            return YEARLY_SLOT_SIZES[slot] ?? null;
        }

        const base = getSelectedBaseCropSize();

        if (!base) return null;

        if (!cropTargetImage) return base;

        return getOrientedSize(
            base,
            cropTargetImage,
            shouldRotateCropByImage()
        );
    })();

    const MONTHS = [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December",
    ];

    const YEARLY_SLOTS = ["A", "B", "C", "D", "E", "F", "G"];

    const getCalendarSlotIndex = (item: any, index: number) => {
        const productId = Number(params.id);

        if (productId === 1) {
            const slot = String(item?.calendar_slot || "").trim();

            const slotIndex = YEARLY_SLOTS.indexOf(slot);

            if (slotIndex >= 0) {
                return slotIndex;
            }

            return Math.max(Number(item?.sort_order || index + 1) - 1, 0);
        }

        if (productId === 5 || productId === 6) {
            const slot = String(item?.calendar_slot || "").trim();

            const monthIndex = MONTHS.indexOf(slot);

            if (monthIndex >= 0) {
                return monthIndex;
            }

            return Math.max(Number(item?.sort_order || index + 1) - 1, 0);
        }

        return undefined;
    };

    const handleDeleteImageFromSlot = async (imgOrId: any) => {
        const imageId =
            typeof imgOrId === "object"
                ? Number(imgOrId?.id)
                : Number(imgOrId);

        if (!imageId) {
            console.error("Delete image failed: invalid image id", imgOrId);
            toast.error("تعذر حذف الصورة");
            return;
        }

        const img =
            typeof imgOrId === "object"
                ? imgOrId
                : [...fetchedImages, ...uploadedImages].find(
                    (item: any) => Number(item.id) === imageId
                );

        const slotIndex =
            typeof img?.monthIndex === "number"
                ? Number(img.monthIndex)
                : img?.sort_order
                    ? Number(img.sort_order) - 1
                    : img?.calendar_slot
                        ? Number(params.id) === 1
                            ? YEARLY_SLOTS.indexOf(String(img.calendar_slot))
                            : MONTHS.indexOf(String(img.calendar_slot))
                        : -1;

        await handleDeleteImage(imageId);

        if (isCalendar) {
            setFetchedImages((prev) =>
                prev.filter((item: any) => Number(item.id) !== imageId)
            );

            setUploadedImages((prev) =>
                prev.filter((item: any) => Number(item.id) !== imageId)
            );

            if (slotIndex >= 0) {
                setCalendarUploadSlotIndex(slotIndex);
            }

            removeImageQuantities([imageId]);
            removeImageTexts([imageId]);
        }
    };

    const htmlDir =
        typeof document !== "undefined"
            ? document.documentElement.dir || "auto"
            : "auto";


    return (
        <section
            className="relative text-gray-800 pt-[100px]  px-4 min-h-screen flex flex-col items-center justify-start bg-[#f4f4f4]">
            {uploading && <AppLoader/>}

            <CropPreparingOverlay show={cropPreparing}/>

            <ProductCropModal
                isOpen={isCropOpen}
                cropFile={cropFile}
                cropImageId={cropImageId}
                productId={params.id}
                selectedImage={cropTargetImage}
                selectedVariation={selectedVariation}
                selectedCropSize={selectedCropSize}
                isRegularPhotos={isRegularPhotos}
                previewAspect={previewAspect}
                setIsCropOpen={setIsCropOpen}
                setCropFile={setCropFile}
                setCropImageId={setCropImageId}
                setCropSourceMeta={setCropSourceMeta}
                onSaved={(data: any) => {
                    const serverImg = data?.data ?? data;
                    const id = Number(serverImg?.id);

                    if (!id) {
                        fetchImages(selectedVariation?.id);
                    } else {
                        setFetchedImages((prev) =>
                            prev.map((img: any) =>
                                Number(img.id) === id ? {...img, ...serverImg} : img
                            )
                        );

                        setUploadedImages((prev) =>
                            prev.map((img: any) =>
                                Number(img.id) === id ? {...img, ...serverImg} : img
                            )
                        );
                    }

                    closeCropModal();
                }}
            />

            <ProductHeader product={product}/>

            <ProductImagesSummary
                imagesLength={images.length}
                totalPhotos={getTotalPhotos()}
                totalQuantity={getTotalQuantity()}
                productId={params.id}
                selectedVariation={selectedVariation}
                handleDeleteAllImages={handleDeleteAllImages}
                handleNewCalenderImages={handleNewCalenderImages}
            />

            {![1, 6, 5].includes(Number(params.id)) && (
                <ProductStartButton
                    visibleImagesLength={visibleImages.length}
                    uploading={uploading}
                    onClick={handleOpenUpload}
                />
            )}



            <ProductDesignArea
                productId={params.id}
                product={product}
                isNewCalendar={isNewCalendar}
                fetchedImages={fetchedImages}
                setFetchedImages={setFetchedImages}
                selectedEffect={selectedEffect}
                selectedVariation={selectedVariation}
                backgroundColor={backgroundColor}
                effects={effects}
                isImgUploading={isImgUploading}
                handleDeleteImage={handleDeleteImageFromSlot}
                visibleImages={visibleImages}
                isRegularPhotos={isRegularPhotos}
                imageMeta={imageMeta}
                htmlDir={htmlDir}
                imageTexts={imageTexts}
                selectedFrame={selectedFrame}
                frames={frames}
                getCardWrapperStyle={getCardWrapperStyle}
                getFixedPreviewBoxStyle={getFixedPreviewBoxStyle}
                hasPreviewText={hasPreviewText}
                uploadSingleImage={uploadSingleImage}
                openCropModal={openCropModal}
                getImageQuantity={getImageQuantity}
                increaseQuantity={increaseQuantity}
                decreaseQuantity={decreaseQuantity}
                updateImageText={updateImageText}
                onOpenUpload={handleOpenUpload}
                yearlyQty={yearlyQty}
                increaseYearlyQty={increaseYearlyQty}
                decreaseYearlyQty={decreaseYearlyQty}
                calendarUploadSlotIndex={calendarUploadSlotIndex}
                setCalendarUploadSlotIndex={setCalendarUploadSlotIndex}
            />

            <ProductUploadModal
                show={showUpload}
                uploading={uploading}
                onClose={() => setShowUpload(false)}
                onImageUpload={handleImageUpload}
            />

            <ProductAddToCartBar
                show={
                    fetchedImages.length > 0 ||
                    uploadedImages.filter((img) => img.uploadStatus !== "failed").length > 0 ||
                    isNewCalendar
                }
                productId={params.id}
                totalPhotos={getTotalPhotos()}
                totalQuantity={getTotalQuantity()}
                addingToCart={addingToCart}
                onAddToCart={handleAddToCart}
                isEditMode={isEditMode}
            />

            {![1, 5, 6].includes(Number(params.id)) && (
                <ProductBottomControls
                    visibleImagesLength={visibleImages.length}
                    product={product}
                    productId={params.id}
                    frames={frames}
                    selectedFrame={selectedFrame}
                    setSelectedFrame={setSelectedFrame}
                    selectedVariation={selectedVariation}
                    setSelectedVariation={setSelectedVariation}
                    selectedPriceItem={selectedPriceItem}
                    setSelectedPriceItem={setSelectedPriceItem}
                    showEffectsBar={showEffectsBar}
                    setShowEffectsBar={setShowEffectsBar}
                    showColorBar={showColorBar}
                    setShowColorBar={setShowColorBar}
                    colorsArray={colorsArray}
                    backgroundColor={backgroundColor}
                    setBackgroundColor={setBackgroundColor}
                    selectedEffect={selectedEffect}
                    setSelectedEffect={setSelectedEffect}
                    fetchedImages={fetchedImages}
                    uploadedImages={uploadedImages}
                    handleOpenUpload={handleOpenUpload}
                    saveImageAttributes={saveImageAttributes}
                    getDisplayedImages={getDisplayedImages}
                    setShowPricingModal={setShowPricingModal}
                />
            )}

            <ProductPricingModal
                show={showPricingModal}
                product={product}
                selectedVariation={selectedVariation}
                selectedPriceItem={selectedPriceItem}
                setSelectedVariation={setSelectedVariation}
                setSelectedPriceItem={setSelectedPriceItem}
                onClose={() => setShowPricingModal(false)}
                onConfirm={() => {
                    setShowPricingModal(false);
                    setShowUpload(true);
                }}
            />
            {/*<ProductYearlyCalendarModal
                isOpen={showYearlyCalendarModal}
                images={visibleImages}
                addingToCart={addingToCart}
                onClose={() => setShowYearlyCalendarModal(false)}
                onConfirm={confirmYearlyCalendarDesign}
            />*/}
        </section>
    );
}