import React, { ChangeEvent, useEffect, useState } from "react";
import { useRouter } from "next/router";
import { RxCross2 } from "react-icons/rx";
import Image from "next/image";
import Cookies from "js-cookie";
import axios from "axios";
import ImageBox from "@/components/ImageBox";
import { ImArrowLeft2 } from "react-icons/im";
import toast, { Toaster } from "react-hot-toast";
import {
  Button,
  Checkbox,
  ConfigProvider,
  Input,
  Modal,
  Skeleton,
  Tooltip,
  message,
} from "antd";
import PopupDialog from "@/components/home/popup";
import AddColorModal from "@/components/helpers/AddColorModal";
import AddSizeModal from "@/components/helpers/AddSizeModal";
import { FaEdit } from "react-icons/fa";
import Loader from "@/components/helpers/Loader";
import { userActivity } from "@/components/commonFunctions/userActivity";
import { useSelector } from "react-redux";
import { RootState } from "@/Redux/store";
import Head from "next/head";

interface FormData {
  _id: string;
  brandId: string;
  productType: string;
  categoryId: string;
  subCategoryId: string;
  productTitle: string;
  productAge: string;
  productQuantity: string;
  productShortDescription: string;
  productDescription: string;
  productAvailability: string;
  productSellingPrice: string;
  productOriginalPrice: string;
  productDiscountPrice: string;
  productDiscountPercentage: string;
  productFeaturedImage: string;
  negotiable: boolean;
  variations: Array<{
    attributeId: string;
    variationId: string;
  }>;
  galleries: Array<{
    createdBy: {
      name: string;
      dateTime: string;
      _id: string;
    };
    created_at: string;
    deleted: string;
    imageUrl: string;
    productId: string;
    updated_at: string;
    _id: string;
  }>;
}

// Initialize formData with default values
const initialFormData: FormData = {
  _id: "",
  brandId: "",
  productType: "",
  categoryId: "",
  subCategoryId: "",
  productTitle: "",
  productAge: "1",
  productQuantity: "1",
  productShortDescription: "",
  productDescription: "",
  productSellingPrice: "",
  productOriginalPrice: "",
  productDiscountPrice: "",
  productAvailability: "",
  productDiscountPercentage: "",
  productFeaturedImage: "",
  variations: [],
  galleries: [],
  negotiable: false
};

