"use client";
import { useState, useEffect, useRef, useCallback } from "react";
import { Edit } from "lucide-react";
import api from "@/api/axios";
import { toast } from "sonner";
import CropImageModal from "@/components/CropImageModal";
import {useLanguage} from "@/context/LanguageContext";
import { getGuestUuid } from "@/utils/guestUuid";

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

type MonthItem = {
  id: string;
  monthIndex: number;
  image: string | null;
  cropped_image: string | null;
};

function buildMonthGrid(year: number, monthIndex: number) {
  const firstDay = new Date(year, monthIndex, 1).getDay();
  const daysCount = new Date(year, monthIndex + 1, 0).getDate();
  const cells: Array<number | null> = [];

  for (let i = 0; i < firstDay; i++) cells.push(null);
  for (let d = 1; d <= daysCount; d++) cells.push(d);
  while (cells.length < 42) cells.push(null);

  const weeks: (number | null)[][] = [];
  for (let w = 0; w < 6; w++) {
    weeks.push(cells.slice(w * 7, w * 7 + 7));
  }
  return weeks;
}

interface MonthlyCalendarProps {
  removeImage: (imageId: string) => void;
  monthImages: any[];
  setMonthImages: (images: any[]) => void;
  selectedEffect: string;
  selectedSize: any;
  backgroundColor: string;
  sizes: any[];
  id: string;
  effects: Record<string, string>;
  isNewCalendar?: boolean;
  isUploadingImage?: (img: any) => boolean;
}

export default function DesktopCalendar({
  removeImage,
  monthImages,
  setMonthImages,
  selectedEffect,
  selectedSize,
  backgroundColor,
  sizes,
  id,
  effects,
  isNewCalendar = false,
}: MonthlyCalendarProps) {
  const { lang, changeLang, t } = useLanguage();
  const [monthFiles, setMonthFiles] = useState<(File | null)[]>(
    new Array(12).fill(null)
  );
  const [internalMonthImages, setInternalMonthImages] = useState<(any | null)[]>(
    new Array(12).fill(null)
  );
  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
  const [draggedOverIndex, setDraggedOverIndex] = useState<number | null>(null);
  const [forceUpdate, setForceUpdate] = useState(0);
  const currentYear = new Date().getFullYear();
  const [isCropOpen, setIsCropOpen] = useState(false);
  const [cropFile, setCropFile] = useState<File | null>(null);
  const [cropPreparing, setCropPreparing] = useState(false);
  const [cropImageId, setCropImageId] = useState<number | string | null>(null);
  const [calendarQty, setCalendarQty] = useState(1);
  const [isAddingToCart, setIsAddingToCart] = useState(false);
  const internalMonthImagesRef = useRef<(any | null)[]>(internalMonthImages);
  const dragStartTimeRef = useRef<number>(0);
  const isDraggingRef = useRef<boolean>(false);
  const touchStartPosRef = useRef<{ x: number; y: number } | null>(null);
  const dragThreshold = 10; // الحد الأدنى لحركة السحب بالبكسل
  const getImgSrc = (img: any) => {
    return img?.cropped_image || img?.selected_crop_image || img?.image;
  };

  /*const bust = (url: string) => `${url}${url.includes("?") ? "&" : "?"}t=${Date.now()}`;*/
  const getImageUrl = (img: any) => {
    if (!img) return "";

    const url = getImgSrc(img);
    if (!url) return "";

    // للصور المحلية المؤقتة لا نضيف شيء
    if (url.startsWith("blob:")) {
      return url;
    }

    // قيمة ثابتة لا تتغير كل render
    const version = img.updated_at || img.updatedAt || img.id;

    return `${url}${url.includes("?") ? "&" : "?"}v=${encodeURIComponent(version)}`;
  };

  const urlToFile = async (url: string) => {
    const res = await fetch(url, { cache: "no-store" });
  const blob = await res.blob();
  const type = blob.type || "image/jpeg";
  const ext = type.includes("png") ? "png" : "jpg";
  return new File([blob], `image.${ext}`, { type });
};
const openCropModal = async (img: any) => {
  if (!img) return;

  // ما نقص صور temp
  if (!img.id || img.id.toString().startsWith("temp-")) {
    toast.info("يرجى الانتظار حتى يتم حفظ الصورة على السيرفر أولاً");
    return;
  }

  try {
    setCropPreparing(true);
    setCropImageId(img.id);

    const file = await urlToFile(img.image);
    setCropFile(file);
    setIsCropOpen(true);
  } catch (e) {
    console.error(e);
    toast.error("فشل تجهيز الصورة للقص");
  } finally {
    setCropPreparing(false);
  }
};
  // Sync with parent prop and maintain 12-element structure - FIXED
  useEffect(() => {
    console.log('Month images from parent:', monthImages);
    console.log('Is new calendar:', isNewCalendar);
    
    // إنشاء مصفوفة من 12 عنصراً فارغة
    const newArray = new Array(12).fill(null);
    
    // إذا كان تقويم جديد، نحافظ على المصفوفة فارغة
    if (isNewCalendar) {
      console.log('New calendar mode - keeping empty array');
      setInternalMonthImages(newArray);
      internalMonthImagesRef.current = newArray;
      //setForceUpdate(prev => prev + 1);
      return;
    }
    
    if (monthImages && monthImages.length > 0) {
      // فرز الصور حسب monthIndex أولاً
      const sortedImages = [...monthImages].sort((a, b) => {
        const indexA = a.monthIndex !== undefined ? a.monthIndex : 0;
        const indexB = b.monthIndex !== undefined ? b.monthIndex : 0;
        return indexA - indexB;
      });
      
      // وضع كل صورة في مكانها الصحيح
      sortedImages.forEach((item: any) => {
        if (item && item.id) {
          let index = item.monthIndex !== undefined ? item.monthIndex : -1;
          
          // إذا كان monthIndex غير صالح، ابحث عن مكان فارغ
          if (index < 0 || index >= 12 || newArray[index] !== null) {
            index = newArray.findIndex(slot => slot === null);
          }
          
          if (index >= 0 && index < 12) {
            newArray[index] = { 
              ...item, 
              monthIndex: index 
            };
          }
        }
      });
    }
    
    console.log('Processed array for calendar:', newArray);
    setInternalMonthImages(newArray);
    internalMonthImagesRef.current = newArray;
    //setForceUpdate(prev => prev + 1);
  }, [monthImages, isNewCalendar]);

  // Improved drag start handler with mouse events
  const handleMouseDown = (e: React.MouseEvent, index: number) => {
    const img = internalMonthImages[index];
    if (!img) return;

    // حفظ وقت بدء الضغط
    dragStartTimeRef.current = Date.now();
    touchStartPosRef.current = { x: e.clientX, y: e.clientY };
    isDraggingRef.current = false;
    
    // Set a timeout to start dragging if mouse moves
    const startDrag = () => {
      if (isDraggingRef.current) return;
      isDraggingRef.current = true;
      setDraggedIndex(index);
      
      // Set drag data
      if (e.target instanceof HTMLElement) {
        e.target.draggable = true;
        const dragEvent = new DragEvent('dragstart', {
          dataTransfer: new DataTransfer(),
          bubbles: true,
          cancelable: true
        });
        
        dragEvent.dataTransfer?.setData('text/plain', index.toString());
        e.target.dispatchEvent(dragEvent);
      }
    };

    // Start drag after a small delay or on mouse move
    const dragTimer = setTimeout(startDrag, 150);
    
    // Add mousemove listener to detect drag
    const onMouseMove = (moveEvent: MouseEvent) => {
      if (!touchStartPosRef.current) return;
      
      const deltaX = Math.abs(moveEvent.clientX - touchStartPosRef.current.x);
      const deltaY = Math.abs(moveEvent.clientY - touchStartPosRef.current.y);
      
      if (deltaX > dragThreshold || deltaY > dragThreshold) {
        clearTimeout(dragTimer);
        startDrag();
        window.removeEventListener('mousemove', onMouseMove);
      }
    };
    
    const onMouseUp = () => {
      clearTimeout(dragTimer);
      window.removeEventListener('mousemove', onMouseMove);
      window.removeEventListener('mouseup', onMouseUp);
      
      // If not dragging and enough time passed, treat as click
      if (!isDraggingRef.current && Date.now() - dragStartTimeRef.current < 200) {
        // Handle crop click
        handleCrop(img, index);
      }
      
      isDraggingRef.current = false;
      touchStartPosRef.current = null;
    };
    
    window.addEventListener('mousemove', onMouseMove);
    window.addEventListener('mouseup', onMouseUp);
  };

  // Improved touch handlers for mobile
  const handleTouchStart = (e: React.TouchEvent, index: number) => {
    const img = internalMonthImages[index];
    if (!img) return;
    
    const touch = e.touches[0];
    touchStartPosRef.current = { x: touch.clientX, y: touch.clientY };
    dragStartTimeRef.current = Date.now();
    isDraggingRef.current = false;
    setDraggedIndex(index);
    
    e.preventDefault();
  };

  const handleTouchMove = (e: React.TouchEvent, index: number) => {
    if (!touchStartPosRef.current || !isDraggingRef.current) return;
    
    const touch = e.touches[0];
    const deltaX = Math.abs(touch.clientX - touchStartPosRef.current.x);
    const deltaY = Math.abs(touch.clientY - touchStartPosRef.current.y);
    
    // Start dragging only after threshold
    if (!isDraggingRef.current && (deltaX > dragThreshold || deltaY > dragThreshold)) {
      isDraggingRef.current = true;
    }
    
    if (isDraggingRef.current) {
      const element = document.elementFromPoint(touch.clientX, touch.clientY);
      
      if (element) {
        const card = element.closest('[data-month-index]');
        if (card) {
          const newIndex = parseInt(card.getAttribute('data-month-index') || '-1');
          if (newIndex !== -1 && newIndex !== draggedIndex) {
            setDraggedOverIndex(newIndex);
          }
        }
      }
    }
  };

  const handleTouchEnd = (e: React.TouchEvent, index: number) => {
    if (touchStartPosRef.current && !isDraggingRef.current) {
      const touch = e.changedTouches[0];
      const deltaX = Math.abs(touch.clientX - touchStartPosRef.current.x);
      const deltaY = Math.abs(touch.clientY - touchStartPosRef.current.y);
      
      // If it was a tap (not drag), handle crop
      if (deltaX < dragThreshold && deltaY < dragThreshold && 
          Date.now() - dragStartTimeRef.current < 200) {
        const img = internalMonthImages[index];
        if (img) handleCrop(img, index);
      }
    }
    
    if (isDraggingRef.current && draggedIndex !== null && draggedOverIndex !== null) {
      performDragDrop(draggedIndex, draggedOverIndex);
    }
    
    setDraggedIndex(null);
    setDraggedOverIndex(null);
    isDraggingRef.current = false;
    touchStartPosRef.current = null;
  };

  // Drag and drop handlers - IMPROVED
  const handleDragStart = (e: React.DragEvent, index: number) => {
    const img = internalMonthImages[index];
    if (!img) {
      e.preventDefault();
      return;
    }
    
    console.log('Drag started from index:', index, 'Image:', img);
    setDraggedIndex(index);
    e.dataTransfer.effectAllowed = 'move';
    
    // استخدام نص عادي للتوافق
    e.dataTransfer.setData('text/plain', index.toString());
    
    // إضافة صورة مصغرة للسحب (اختياري ولكن يحسن التجربة)
    if (img.cropped_image || img.image) {
      const dragImage = document.createElement('div');
      dragImage.style.width = '100px';
      dragImage.style.height = '100px';
      dragImage.style.backgroundImage = `url(${getImgSrc(img)})`;
      dragImage.style.backgroundSize = 'cover';
      dragImage.style.position = 'absolute';
      dragImage.style.top = '-1000px';
      document.body.appendChild(dragImage);
      
      e.dataTransfer.setDragImage(dragImage, 50, 50);
      
      // تنظيف بعد السحب
      setTimeout(() => document.body.removeChild(dragImage), 0);
    }
  };

  const handleDragOver = (e: React.DragEvent, index: number) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
    
    if (draggedIndex !== null && draggedIndex !== index) {
      setDraggedOverIndex(index);
    }
  };

  const handleDragLeave = () => {
    setDraggedOverIndex(null);
  };

  const handleDrop = (e: React.DragEvent, targetIndex: number) => {
    e.preventDefault();
    setDraggedOverIndex(null);
    
    // استخدم text/plain للتوافق
    const sourceIndexStr = e.dataTransfer.getData('text/plain');
    if (!sourceIndexStr) return;
    
    const sourceIndex = parseInt(sourceIndexStr);
    
    if (isNaN(sourceIndex) || sourceIndex === targetIndex || !internalMonthImages[sourceIndex]) {
      return;
    }
    
    performDragDrop(sourceIndex, targetIndex);
  };

  // Helper function to perform the drag and drop operation
  const performDragDrop = (sourceIndex: number, targetIndex: number) => {
    console.log('Dropping from', sourceIndex, 'to', targetIndex);
    
    // إنشاء نسخة من المصفوفات
    const newImages = [...internalMonthImages];
    const newFiles = [...monthFiles];
    
    // تبديل المواقع
    [newImages[sourceIndex], newImages[targetIndex]] = [
      newImages[targetIndex], 
      newImages[sourceIndex]
    ];
    
    [newFiles[sourceIndex], newFiles[targetIndex]] = [
      newFiles[targetIndex], 
      newFiles[sourceIndex]
    ];
    
    // تحديث monthIndex لكل الصور
    const updatedImages = newImages.map((item, idx) => {
      if (item) {
        return { 
          ...item, 
          monthIndex: idx 
        };
      }
      return null;
    });
    
    console.log('Updated images after swap:', updatedImages);
    
    // تحديث الحالة المحلية
    setInternalMonthImages(updatedImages);
    internalMonthImagesRef.current = updatedImages;
    setMonthFiles(newFiles);
    //setForceUpdate(prev => prev + 1);
    
    // تحديث الأب مع البيانات المحدثة
    const filteredForParent = updatedImages
      .filter(item => item !== null)
      .map(item => ({
        id: item.id,
        image: item.image,
        cropped_image: item.cropped_image,
        monthIndex: item.monthIndex,
        product_id: item.product_id || id
      }));
    
    console.log('Sending to parent:', filteredForParent);
    setMonthImages(filteredForParent);
    
    // Send re-order data to server
    sendReOrderData(updatedImages);
    
    setDraggedIndex(null);
    
    // إظهار رسالة نجاح
    toast.success(`تم نقل الصورة من ${MONTHS[sourceIndex]} إلى ${MONTHS[targetIndex]}`);
  };

  const handleDragEnd = () => {
    setDraggedIndex(null);
    setDraggedOverIndex(null);
    isDraggingRef.current = false;
  };

  // Send re-order data to server
  const sendReOrderData = async (updatedImages: (any | null)[]) => {
    try {
      const guestUuid = getGuestUuid();

      const reOrderData = updatedImages
          .filter(
              (item) =>
                  item !== null &&
                  item.id &&
                  !item.id.toString().startsWith("temp-")
          )
          .map((item, index) => ({
            image_id: item.id,
            sort_order: index + 1,
          }));

      if (reOrderData.length > 0) {
        console.log("Sending re-order data:", {
          guest_uuid: guestUuid,
          images: reOrderData,
        });

        await api.post(
            "account-images/re-order",
            {
              guest_uuid: guestUuid,
              images: reOrderData,
            },
            {
              headers: {
                ...(guestUuid ? { "X-Guest-Uuid": guestUuid } : {}),
              },
            }
        );

        console.log("Re-order saved to server");
      }
    } catch (error) {
      console.error("Error saving re-order:", error);
      toast.error("فشل في حفظ الترتيب");
    }
  };

  // حساب عدد الصور الحالية
  const getCurrentImageCount = useCallback(() => {
    return internalMonthImages.filter(item => item !== null).length;
  }, [internalMonthImages]);

  // ✅ استبدال صورة لشهر محدد مع التحقق من الحد الأقصى
  const handleReplaceImage = async (index: number, file: File | null) => {
    if (!file) return;

    // التحقق من الحد الأقصى (12 صورة)
    const currentCount = getCurrentImageCount();
    const hasExistingImage = internalMonthImages[index] !== null;
    
    if (!hasExistingImage && currentCount >= 12) {
      toast.error("وصلت للحد المطلوب! لا يمكن إضافة أكثر من 12 صورة");
      return;
    }

    const url = URL.createObjectURL(file);
    const currentImages = [...internalMonthImages];
    const currentFiles = [...monthFiles];

    // إنشاء كائن الصورة المؤقت
    const tempId = `temp-${Date.now()}-${index}`;
    const newImage = {
      id: tempId,
      image: url,
      cropped_image: null,
      monthIndex: index,
      product_id: id.toString(),
      sort_order: index + 1,
      isTemp: true
    };

    currentImages[index] = newImage;
    currentFiles[index] = file;

    setInternalMonthImages(currentImages);
    setMonthFiles(currentFiles);
    internalMonthImagesRef.current = currentImages;
    //setForceUpdate(prev => prev + 1);

    const filteredForParent = currentImages
      .filter(item => item !== null)
      .map(item => ({ ...item }));
    setMonthImages(filteredForParent);

    // رفع للسيرفر
    const formData = new FormData();
    formData.append("image", file);
    formData.append("product_id", id.toString());
    formData.append("sort_order", (index + 1).toString());
    formData.append("month_index", index.toString());

// منتج رقم 6 - رزنامة سطح مكتب
    formData.append("calendar_slot", MONTHS[index]);
    formData.append("calendar_type", "desk");
    const guestUuid = getGuestUuid();

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

      if (response.data?.success) {
        const serverImg = response.data.data;

        const serverImage = {
          ...serverImg,
          monthIndex: index,
          uploadStatus: "done",
        };

        const serverImageUrl = getImageUrl(serverImage);

        try {
          await preloadImage(serverImageUrl);
        } catch (e) {
          console.warn("Server image preload failed:", e);
        }

        const updatedImages = [...internalMonthImagesRef.current];

        updatedImages[index] = serverImage;

        setInternalMonthImages(updatedImages);
        internalMonthImagesRef.current = updatedImages;

        const updatedForParent = updatedImages
            .filter((item) => item !== null)
            .map((item: any) => ({ ...item }));

        setMonthImages(updatedForParent);

        toast.success("تم رفع الصورة بنجاح");
      }
    } catch (err: any) {
      console.error("Upload failed:", err);
      toast.error("فشل في رفع الصورة");
    }
  };

  // ✅ دالة لحذف الصورة من السيرفر ومحلياً
  const handleDeleteImage = async (index: number) => {
    const imgToDelete = internalMonthImages[index];
    
    if (!imgToDelete) return;
    // ✅ Guest UUID للزائر
    const guestUuid = getGuestUuid();
    // إذا كانت الصورة مرفوعة على السيرفر (ليست مؤقتة)، نحذفها من السيرفر
    if (imgToDelete.id && !imgToDelete.id.toString().startsWith('temp-')) {
      try {
        // 🔥 حذف الصورة من السيرفر
        await api.post("account-images/delete", {
          product_id: id,
          images_ids: [imgToDelete.id],
          guest_uuid: guestUuid, // ✅ إرسال UUID مع طلب الحذف
        });
        console.log('Image deleted from server:', imgToDelete.id);
      } catch (error) {
        console.error("Failed to delete image from server:", error);
        toast.error("فشل في حذف الصورة من السيرفر");
        return; // لا نحذف محلياً إذا فشل الحذف من السيرفر
      }
    }
    
    // حذف الصورة محلياً
    const newImgs = [...internalMonthImages];
    const newFiles = [...monthFiles];
    
    newImgs[index] = null;
    newFiles[index] = null;
    
    console.log('Deleting image at index:', index, 'Image:', imgToDelete);
    
    setInternalMonthImages(newImgs);
    setMonthFiles(newFiles);
    internalMonthImagesRef.current = newImgs;
    //setForceUpdate(prev => prev + 1);
    
    const filteredForParent = newImgs
      .map((item, idx) => item ? { ...item, monthIndex: idx } : null)
      .filter(item => item !== null);
    
    setMonthImages(filteredForParent);
    
    // استدعاء الدالة الأصلية للتحديث في الأب
    /*if (imgToDelete.id && !imgToDelete.id.toString().startsWith('temp-') && removeImage) {
      removeImage(imgToDelete.id);
    }*/
    
    toast.success("تم حذف الصورة بنجاح");
  };

  // ✅ دالة للذهاب إلى صفحة القص
  const handleCrop = (img: any, index: number) => {
    if (!img) return;
    openCropModal(img);  
  };

  const handleAddToCart = async () => {
    const uploadedImages = internalMonthImages.filter((item) => item !== null);

    if (uploadedImages.length !== 12) {
      toast.error("يجب إضافة 12 صورة قبل الإضافة للسلة");
      return;
    }

    const hasTempImages = internalMonthImages.some(
        (img) => img && (!img.id || img.id.toString().startsWith("temp-"))
    );

    if (hasTempImages) {
      toast.info("يرجى الانتظار حتى يتم حفظ جميع الصور على السيرفر");
      return;
    }

    try {
      setIsAddingToCart(true);

      const items = internalMonthImages
          .map((img: any, index) => {
            if (!img) return null;

            return {
              image_id: img.id,
              qty: calendarQty,
              calendar_slot: MONTHS[index],
              calendar_type: "desk",
            };
          })
          .filter(Boolean);

      await api.post("cart/add", {
        product_id: Number(id), // هنا سيكون 6
        items,
      });

      toast.success("تمت إضافة رزنامة سطح المكتب إلى السلة");
    } catch (error: any) {
      console.error("Add to cart failed:", error);

      const message =
          error?.response?.data?.message ||
          error?.response?.data?.errors?.cart?.[0] ||
          "فشل إضافة رزنامة سطح المكتب إلى السلة";

      toast.error(message);
    } finally {
      setIsAddingToCart(false);
    }
  };

  // Month card component مع دعم اللمس
  const MonthCard = ({ month, index, img }: any) => {
    const weeks = buildMonthGrid(currentYear, index);
    const isDraggedOver = draggedOverIndex === index;
    const isBeingDragged = draggedIndex === index;
    //const imageUrl = img ? bust(getImgSrc(img)) : "";
    const imageUrl = getImageUrl(img);
    return (
      <div
        data-month-index={index}
        className={`relative bg-white shadow-sm p-0 flex transition-all overflow-hidden w-full md:w-[360px] lg:w-[360px] ${
          isDraggedOver ? 'ring-2 ring-blue-400 ring-opacity-50 scale-105' : ''
        } ${
          isBeingDragged ? 'opacity-50 scale-95' : ''
        }`}
        style={{
          backgroundColor,
          color: "#222",
          flexDirection: 'row-reverse', // Month on right, photo on left
          transition: 'transform 0.2s, opacity 0.2s'
        }}
        onDragOver={(e) => handleDragOver(e, index)}
        onDragLeave={handleDragLeave}
        onDrop={(e) => handleDrop(e, index)}
      >
         {/* Photo on the left */}
        <div className="flex-1 relative">
          {/* زر الحذف */}
          {img && (
              <button
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    handleDeleteImage(index);
                  }}
                  className="absolute top-2 left-2 z-20 w-8 h-8 bg-white/90 hover:bg-white rounded-full flex items-center justify-center text-gray-600 hover:text-red-500 transition-colors shadow-lg hover:shadow-xl"
                  aria-label="Delete image"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
          )}

          <div className="w-[160px] h-[225px] bg-gray-200 overflow-hidden relative p-0 border-0">
            {img ? (
                <div
                    className="w-full h-full relative"
                    draggable="true"
                    onMouseDown={(e) => handleMouseDown(e, index)}
                    onDragStart={(e) => handleDragStart(e, index)}
                    onDragEnd={handleDragEnd}
                    onTouchStart={(e) => handleTouchStart(e, index)}
                    onTouchMove={(e) => handleTouchMove(e, index)}
                    onTouchEnd={(e) => handleTouchEnd(e, index)}
                    style={{ cursor: "grab" }}
                >
                  <img
                      src={imageUrl}
                      alt={`${month}-${currentYear}`}
                      className="w-full h-full object-cover select-none"
                      style={{
                        filter: effects[selectedEffect as keyof typeof effects],
                        pointerEvents: "none",
                        userSelect: "none",
                      }}
                  />

                  {/* Drag indicator */}
                  <div className="absolute top-2 right-2 bg-black/50 text-white text-xs px-2 py-1 rounded select-none">
                    اسحبني 🖱️
                  </div>

                  {/* زر التعديل */}
                  <div className="absolute bottom-2 left-2 flex gap-2">
                    <button
                        onClick={(e) => {
                          e.preventDefault();
                          e.stopPropagation();
                          handleCrop(img, index);
                        }}
                        className="p-1 bg-white/80 hover:bg-white rounded text-gray-800 hover:text-blue-500 transition-colors shadow-sm select-none"
                        aria-label="Edit image"
                    >
                      <Edit size={16} />
                    </button>
                  </div>
                </div>
            ) : (
                <div
                    className="w-full h-full flex items-center justify-center text-gray-400 cursor-pointer hover:bg-gray-300 transition-colors select-none"
                    onClick={() => {
                      const currentCount = getCurrentImageCount();

                      if (currentCount >= 12) {
                        toast.error("وصلت للحد المطلوب! لا يمكن إضافة أكثر من 12 صورة");
                        return;
                      }

                      const fileInput = document.createElement("input");
                      fileInput.type = "file";
                      fileInput.accept = "image/*";

                      fileInput.onchange = (e) => {
                        const file = (e.target as HTMLInputElement).files?.[0];
                        if (file) handleReplaceImage(index, file);
                      };

                      fileInput.click();
                    }}
                >
                  + إضافة صورة
                </div>
            )}
          </div>
        </div>
        {/* Month info on the right */}
        <div className="flex flex-col justify-center px-4">
          <div className="flex flex-col items-end">
            <div className="flex items-center">
              <h2 className="text-2xl font-semibold leading-none ml-1">
                {String(index + 1).padStart(2, "0")}
              </h2>
              <h3 className="text-lg font-medium mt-0.5">{month}</h3>
            </div>
            <div className="w-18 h-[2px] bg-gray-800 mx-auto -mt-2 mr-3 mb-3" />
          </div>
          
          {/* Calendar grid */}
          <div className="mt-2">
            <div className="grid grid-cols-7 gap-1 text-[9px] text-center text-gray-600 mb-1 font-semibold">
              {["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"].map((d) => (
                <div key={d} className={`uppercase ${d === "FRI" ? "text-[#3EB489]" : ""}`}>
                  {d}
                </div>
              ))}
            </div>
            <div className="grid grid-cols-7 gap-1 text-center text-xs">
              {weeks.flat().map((day, i) => {
                const col = i % 7;
                const isFri = col === 5;
                return (
                  <div
                    key={i}
                    className={`flex items-center justify-center text-xs ${
                      day ? (isFri ? "text-[#3EB489]" : "text-gray-800") : "text-gray-300"
                    }`}
                  >
                    {day ?? ""}
                  </div>
                );
              })}
            </div>
          </div>
          
          <div className="text-xs text-gray-500 mt-2 text-center">
            {currentYear}
          </div>
        </div>

      </div>
    );
  };

  const preloadImage = (url: string): Promise<void> => {
    return new Promise((resolve, reject) => {
      if (!url) {
        resolve();
        return;
      }

      const image = new window.Image();

      image.onload = () => resolve();
      image.onerror = () => reject();

      image.src = url;
    });
  };

  const createTempImage = (file: File, index: number) => {
    return {
      localId:
          typeof crypto !== "undefined" && crypto.randomUUID
              ? crypto.randomUUID()
              : `local-${Date.now()}-${index}-${Math.random()}`,
      id: `temp-${Date.now()}-${index}-${Math.random()}`,
      image: URL.createObjectURL(file),
      cropped_image: null,
      selected_crop_image: null,
      monthIndex: index,
      product_id: id.toString(),
      sort_order: index + 1,
      isTemp: true,
      uploadStatus: "uploading",
    };
  };
  const uploadImageForMonth = async (index: number, file: File, localId: string) => {
    const formData = new FormData();

    formData.append("image", file);
    formData.append("product_id", id.toString());
    formData.append("sort_order", (index + 1).toString());
    formData.append("month_index", index.toString());
    formData.append("calendar_slot", MONTHS[index]);
    formData.append("calendar_type", "desk");

    try {
      const response = await api.post("account-images/upload", formData, {
        headers: { "Content-Type": "multipart/form-data" },
      });

      if (!response.data?.success) {
        throw new Error("Upload failed");
      }

      const serverImg = response.data.data;

      const serverImage = {
        ...serverImg,
        localId,
        monthIndex: index,
        uploadStatus: "done",
      };

      const serverImageUrl = getImageUrl(serverImage);

      try {
        await preloadImage(serverImageUrl);
      } catch (e) {
        console.warn("Server image preload failed:", e);
      }

      const updatedImages = [...internalMonthImagesRef.current];

      updatedImages[index] = {
        ...serverImage,
        localId,
        monthIndex: index,
        uploadStatus: "done",
      };

      setInternalMonthImages(updatedImages);
      internalMonthImagesRef.current = updatedImages;

      const updatedForParent = updatedImages
          .filter((item) => item !== null)
          .map((item: any) => ({ ...item }));

      setMonthImages(updatedForParent);

      return true;
    } catch (err) {
      console.error("Upload failed:", err);

      const updatedImages = [...internalMonthImagesRef.current];

      if (updatedImages[index]?.localId === localId) {
        updatedImages[index] = {
          ...updatedImages[index],
          uploadStatus: "failed",
        };
      }

      setInternalMonthImages(updatedImages);
      internalMonthImagesRef.current = updatedImages;

      const updatedForParent = updatedImages
          .filter((item) => item !== null)
          .map((item: any) => ({ ...item }));

      setMonthImages(updatedForParent);

      return false;
    }
  };

  const handleBulkUpload = () => {
    const currentImages = internalMonthImagesRef.current;
    const currentCount = currentImages.filter(Boolean).length;

    if (currentCount >= 12) {
      toast.error("وصلت للحد المطلوب! لا يمكن إضافة أكثر من 12 صورة");
      return;
    }

    const fileInput = document.createElement("input");
    fileInput.type = "file";
    fileInput.accept = "image/*";
    fileInput.multiple = true;

    fileInput.onchange = async (e) => {
      const files = Array.from((e.target as HTMLInputElement).files || []);

      if (files.length === 0) return;

      const latestImages = [...internalMonthImagesRef.current];

      const emptyIndexes = latestImages
          .map((item, index) => (item ? null : index))
          .filter((index) => index !== null) as number[];

      const filesToUpload = files.slice(0, emptyIndexes.length);

      if (files.length > emptyIndexes.length) {
        toast.info(`تم اختيار ${files.length} صور، سيتم رفع ${emptyIndexes.length} فقط`);
      }

      const updatedImages = [...latestImages];
      const uploadJobs: Array<{
        index: number;
        file: File;
        localId: string;
      }> = [];

      filesToUpload.forEach((file, i) => {
        const index = emptyIndexes[i];
        const tempImage = createTempImage(file, index);

        updatedImages[index] = tempImage;

        uploadJobs.push({
          index,
          file,
          localId: tempImage.localId,
        });
      });

      // نعرض كل الصور فوراً في أماكنها الصحيحة
      setInternalMonthImages(updatedImages);
      internalMonthImagesRef.current = updatedImages;

      const updatedForParent = updatedImages
          .filter((item) => item !== null)
          .map((item: any) => ({ ...item }));

      setMonthImages(updatedForParent);

      // نرفع الصور بعد تثبيت أماكنها
      const results = await Promise.all(
          uploadJobs.map((job) =>
              uploadImageForMonth(job.index, job.file, job.localId)
          )
      );

      const successCount = results.filter(Boolean).length;

      if (successCount > 0) {
        toast.success(`تم رفع ${successCount} صورة بنجاح`);
      }

      if (successCount < uploadJobs.length) {
        toast.error(`فشل رفع ${uploadJobs.length - successCount} صورة`);
      }
    };

    fileInput.click();
  };
  return (
    <section>
      {cropPreparing && (
  <div className="fixed inset-0 z-[60] bg-black/50 flex items-center justify-center">
    <div className="bg-white rounded-xl p-4">
      <p className="text-sm">جاري تجهيز الصورة...</p>
    </div>
  </div>
)}

<CropImageModal
  isOpen={isCropOpen}
  file={cropFile}
  imageId={cropImageId}
  productId={id}
  onCancel={() => {
    setIsCropOpen(false);
    setCropFile(null);
    setCropImageId(null);
  }}
  onClose={() => {
    setIsCropOpen(false);
    setCropFile(null);
    setCropImageId(null);
  }}
  onSaved={(serverImg: any) => {
    const sid = Number(serverImg?.id);

    const updated = internalMonthImagesRef.current.map((it: any | null) => {
      if (!it) return null;
      if (Number(it.id) === sid) return { ...it, ...serverImg };
      return it;
    });

    setInternalMonthImages(updated);
    internalMonthImagesRef.current = updated;
    //setForceUpdate((p) => p + 1);

    const updatedForParent = updated
      .filter((x) => x !== null)
      .map((x: any) => ({ ...x }));
    setMonthImages(updatedForParent);

    setIsCropOpen(false);
    setCropFile(null);
    setCropImageId(null);

    toast.success("تم حفظ القص بنجاح");
  }}
/>
      {/* عداد الصور */}
      <div className="text-center mb-4 p-3 bg-green-50 rounded-lg max-w-2xl mx-auto">
        <p className="text-sm text-green-800">
          📸 عدد الصور: <strong>{getCurrentImageCount()}</strong> / 12
          {getCurrentImageCount() === 12 && (
            <span className="text-green-600 mr-2">✓ اكتمل التقويم!</span>
          )}
        </p>
      </div>

      {/* تعليمات السحب */}
      <div className="text-center mb-4 p-3 bg-blue-50 rounded-lg max-w-2xl mx-auto">
        <p className="text-sm text-blue-800">
          💡 <strong>تعليمات:</strong> اضغط مطولاً على الصورة واسحبها لوضعها في شهر مختلف
          <br />
          <span className="text-xs">(يعمل على الهواتف وأجهزة الكمبيوتر)</span>
        </p>
      </div>

      <div className="max-w-2xl mx-auto mb-4 flex justify-center">
        <button
            type="button"
            onClick={handleBulkUpload}
            disabled={getCurrentImageCount() >= 12}
            className="px-5 py-3 rounded-xl bg-pink-500 hover:bg-pink-600 disabled:bg-gray-300 disabled:cursor-not-allowed text-white font-bold transition-colors"
        >
          {t("upload_images")}
        </button>
      </div>
      {/* شبكة الأشهر */}
      <div className="max-w-7xl w-full mx-auto mb-8">
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-8">
          {MONTHS.map((month, index) => {
            const img = internalMonthImages[index];
            return (
                <MonthCard
                    key={`month-${index}`}
                    month={month}
                    index={index}
                    img={img}
                />
            );
          })}
        </div>
      </div>

      {/* الكمية والإضافة للسلة */}
      <div className="max-w-2xl mx-auto mb-16 bg-white border border-gray-200 rounded-2xl shadow-sm p-5">
        <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
          <div className="text-center sm:text-right">
            <p className="font-semibold text-gray-800">كمية رزنامة سطح المكتب</p>
            <p className="text-sm text-gray-500">
              السعر يحسب حسب عدد الرزنامات وليس عدد الصور
            </p>
          </div>

          <div className="flex items-center gap-3">
            <button
                type="button"
                onClick={() => setCalendarQty((q) => Math.max(1, q - 1))}
                disabled={calendarQty <= 1 || isAddingToCart}
                className="w-10 h-10 rounded-full bg-gray-100 hover:bg-gray-200 disabled:opacity-50 flex items-center justify-center text-xl font-bold"
            >
              -
            </button>

            <span className="min-w-12 text-center text-xl font-bold text-gray-900">
        {calendarQty}
      </span>

            <button
                type="button"
                onClick={() => setCalendarQty((q) => q + 1)}
                disabled={isAddingToCart}
                className="w-10 h-10 rounded-full bg-pink-500 hover:bg-pink-600 text-white flex items-center justify-center text-xl font-bold"
            >
              +
            </button>
          </div>
        </div>

        <button
            type="button"
            onClick={handleAddToCart}
            disabled={
                isAddingToCart ||
                getCurrentImageCount() !== 12 ||
                internalMonthImages.some(
                    (img) => img && (!img.id || img.id.toString().startsWith("temp-"))
                )
            }
            className="mt-5 w-full h-12 rounded-xl bg-pink-500 hover:bg-pink-600 disabled:bg-gray-300 disabled:cursor-not-allowed text-white font-bold transition-colors"
        >
          {isAddingToCart ? "جاري الإضافة..." : "إضافة للسلة"}
        </button>
      </div>
    </section>
  );
}