const EditProduct = () => {
  const router = useRouter();
  const { id } = router.query;
  const [counterOfferData, setCounterOfferData] = useState<{ buyerId: string } | null>(null);

  const [data, setData] = React.useState<any>(null);
  const [loading, setLoading] = useState<boolean>(false);
  const [categoryImage, setCategoryImage] = useState<string>("");
  const [formData, setFormData] = useState<FormData>(initialFormData);
  const [brandData, setBrandData] = useState<any[]>([]);
  const [categoryData, setCategoryData] = useState<any[]>([]);
  const [subcategoryData, setSubCategoryData] = useState<any[]>([]);
  const [imageGallery, setImageGallery] = useState<any[]>([]);
  const [actionExecuted, setActionExecuted] = useState<boolean>(false);

  const [isColorPopupOpen, setIsColorPopupOpen] = useState(false);
  const [isSizePopupOpen, setIsSizePopupOpen] = useState(false);

  const [EditModalOpen, setEditModalOpen] = useState(false);
  const [editInputvalue, setEditInputValue] = useState("");

  const [imageUpdateLoader, setImageUpdateLoader] = useState(false);

  const [selectedImagesCount, setSelectedImagesCount] = useState(0);

  const [newImageUrls, setNewImageUrls] = useState<any>([]);

  const [deleteImageUrls, setDeleteImageUrls] = useState<any>([]);

  const [imagesToDelete, setImagesToDelete] = useState<any>([]);

  const [selectedItem, setSelectedItem] = useState<any>(null);

  const [variation, setVariations] = useState<any>([]);

  const _loggedIn_user = useSelector((state: RootState) => state.user.user);

  // const [subCategoryDataforType,setSubCategoryDataforType] = useState<any>(null)

  useEffect(() => {
    setLoading(true);
    if (id) {
      const getSingleProductData = async () => {
        try {
          // const authToken = Cookies.get("jazz_token");
          // const axiosInstance = axios.create({
          //   baseURL: "https://api.jazzagain.com/public/index.php",
          //   headers: {
          //     authorization: `Bearer ${authToken}`,
          //   },
          // });
          const response = await axios.get(
            `https://api.jazzagain.com/public/index.php/api/getSingleProduct/${id}`
          );
          // const presentSubCat = await axiosInstance.get(
          //   `https://api.jazzagain.com/public/index.php/api/user/subCategory/${response.data.product.subCategoryId}/edit`
          // );
          // console.log("presentSubCat",presentSubCat.data.subCategory)
          // setSubCategoryDataforType(presentSubCat.data.subCategory)
          const getCats = await axios.get(
            "https://api.jazzagain.com/public/index.php/api/getCategories"
          );
          const getbrands = await axios.get(
            "https://api.jazzagain.com/public/index.php/api/getBrands"
          );
          const subCategories = await axios.get(
            `https://api.jazzagain.com/public/index.php/api/getSubCategories/${response.data.product.categoryId}`
          );
          setSubCategoryData(subCategories.data.subCategories);
          setCategoryData(getCats.data.categories);
          setBrandData(getbrands.data.brands);
          setData(response.data.product);
          setFormData(response.data.product);
          setVariations(response.data.product.variations);
          setImageGallery(response.data.product.galleries);
          console.log("Response Edit :", response.data.product);
          setLoading(false);
        } catch (error) {
          toast.error("something went wrong.");
          console.error("Error:", error);
        }
      };
      getSingleProductData();
    }

    return () => { };
  }, [id, actionExecuted]);

  useEffect(() => {
    if (formData?.categoryId) {
      const subCategories = async () => {
        const res = await axios.get(
          `https://api.jazzagain.com/public/index.php/api/getSubCategories/${formData.categoryId}`
        );
        setSubCategoryData(res.data.subCategories);
      };
      subCategories();
    }
  }, [formData?.categoryId]);

  // const handleImageUpload = (id: number, imageUrl: string) => {
  //   setImageUpdateLoader(true)
  //   console.log("IMAGE UPLOAD RES :", id, imageUrl);
  //   setNewImageUrls(prevUrls => [...prevUrls, imageUrl]);
  //   const authToken = Cookies.get("jazz_token");

  //   const axiosInstance = axios.create({
  //     baseURL: "https://api.jazzagain.com/public/index.php",
  //     headers: {
  //       authorization: `Bearer ${authToken}`,
  //     },
  //   });
  //   let data = {
  //     productId: formData?._id,
  //     imageUrl: imageUrl,
  //   };

  //   console.log(data);

  //   axiosInstance
  //     .post(`/api/user/productGallery`, data)
  //     .then((res) => {
  //       console.log(res)
  //       message.success("Uploaded !")
  //       setActionExecuted(!actionExecuted)
  //       setImageUpdateLoader(false)
  //     });
  // };

  const handleImageUpload = async (id: any, imageUrl: any) => {
    console.log("IMAGE UPLOAD RES :", id, imageUrl);

    setNewImageUrls((prevUrls: any) => [...prevUrls, imageUrl]);

    if (id === 1) {
      try {
        const authToken = Cookies.get("jazz_token");
        const axiosInstance = axios.create({
          baseURL: "https://api.jazzagain.com/public/index.php",
          headers: {
            authorization: `Bearer ${authToken}`,
          },
        });

        // Update the featured image
        await axiosInstance.put(`/api/user/products/${formData._id}`, {
          productFeaturedImage: imageUrl
        });

        // Update local state
        setFormData(prev => ({
          ...prev,
          productFeaturedImage: imageUrl
        }));

        console.log("Featured image updated successfully");
      } catch (error) {
        console.error("Error updating featured image:", error);
        toast.error("Failed to update featured image");
      }
    }
  };

  const showModal = () => {
    setEditModalOpen(true);
  };

  const handleOk = () => {
    setEditModalOpen(false);
  };

  const handleCancel = () => {
    setEditModalOpen(false);
  };

  // const deleteImageFromGallery = (data: any) => {

  //   if(!formData.productAvailability){
  //     return toast.error('You can\'t edit sold out product.')
  //   }

  //   const preFilledImagesCount = formData.galleries.filter(
  //     (gallery) => !gallery.deleted
  //   ).length;

  //   const totalSelectedImagesCount = preFilledImagesCount + newImageUrls.length;

  //   console.log(preFilledImagesCount + newImageUrls.length)

  //   const isSubmitDisabled = totalSelectedImagesCount >= 4;

  //   console.log(preFilledImagesCount,totalSelectedImagesCount,newImageUrls.length)

  //   if(!isSubmitDisabled){
  //     return toast.error("Minimum 3 images required.")
  //   }

  //   const authToken = Cookies.get("jazz_token");

  //   const axiosInstance = axios.create({
  //     baseURL: "https://api.jazzagain.com/public/index.php",
  //     headers: {
  //       authorization: `Bearer ${authToken}`,
  //     },
  //   });

  //   axiosInstance.delete(`/api/user/productGallery/${data._id}`).then((res) => {
  //     console.log(res);
  //     setActionExecuted(!actionExecuted);
  //   });
  // };

  const deleteImageFromGallery2 = (image: any) => {
    setImageGallery((prevGallery) =>
      prevGallery.map((galleryImage) =>
        galleryImage._id === image._id
          ? {
            ...galleryImage,
            markedForDeletion: !galleryImage.markedForDeletion,
          }
          : galleryImage
      )
    );
  };

  const editVariation = (item: any, attributeName: string, newName: string) => {
    // console.log(item, attributeName, newName);
    if (!formData.productAvailability) {
      return toast.error("You can't edit sold out product.");
    }
    if (newName == "") {
      return message.info("Cannot add empty !");
    }
    // showModal();
    console.log(item, attributeName, newName);
    const authToken = Cookies.get("jazz_token");

    const axiosInstance = axios.create({
      baseURL: "https://api.jazzagain.com/public/index.php",
      headers: {
        authorization: `Bearer ${authToken}`,
      },
    });

    const data = {
      attributeId: item.attributeId[0],
      variationName: newName,
    };

    console.log("for data update>>>>>>>", data);

    axiosInstance
      .put(`/api/user/variations/${item.variationId[0]}`, data)
      .then((res) => {
        console.log(res);
        setActionExecuted(!actionExecuted);
        handleCancel();
      });
  };


  const PostProduct = async (e: any) => {
    e.preventDefault();
    console.log(variation);
    // return console.log(formData);
    const imagesToDelete = imageGallery.filter(
      (image) => image.markedForDeletion
    );

    if (!formData.productAvailability) {
      return toast.error("You can't edit sold out product.");
    }

    if (
      Number(formData.productSellingPrice) >
      Number(formData.productOriginalPrice)
    ) {
      return toast.error("Selling price can't be more than original price.");
    }

    // Images that are not deleted or marked for deletion
    const remainingImages = imageGallery.filter(
      (image) => !image.deleted && !image.markedForDeletion
    );

    // Calculate total images after potential deletions, taking into account newly uploaded images
    const totalImagesAfterDeletion =
      remainingImages.length + newImageUrls.length;

    // Check if the total number of images after deletion is less than 3
    if (totalImagesAfterDeletion < 3) {
      return toast.error("Minimum 3 images are required.");
    }

    userActivity(
      _loggedIn_user,
      "website",
      router.asPath,
      {
        formSubmit: "edit product done",
      },
      navigator.userAgent
    );

    // if(!isSubmitDisabled){
    //   return toast.error("Minimum 3 images required.")
    // }

    const {
      productSellingPrice,
      productOriginalPrice,
      categoryId,
      productFeaturedImage,
      productTitle,
      productType,
      subCategoryId,
      productAge,
      productDescription,
      productDiscountPercentage,
      productDiscountPrice,
      productShortDescription,
      brandId,
      negotiable
    } = formData;

    const data = {
      productSellingPrice,
      productOriginalPrice,
      categoryId,
      productFeaturedImage,
      productTitle,
      productType,
      subCategoryId,
      productAge,
      productDescription,
      productDiscountPercentage,
      productDiscountPrice,
      productShortDescription,
      brandId,
      negotiable
    };
    const authToken = Cookies.get("jazz_token");

    const axiosInstance = axios.create({
      baseURL: "https://api.jazzagain.com/public/index.php",
      headers: {
        authorization: `Bearer ${authToken}`,
      },
    });

    // delete requests for each marked image
    const deletePromises = imagesToDelete.map((image) =>
      axiosInstance.delete(`/api/user/productGallery/${image._id}`)
    );

    try {
      await Promise.all(deletePromises);
    } catch (error) {
      console.error("Error deleting images:", error);
      toast.error("Error deleting images");
    }

    newImageUrls.map((url: any) => {
      let Imagedata = {
        productId: formData?._id,
        imageUrl: url,
      };
      axiosInstance.post(`/api/user/productGallery`, Imagedata).then((res) => {
        console.log(res);
        // message.success("Uploaded !")
        // setActionExecuted(!actionExecuted)
        setImageUpdateLoader(false);
        setNewImageUrls([]);
      });
    });

    if (variation.length >= 1) {
      if (productType === "simple") {
        // delete variations
        const variationdeletePromises = variation.map((varItem: any) =>
          axiosInstance.delete(`/api/user/variations/${varItem.variationId[0]}`)
        );

        try {
          await Promise.all(variationdeletePromises);
        } catch (error) {
          console.error("Error deleting images:", error);
          toast.error("Error deleting images");
        }
      }
    }

    axiosInstance
      .put(`/api/user/products/${id}`, data)
      .then(async (res) => {
        toast.success("Product Updated");

        // 🔔 SEND NOTIFICATION TO BUYER (if any)
        if (counterOfferData?.buyerId && _loggedIn_user?._id) {
          const notifyPayload = {
            title: "Jazzagain - Price Update",
            body: `Seller has updated the price for ${formData.productTitle}. Click here to see new price.`,
            data: {
              type: "price updated",
              productId: formData._id,
              clickUrl: `https://www.jazzagain.com/singleproduct/${formData._id}` // ✅ Include clickUrl here too
            },
            userId: counterOfferData.buyerId,
            sender: _loggedIn_user?._id,
          };


          try {
            await axios.post(
              "https://api.jazzagain.com/node/notification-token/v2/send-notification",
              notifyPayload
            );
            toast.success("Buyer Notified");
          } catch (err) {
            console.error("Error notifying buyer:", err);
            toast.error("Buyer notification failed");
          }
        }

        setActionExecuted(!actionExecuted);
      })
      .catch((err) => {
        console.error("Update error", err);
        toast.error("Something went wrong!");
      });


  };

  const handleInputChange = async (
    event: ChangeEvent<
      HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement
    >
  ) => {
    const { name, value } = event.target;
    console.log(name, value);

    // Validation for productTitle
    if (name === "productTitle") {
      const digitCount = (value.match(/\d/g) || []).length;
      if (digitCount > 3) {
        toast.error("Product title must not contain more than 3 digits.");
        return; // Prevent updating the state if validation fails
      }
    }

    if (name === "productType" && value === "simple") {
      setFormData((prevData: any) => ({
        ...prevData,
        [name]: value,
      }));
    } else if (name === "productOriginalPrice") {
      setFormData((prevData: any) => ({
        ...prevData,
        [name]: value,
        productDiscountPrice: (
          Number(value) - Number(formData.productSellingPrice)
        ).toString(),
        productDiscountPercentage: (
          ((Number(value) - Number(formData.productSellingPrice)) * 100) /
          Number(value)
        )
          .toFixed(0)
          .toString(),
      }));
    } else if (name === "productSellingPrice") {
      setFormData((prevData: any) => ({
        ...prevData,
        [name]: value,
        productDiscountPrice: (
          Number(formData.productOriginalPrice) - Number(value)
        ).toString(),
        productDiscountPercentage: (
          ((Number(formData.productOriginalPrice) - Number(value)) * 100) /
          Number(formData.productOriginalPrice)
        )
          .toFixed(0)
          .toString(),
      }));
    } else {
      setFormData((prevData: any) => ({
        ...prevData,
        [name]: value,
      }));
    }
  };

  const togglePopupColor = (brand: string, id: string, buttonType: string) => {
    // console.log(modalCategoryId, modalsubCategoryId, brand, id)
    if (brand != "" && buttonType === "submit") {
      const authToken = Cookies.get("jazz_token");

      const axiosInstance = axios.create({
        baseURL: "https://api.jazzagain.com/public/index.php",
        headers: {
          authorization: `Bearer ${authToken}`,
        },
      });
      let newvariation = {
        attributeId: id,
        variationName: brand,
      };
      axiosInstance
        .post("/api/user/variations", newvariation)
        .then((res) => {
          console.log("Variation clg ", res.data);
          toast.success("Added successfully");
          // setvariationChangeTrigger(!variationChangeTrigger)
          const {
            productSellingPrice,
            productOriginalPrice,
            categoryId,
            productFeaturedImage,
            productTitle,
            productType,
            subCategoryId,
            productAge,
            productDescription,
            productDiscountPercentage,
            productDiscountPrice,
            productShortDescription,
            brandId,
            variations,
          } = formData;

          const data = {
            productSellingPrice,
            productOriginalPrice,
            categoryId,
            productFeaturedImage,
            productTitle,
            productType,
            subCategoryId,
            productAge,
            productDescription,
            productDiscountPercentage,
            productDiscountPrice,
            productShortDescription,
            brandId,
            variations,
          };

          const totalVariations = variations.length;
          const newVariation = {
            attributeId: res.data.variation.attributeId,
            variationId: res.data.variation._id,
          };
          variations.push(newVariation);

          const axiosInstance = axios.create({
            baseURL: "https://api.jazzagain.com/public/index.php",
            headers: {
              authorization: `Bearer ${authToken}`,
            },
          });

          axiosInstance
            .put(`/api/user/products/${formData._id}`, data)
            .then((res) => console.log(res));
        })
        .catch((err) => {
          console.log({ success: false, message: err.response.data.message });
          toast.error(err.response.data.message);
          return { success: false, message: err.response.message };
        });
    }

    setIsColorPopupOpen(!isColorPopupOpen);
  };

  const togglePopupSize = (brand: string, id: string, buttonType: string) => {
    // console.log(modalCategoryId, modalsubCategoryId, brand, id)
    if (brand != "" && buttonType === "submit") {
      const authToken = Cookies.get("jazz_token");

      const axiosInstance = axios.create({
        baseURL: "https://api.jazzagain.com/public/index.php",
        headers: {
          authorization: `Bearer ${authToken}`,
        },
      });
      let newvariation = {
        attributeId: id,
        variationName: brand,
      };
      console.table(newvariation);
      axiosInstance.post("/api/user/variations", newvariation).then((res) => {
        console.log(res.data);
        toast.success(res.data.message);
        // setvariationChangeTrigger(!variationChangeTrigger)
        const {
          productSellingPrice,
          productOriginalPrice,
          categoryId,
          productFeaturedImage,
          productTitle,
          productType,
          subCategoryId,
          productAge,
          productDescription,
          productDiscountPercentage,
          productDiscountPrice,
          productShortDescription,
          brandId,
          variations,
        } = formData;

        const data = {
          productSellingPrice,
          productOriginalPrice,
          categoryId,
          productFeaturedImage,
          productTitle,
          productType,
          subCategoryId,
          productAge,
          productDescription,
          productDiscountPercentage,
          productDiscountPrice,
          productShortDescription,
          brandId,
          variations,
        };

        console.log("DATA --- ", data);
        const totalVariations = variations.length;
        const newVariation = {
          attributeId: res.data.variation.attributeId,
          variationId: res.data.variation._id,
        };
        variations.push(newVariation);
        console.log(variations);

        const axiosInstance = axios.create({
          baseURL: "https://api.jazzagain.com/public/index.php",
          headers: {
            authorization: `Bearer ${authToken}`,
          },
        });

        axiosInstance
          .put(`/api/user/products/${formData._id}`, data)
          .then((res) => console.log("Updated data>>>", res));
      });
    }

    setIsSizePopupOpen(!isSizePopupOpen);
  };

  if (imageUpdateLoader) {
    return <Loader />;
  }

  return loading ? (
    <Loader />
  ) : (
    <>
      <Head>
        <link rel="shortcut icon" href="/images/jazzagian-logo.png" />
        <script
          dangerouslySetInnerHTML={{
            __html: `
              !function(f,b,e,v,n,t,s)
              {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
              n.callMethod.apply(n,arguments):n.queue.push(arguments)};
              if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
              n.queue=[];t=b.createElement(e);t.async=!0;
              t.src=v;s=b.getElementsByTagName(e)[0];
              s.parentNode.insertBefore(t,s)}(window, document,'script',
              'https://connect.facebook.net/en_US/fbevents.js');
              fbq('init', '360254480441103');
              fbq('track', 'EditProduct');
            `,
          }}
        />
        <noscript>
          <Image
            height="1"
            width="1"
            alt="facebook link"
            style={{ display: "none" }}
            src="https://www.facebook.com/tr?id=360254480441103&ev=EditProduct&noscript=1"
          />
        </noscript>
      </Head>

      <div className="w-full px-2 sm:w-[75%] mx-auto my-[2rem]">
        <div className="flex justify-between my-4">
          <div
            onClick={() => router.back()}
            className="flex items-center space-x-3 cursor-pointer"
          >
            <ImArrowLeft2 size={20} />
            <span>BACK</span>
          </div>
          <div></div>
          <div></div>
        </div>

        <Toaster
          toastOptions={{
            className: "",
            duration: 5000,
          }}
        />

        <div className="bg-white px-[2rem] relative">
          <hr className="border border-gray-400" />

          <form action="#" onSubmit={PostProduct}>
            <h2 className="font-bold py-[1rem]">EDIT DETAILS</h2>

            {/* <div className="text-sm pb-[1rem]">
              <label htmlFor="productType">Type *</label>
              <select
                name="productType"
                id="productType"
                style={{ display: "flex", width: "100%", maxWidth: "520px" }}
                className="flex my-1 p-2 rounded-lg border border-gray-300"
                onChange={handleInputChange}
              >
                <option
                  value={"simple"}
                  selected={formData?.productType === "simple" ? true : false}
                >
                  Standard product
                </option>
                <option
                  value={"variable"}
                  selected={formData?.productType === "variable" ? true : false}
                >
                  Product with size/color options
                </option>
              </select>
            </div> */}

            <div className="text-sm pb-[1rem]">
              <label htmlFor="categoryId">Category *</label>
              <select
                name="categoryId"
                id="categoryId"
                style={{ display: "flex", width: "100%", maxWidth: "520px" }}
                className="flex my-1 p-2 rounded-lg border border-gray-300"
                onChange={handleInputChange}
              >
                <option value="" disabled selected={true}>
                  Select Category
                </option>
                {categoryData?.map((item) => {
                  return (
                    <option
                      value={item._id}
                      key={item._id}
                      selected={item._id === formData.categoryId}
                    >
                      {item.categoryName}
                    </option>
                  );
                })}
              </select>
            </div>

            <div className="text-sm pb-[1rem]">
              <label htmlFor="subCategoryId">Sub Category *</label>
              <select
                name="subCategoryId"
                id="subCategoryId"
                style={{ display: "flex", width: "100%", maxWidth: "520px" }}
                className="flex my-1 p-2 rounded-lg border border-gray-300"
                onChange={handleInputChange}
              >
                <option value="" disabled selected={true}>
                  Select Subcategory
                </option>
                {subcategoryData.map((item) => {
                  return (
                    <option
                      value={item._id}
                      key={item._id}
                      selected={item._id === formData.subCategoryId}
                    >
                      {item.subCategoryName}
                    </option>
                  );
                })}
              </select>
            </div>

            <div className="text-sm my">
              <label htmlFor="productTitle">Product Name *</label>
              <input
                type="text"
                name="productTitle"
                id="productTitle"
                style={{ display: "flex", width: "100%", maxWidth: "520px" }}
                className="flex my-1 p-2 rounded-lg border border-gray-300"
                onChange={handleInputChange}
                value={formData?.productTitle}
              ></input>
            </div>

            <div>
              <div className="text-sm pt-[1rem]">
                <label htmlFor="brandId">Brand</label>
                <select
                  name="brandId"
                  id="brandId"
                  style={{ display: "flex", width: "100%", maxWidth: "520px" }}
                  className="flex my-1 p-2 rounded-lg border border-gray-300"
                  onChange={handleInputChange}
                >
                  <option value="" disabled selected={true}>
                    Select a brand
                  </option>
                  {brandData.map((item) => {
                    return (
                      <option value={item._id} key={item._id}>
                        {item.brandName}
                      </option>
                    );
                  })}
                </select>
              </div>
            </div>

            {formData.productType === "variable"
              ? formData.variations?.map((item: any, index: number) => (
                <>
                  {isColorPopupOpen && (
                    <AddColorModal
                      onCloseColor={togglePopupColor}
                      category={formData.categoryId}
                      subCategory={formData.subCategoryId}
                    />
                  )}
                  {isSizePopupOpen && (
                    <AddSizeModal
                      onCloseSize={togglePopupSize}
                      category={formData.categoryId}
                      subCategory={formData.subCategoryId}
                    />
                  )}
                  {formData.variations?.length < 2 ? (
                    <h2 className="text-sm flex justify-between items-center max-w-lg">
                      {/* { index === 0 && item.attribute[0]?.attributeName} */}
                      {index === 0 && "Variations"}
                      {item.attribute[0]?.attributeName === "Color" &&
                        index == 0 ? (
                        <div className="text-xs pb-[1rem] flex flex-row-reverse max-w-lg">
                          <span
                            onClick={() => togglePopupColor("", "", "")}
                            className="text-[#FE342B] cursor-pointer"
                          >
                            Add New Color
                          </span>{" "}
                          &nbsp;
                          <span
                            onClick={() => togglePopupSize("", "", "")}
                            className="text-[#FE342B] cursor-pointer"
                          >
                            Add New Size
                          </span>
                          {/* Color Not in List? &nbsp; */}
                        </div>
                      ) : item.attribute[0]?.attributeName === "Size" &&
                        index == 0 ? (
                        <div className="text-xs pb-[1rem] flex flex-row-reverse max-w-lg">
                          <span
                            onClick={() => togglePopupSize("", "", "")}
                            className="text-[#FE342B] cursor-pointer"
                          >
                            Add New
                          </span>
                          Size Not in List? &nbsp;
                        </div>
                      ) : null}
                    </h2>
                  ) : null}

                  {index === 0 &&
                    formData.variations?.map((item: any, index: number) => (
                      <>
                        <p className="inline font-semibold">
                          {item.attribute[0].attributeName} -
                        </p>
                        <Checkbox
                          key={index}
                          value={item._id}
                          className="m-2"
                          checked={true}
                          disabled
                        // onChange={() => handleVariationSelection(item)}
                        />
                        <label>{item.variation[0]?.variationName}</label>
                        <Tooltip title="Edit">
                          <button
                            type="button"
                            className="p-2 m-2"
                            // onClick={()=>editVariation(item.variation[0],item.attribute[0]?.attributeName
                            //   )}
                            onClick={() => {
                              setSelectedItem(item);
                              setEditModalOpen(true);
                            }}
                          >
                            <FaEdit />
                          </button>
                        </Tooltip>
                      </>
                    ))}
                </>
              ))
              : null}

            <Modal
              title={`Edit ${selectedItem?.attribute[0].attributeName}`}
              footer={null}
              mask={false}
              open={EditModalOpen}
              onOk={handleOk}
              onCancel={() => {
                handleCancel();
                setSelectedItem(null);
              }}
            >
              <Input
                placeholder="Enter new name"
                showCount={true}
                onChange={(e) => setEditInputValue(e.target.value)}
              />
              <div className="my-4">
                <Button
                  onClick={() =>
                    editVariation(
                      selectedItem,
                      selectedItem?.attribute[0]?.attributeName,
                      editInputvalue
                    )
                  }
                >
                  Update
                </Button>
              </div>
            </Modal>

            {/* <div className="pt-[1rem] text-sm">
              <label htmlFor="productShortDescription *">
                Product Short Description *
              </label>
              <textarea
                rows={3}
                name="productShortDescription"
                id="productShortDescription"
                style={{ display: "flex", width: "100%", maxWidth: "520px" }}
                className="flex my-1 p-2 rounded-lg border border-gray-300"
                onChange={handleInputChange}
                value={formData?.productShortDescription}
              ></textarea>
              <div
                className="text-xs flex flex-row-reverse justify-between"
                style={{ maxWidth: "520px" }}
              >
              </div>
            </div> */}

            <div className="text-sm">
              <label htmlFor="productDescription *">
                Detailed Product Description *
              </label>
              <textarea
                rows={5}
                name="productDescription"
                id="productDescription"
                style={{ display: "flex", width: "100%", maxWidth: "520px" }}
                className="flex my-1 p-2 rounded-lg border border-gray-300"
                onChange={handleInputChange}
                value={formData?.productDescription}
              ></textarea>
              <div
                className="text-xs flex flex-row-reverse justify-between"
                style={{ maxWidth: "520px" }}
              >
                {/* <span> {formData.productDescription.length}/4096</span> */}
                <p className="text-xs text-gray-500">
                  Our refund policy cover SIGNIFICANTLY NOT AS DESCRIBED.
                  <br />
                  We consider items to be &apos;SNAD&apos; if they are
                  significantly different from the listing descriptions or
                  photos. Kindly ensure you clearly define the item being listed
                  and include any issues with the product.
                </p>
              </div>
            </div>

            <hr className="border border-gray-400 my-[1rem]" />

            <div className="">
              <h3 className="font-bold py-[.8rem]">EDIT PRICE</h3>

              <div className="pt-[1rem]">
                <label
                  htmlFor="productSellingPrice"
                  className="pb-[.3rem] text-sm flex flex-col"
                >
                  Product Selling Price *
                </label>
                <input
                  type="number"
                  name="productSellingPrice"
                  placeholder="&#8358; | "
                  style={{ display: "flex", width: "100%", maxWidth: "520px" }}
                  className="flex my-1 p-2 rounded-lg border border-gray-300"
                  onChange={handleInputChange}
                  value={formData?.productSellingPrice}
                />
              </div>

              <div className="pt-[1rem]">
                <label
                  htmlFor="productOriginalPrice"
                  className="pb-[.3rem] text-sm flex flex-col"
                >
                  Product Original Price *
                </label>
                <input
                  type="number"
                  name="productOriginalPrice"
                  placeholder="&#8358; | "
                  style={{ display: "flex", width: "100%", maxWidth: "520px" }}
                  className="flex my-1 p-2 rounded-lg border border-gray-300"
                  onChange={handleInputChange}
                  value={formData?.productOriginalPrice}
                />
              </div>
            </div>

            <div className="mt-4">
              <label className="text-sm">
                <input
                  type="checkbox"
                  checked={formData?.negotiable}
                  onChange={(e) =>
                    setFormData((prevData) => ({
                      ...prevData,
                      negotiable: e.target.checked,
                    }))
                  }
                  className="mr-2"
                />
                Price Negotiable - Reach a Deal!  </label> <p className="text-xs text-[#FF332B]">
                &#40;Make the price negotiable and reach a deal.&#x29;
              </p>
            </div>

            <hr className="border border-gray-400 mb-[1rem] mt-[1.5rem]" />

            <div className="">
              <h2 className="font-bold pt-[1rem]">UPLOAD PHOTOS *</h2>
              <p className="my-3">Minimum 3 photos should be selected</p>
              <div className="flex flex-wrap">
                <div className="mr-4 mb-4">
                  <div className="flex flex-wrap">
                    {Array.from({ length: 5 }).map((_, index) => {
                      const gallery = imageGallery?.[index];

                      if (
                        gallery &&
                        !gallery.deleted &&
                        !gallery.markedForDeletion
                      ) {
                        // Image is not marked for deletion, render it normally
                        return (
                          <div
                            key={index}
                            className="md:inline-block mr-4 mb-4"
                          >
                            <div className="flex flex-col items-center">
                              <Image
                                src={`https://api.jazzagain.com/public/${gallery.imageUrl}`}
                                alt="Uploaded Preview"
                                width={150}
                                height={150}
                                className="h-36 w-36"
                              />
                              <br />
                              <Image
                                src={"/images/trash-icon.png"}
                                width={25}
                                height={25}
                                alt="delete icon"
                                onClick={() => deleteImageFromGallery2(gallery)}
                                className="cursor-pointer"
                              />
                            </div>
                          </div>
                        );
                      } else if (!gallery || gallery.markedForDeletion) {
                        // No image or image marked for deletion, show the upload box
                        return (
                          <div
                            key={index}
                            className="md:inline-block mr-4 mb-4"
                          >
                            <ImageBox
                              key={`upload-${index}`}
                              id={index + 1}
                              onImageUpload={handleImageUpload}
                            />
                          </div>
                        );
                      }
                    })}
                  </div>
                </div>
              </div>
            </div>

            <button type="submit" className="bg-[#FF332B] hover:bg-[#383736] text-white text-base rounded-lg p-2 my-[.5rem] mb-[2rem] inline-block">
              UPDATE
            </button>
          </form>
        </div>
      </div>
    </>
  );
};

export default EditProduct;
