Adding a product does add images without issues... however editing the product always deletes the images!!
"use client";
import { X, Plus, Trash2 } from "lucide-react";
import { MultipartFileUploader } from "@/components/MultipartFileUploader";
import { toast } from "react-toastify";
import React, { useEffect, useState } from "react";
import { getToken } from "@/app/auth";

interface Category {
  id: number;
  name: string;
}

interface EditProductProps {
  isOpen: boolean;
  onClose: () => void;
  product: Product;
}

interface Brand {
  id: number;
  name: string;
}

interface Size {
  id?: number;
  name: string;
  price: string;
  qty: string;
  images: string[];
  inheritImages?: boolean;
}

interface Color {
  inheritImages?: boolean;
  id?: number;
  name: string;
  price: string | null;
  qty: string | null;
  sizes: Size[];
  images: string[];
}

interface Product {
  id: number;
  name: string;
  description: string;
  brand_id: number;
  has_color: boolean;
  has_size: boolean;
  categories: Category[];
  colors: Color[];
  sizes: Size[];
  price: string | null;
  qty: string | null;
  images: string[];
}

export default function EditProduct({
  isOpen,
  onClose,
  product,
}: EditProductProps) {
  const [editedProduct, setEditedProduct] = useState<Product>({
    ...product,
    sizes: product.sizes || [], // Ensure sizes is always an array
    colors: product.colors.map((color) => ({
      ...color,
      sizes: color.sizes || [], // Ensure sizes is always an array for each color
    })),
    images: [],
  });
  const [categories, setCategories] = useState<Category[]>([]);
  const [brands, setBrands] = useState<Brand[]>([]);

  useEffect(() => {
    fetchCategories();
    fetchBrands();
  }, []);
  const handleDeleteColor = (colorIndex: number) => {
    setEditedProduct((prevProduct) => {
      const newColors = [...prevProduct.colors];
      newColors.splice(colorIndex, 1);
      return { ...prevProduct, colors: newColors };
    });
  };

  const handleDeleteSize = (colorIndex: number, sizeIndex: number) => {
    setEditedProduct((prevProduct) => {
      if (colorIndex === -1) {
        const newSizes = [...prevProduct.sizes];
        newSizes.splice(sizeIndex, 1);
        return { ...prevProduct, sizes: newSizes };
      } else {
        const newColors = [...prevProduct.colors];
        newColors[colorIndex].sizes.splice(sizeIndex, 1);
        return { ...prevProduct, colors: newColors };
      }
    });
  };

  const handleInheritImagesChange = (
    variantType: "color" | "size",
    colorIndex: number,
    sizeIndex: number,
  ) => {
    setEditedProduct((prevProduct) => {
      const updatedProduct = { ...prevProduct };

      if (variantType === "color") {
        updatedProduct.colors[colorIndex].inheritImages =
          !updatedProduct.colors[colorIndex].inheritImages;

        if (updatedProduct.colors[colorIndex].inheritImages && colorIndex > 0) {
          const prevColor = updatedProduct.colors[colorIndex - 1];
          updatedProduct.colors[colorIndex].images = [...prevColor.images];
        }
      } else if (variantType === "size") {
        if (colorIndex === -1) {
          updatedProduct.sizes[sizeIndex].inheritImages =
            !updatedProduct.sizes[sizeIndex].inheritImages;

          if (updatedProduct.sizes[sizeIndex].inheritImages && sizeIndex > 0) {
            const prevSize = updatedProduct.sizes[sizeIndex - 1];
            updatedProduct.sizes[sizeIndex].images = [...prevSize.images];
          }
        } else {
          updatedProduct.colors[colorIndex].sizes[sizeIndex].inheritImages =
            !updatedProduct.colors[colorIndex].sizes[sizeIndex].inheritImages;

          if (
            updatedProduct.colors[colorIndex].sizes[sizeIndex].inheritImages &&
            sizeIndex > 0
          ) {
            const prevSize =
              updatedProduct.colors[colorIndex].sizes[sizeIndex - 1];
            updatedProduct.colors[colorIndex].sizes[sizeIndex].images = [
              ...prevSize.images,
            ];
          }
        }
      }

      return updatedProduct;
    });
  };

  const fetchCategories = async () => {
    try {
      const response = await fetch(
        "http://localhost:4000/subcategories/non-brands",
      );
      const data = await response.json();
      setCategories(data);
    } catch (error) {
      console.error("Error fetching categories:", error);
    }
  };

  const fetchBrands = async () => {
    try {
      const response = await fetch(
        "http://localhost:4000/subcategories/brands",
      );
      const data = await response.json();
      setBrands(data);
    } catch (error) {
      console.error("Error fetching brands:", error);
    }
  };

  const handleCategoryToggle = (categoryId: number) => {
    // @ts-ignore
    setEditedProduct((prevProduct) => {
      const updatedCategories = prevProduct.categories.some(
        // @ts-ignore
        (cat) => cat.id === categoryId,
      )
        ? prevProduct.categories.filter((cat) => {
            // @ts-ignore
            cat.id !== categoryId;
          })
        : [
            ...prevProduct.categories,
            {
              id: categoryId,
              name: categories.find((cat) => cat.id === categoryId)?.name || "",
            },
          ];
      return { ...prevProduct, categories: updatedCategories };
    });
  };

  const handleInputChange = (e: {
    target: { name: string; value: string };
  }) => {
    const { name, value } = e.target;
    setEditedProduct((prevProduct) => ({
      ...prevProduct,
      [name]: value,
    }));
  };

  const handleColorToggle = () => {
    setEditedProduct((prevProduct) => ({
      ...prevProduct,
      has_color: !prevProduct.has_color,
      colors: !prevProduct.has_color ? [] : prevProduct.colors,
    }));
  };

  const handleBrandChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setEditedProduct((prevProduct) => ({
      ...prevProduct,
      brand_id: parseInt(e.target.value),
    }));
  };

  const handleSizeToggle = () => {
    setEditedProduct((prevProduct) => ({
      ...prevProduct,
      has_size: !prevProduct.has_size,
      sizes: !prevProduct.has_size ? [] : prevProduct.sizes,
    }));
  };

  const handleAddColor = () => {
    setEditedProduct((prevProduct) => ({
      ...prevProduct,
      colors: [
        ...prevProduct.colors,
        { name: "", price: null, qty: null, sizes: [], images: [] },
      ],
    }));
  };

  const handleAddSize = (colorIndex: number) => {
    setEditedProduct((prevProduct) => {
      if (colorIndex === -1) {
        return {
          ...prevProduct,
          sizes: [
            ...prevProduct.sizes,
            { name: "", price: "", qty: "", images: [] },
          ],
        };
      } else {
        const newColors = [...prevProduct.colors];
        newColors[colorIndex].sizes.push({
          name: "",
          price: "",
          qty: "",
          images: [],
        });
        return {
          ...prevProduct,
          colors: newColors,
        };
      }
    });
  };

  const handleColorChange = (
    index: number,
    field: keyof Color,
    value: string,
  ) => {
    setEditedProduct((prevProduct) => {
      const newColors = [...prevProduct.colors];
      newColors[index] = {
        ...newColors[index],
        [field]: value,
      };
      return { ...prevProduct, colors: newColors };
    });
  };

  const handleSizeChange = (
    colorIndex: number,
    sizeIndex: number,
    field: keyof Size,
    value: string,
  ) => {
    setEditedProduct((prevProduct) => {
      if (colorIndex === -1) {
        const newSizes = [...prevProduct.sizes];
        newSizes[sizeIndex] = {
          ...newSizes[sizeIndex],
          [field]: value,
          images: newSizes[sizeIndex].images || null, // Ensure images array exists
        };
        return { ...prevProduct, sizes: newSizes };
      } else {
        const newColors = [...prevProduct.colors];
        newColors[colorIndex].sizes[sizeIndex] = {
          ...newColors[colorIndex].sizes[sizeIndex],
          [field]: value,
          images: newColors[colorIndex].sizes[sizeIndex].images || [], // Ensure images array exists
        };
        return { ...prevProduct, colors: newColors };
      }
    });
  };

  const handleImageUpload = (
    fileIds: string[],
    variantType: "color" | "size" | "product",
    colorIndex: number,
    sizeIndex: number,
  ) => {
    setEditedProduct((prevProduct) => {
      const updatedProduct = { ...prevProduct };

      if (variantType === "color") {
        updatedProduct.colors[colorIndex].images = fileIds;
      } else if (variantType === "size") {
        if (colorIndex === -1) {
          updatedProduct.sizes[sizeIndex].images = fileIds;
        } else {
          updatedProduct.colors[colorIndex].sizes[sizeIndex].images = fileIds;
        }
      } else {
        updatedProduct.images = fileIds;
      }

      return updatedProduct;
    });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const productType =
      editedProduct.has_color && editedProduct.has_size
        ? "color_size"
        : editedProduct.has_color
          ? "color"
          : editedProduct.has_size
            ? "size"
            : "simple";

    const productData = {
      ...editedProduct,
      product_type: productType,
      category_ids: editedProduct.categories.map((cat) => cat.id),
      hasColor: editedProduct.has_color,
      hasSize: editedProduct.has_size,
      colors: editedProduct.has_color
        ? editedProduct.colors.map((color) => ({
            id: color.id, // Include the color ID if it exists
            name: color.name,
            price: color.price ? parseFloat(color.price) : null,
            qty: color.qty ? parseInt(color.qty) : null,
            hasSize: editedProduct.has_size,
            sizes: editedProduct.has_size
              ? color.sizes.map((size) => ({
                  id: size.id, // Include the size ID if it exists
                  name: size.name,
                  price: parseFloat(size.price),
                  qty: parseInt(size.qty),
                  images: size.images,
                }))
              : [],
            images: color.images,
          }))
        : [],
      sizes:
        editedProduct.has_size && !editedProduct.has_color
          ? editedProduct.sizes.map((size) => ({
              id: size.id, // Include the size ID if it exists
              name: size.name,
              price: parseFloat(size.price),
              qty: parseInt(size.qty),
              images: size.images,
            }))
          : [],
      price: editedProduct.price ? parseFloat(editedProduct.price) : null,
      qty: editedProduct.qty ? parseInt(editedProduct.qty) : null,
      images: editedProduct.images,
    };
    const token = getToken();

    if (!token) {
      toast.error("You must be logged in to edit the product.");
      return;
    }
    try {
      const response = await fetch(
        `http://localhost:4000/products/${editedProduct.id}`,
        {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`, // Include the token here
          },
          body: JSON.stringify(productData),
        },
      );

      if (!response.ok) {
        throw new Error("Failed to update product");
      }

      const updatedProduct = await response.json();
      console.log("Product updated:", updatedProduct);
      toast.success("Product updated successfully!");
      onClose();
    } catch (error) {
      console.error("Error updating product:", error);
      toast.error("Failed to update product. Please try again.");
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[99999999] flex h-screen transform items-center justify-center overflow-y-scroll bg-black bg-opacity-50">
      <div className="relative h-screen w-full max-w-2xl overflow-y-scroll rounded-lg bg-white p-8">
        <button
          onClick={onClose}
          className="absolute right-4 top-4 text-gray-500 hover:text-gray-700"
        >
          <X size={24} />
        </button>

        <h2 className="mb-6 text-2xl font-bold">Edit Product</h2>

        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Product Name */}
          <div>
            <label className="mb-2 block font-bold" htmlFor="name">
              Product Name
            </label>
            <input
              type="text"
              id="name"
              name="name"
              value={editedProduct.name}
              onChange={handleInputChange}
              className="w-full rounded-md border p-2"
              required
            />
          </div>

          {/* Description */}
          <div>
            <label className="mb-2 block font-bold" htmlFor="description">
              Description
            </label>
            <textarea
              id="description"
              name="description"
              value={editedProduct.description}
              onChange={handleInputChange}
              className="w-full rounded-md border p-2"
              style={{ direction: "rtl" }}
              required
            />
          </div>

          {/* Categories */}
          <div>
            <label className="mb-2 block font-bold">Categories</label>
            <div className="flex flex-wrap gap-2">
              {categories.map((category) => (
                <button
                  key={category.id}
                  type="button"
                  onClick={() => handleCategoryToggle(category.id)}
                  className={`rounded-full px-3 py-1 text-sm ${
                    editedProduct.categories.some(
                      // @ts-ignore
                      (cat) => cat.id === category.id,
                    )
                      ? "bg-blue-500 text-white"
                      : "bg-gray-200 text-gray-700"
                  }`}
                >
                  {category.name}
                </button>
              ))}
            </div>
          </div>

          {/* Brand */}
          <div>
            <label className="mb-2 block font-bold" htmlFor="brand">
              Brand
            </label>
            <select
              id="brand"
              name="brand"
              value={editedProduct.brand_id}
              onChange={handleBrandChange}
              className="w-full rounded-md border p-2"
              required
            >
              <option value="">Select a brand</option>
              {brands.map((brand) => (
                <option key={brand.id} value={brand.id}>
                  {brand.name}
                </option>
              ))}
            </select>
          </div>

          {/* Has Color */}
          <div>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={editedProduct.has_color}
                onChange={handleColorToggle}
                className="mr-2"
              />
              <span className="font-bold">Has Color?</span>
            </label>
          </div>

          {/* Colors */}
          {editedProduct.has_color && (
            <div>
              <label className="mb-2 block font-bold">Colors</label>
              <div className="space-y-4">
                {editedProduct.colors.map((color, colorIndex) => (
                  <div key={colorIndex} className="rounded-md border p-4">
                    <div className="mb-2 flex items-center justify-between">
                      <input
                        type="text"
                        value={color.name}
                        onChange={(e) =>
                          handleColorChange(colorIndex, "name", e.target.value)
                        }
                        className="mr-2 flex-grow rounded-md border p-2"
                        placeholder="Color name"
                      />
                      <button
                        type="button"
                        onClick={() => handleDeleteColor(colorIndex)}
                        className="text-red-500 hover:text-red-700"
                      >
                        <Trash2 size={20} />
                      </button>
                    </div>

                    <div className="mt-2 space-y-2">
                      <div className="flex space-x-2">
                        <input
                          type="number"
                          // @ts-ignore
                          value={color.price}
                          onChange={(e) =>
                            handleColorChange(
                              colorIndex,
                              "price",
                              e.target.value,
                            )
                          }
                          className="w-1/2 rounded-md border p-2"
                          placeholder="Price"
                        />
                        <input
                          type="number"
                          // @ts-ignore
                          value={color.qty}
                          onChange={(e) =>
                            handleColorChange(colorIndex, "qty", e.target.value)
                          }
                          className="w-1/2 rounded-md border p-2"
                          placeholder="Quantity"
                        />
                      </div>
                      <MultipartFileUploader
                        onUploadSuccess={(fileIds) =>
                          // @ts-ignore
                          handleImageUpload(fileIds, "color", colorIndex)
                        }
                        // @ts-ignore
                        existingImages={color.images}
                      />
                    </div>
                  </div>
                ))}
              </div>
              <button
                type="button"
                onClick={handleAddColor}
                className="mt-2 rounded-md bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
              >
                <Plus className="mr-1 inline-block" size={16} />
                Add Color
              </button>
            </div>
          )}

          {/* Has Size */}
          <div>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={editedProduct.has_size}
                onChange={handleSizeToggle}
                className="mr-2"
              />
              <span className="font-bold">Has Size?</span>
            </label>
          </div>

          {/* Sizes */}
          {editedProduct.has_size && (
            <div>
              <label className="mb-2 block font-bold">Sizes</label>
              <div className="space-y-2">
                {editedProduct.sizes.map((size, index) => (
                  <div key={index} className="space-y-2 rounded-md border p-2">
                    <div className="flex items-center justify-between">
                      <input
                        type="text"
                        value={size.name}
                        onChange={(e) =>
                          handleSizeChange(-1, index, "name", e.target.value)
                        }
                        className="mr-2 w-full rounded-md border p-2"
                        placeholder="Size name"
                      />
                      <button
                        type="button"
                        onClick={() => handleDeleteSize(-1, index)}
                        className="text-red-500 hover:text-red-700"
                      >
                        <Trash2 size={20} />
                      </button>
                    </div>
                    <div className="flex space-x-2">
                      <input
                        type="number"
                        value={size.price}
                        onChange={(e) =>
                          handleSizeChange(-1, index, "price", e.target.value)
                        }
                        className="w-1/2 rounded-md border p-2"
                        placeholder="Price"
                      />
                      <input
                        type="number"
                        value={size.qty}
                        onChange={(e) =>
                          handleSizeChange(-1, index, "qty", e.target.value)
                        }
                        className="w-1/2 rounded-md border p-2"
                        placeholder="Quantity"
                      />
                    </div>
                    {index > 0 && (
                      <label className="flex items-center">
                        <input
                          type="checkbox"
                          checked={size.inheritImages}
                          onChange={() =>
                            handleInheritImagesChange("size", -1, index)
                          }
                          className="mr-1"
                        />
                        <span>Inherit images</span>
                      </label>
                    )}
                    {!size.inheritImages && (
                      <MultipartFileUploader
                        onUploadSuccess={(fileIds) =>
                          handleImageUpload(fileIds, "size", -1, index)
                        }
                      />
                    )}
                  </div>
                ))}
                <button
                  type="button"
                  onClick={() => handleAddSize(-1)}
                  className="rounded-md bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
                >
                  <Plus className="mr-1 inline-block" size={16} />
                  Add Size
                </button>
              </div>
            </div>
          )}

          {/* Product Details (when no color and no size) */}
          {!product.has_color && !product.has_size && (
            <div>
              <label className="mb-2 block font-bold">Product Details</label>
              <div className="flex items-center space-x-2">
                <input
                  type="number"
                  // @ts-ignore
                  value={product.price}
                  onChange={(e) =>
                    handleInputChange({
                      target: { name: "price", value: e.target.value },
                    })
                  }
                  className="rounded-md border p-2"
                  placeholder="Price"
                />
                <input
                  type="number"
                  // @ts-ignore
                  value={product.qty}
                  onChange={(e) =>
                    handleInputChange({
                      target: { name: "qty", value: e.target.value },
                    })
                  }
                  className="rounded-md border p-2"
                  placeholder="Quantity"
                />
              </div>
              <div className="mt-2">
                <MultipartFileUploader
                  onUploadSuccess={(fileIds) =>
                    // @ts-ignore
                    handleImageUpload(fileIds, "product")
                  }
                />
              </div>
            </div>
          )}

          <div className="flex justify-end">
            <button
              type="submit"
              className="rounded-md bg-green-500 px-4 py-2 text-white hover:bg-green-600"
            >
              Edit Product
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
"use client";
import React, { useState, useEffect } from "react";
import { X, Plus } from "lucide-react";
import { MultipartFileUploader } from "@/components/MultipartFileUploader";
import { toast } from "react-toastify";
import { getToken } from "@/app/auth";

export default function AddProductDialog({ isOpen, onClose }) {
  const [product, setProduct] = useState({
    name: "",
    description: "",
    category: "",
    subcategory: "",
    brand: "",
    hasColor: false,
    colors: [],
    hasSize: false,
    sizes: [],
    categories: [],
    price: "",
    qty: "",
    images: [],
  });

  const [categories, setCategories] = useState([]);
  const [brands, setBrands] = useState([]);

  useEffect(() => {
    fetchCategories();
    fetchBrands();
  }, []);

  const fetchCategories = async () => {
    try {
      const token = getToken(); // Retrieve the token from localStorage

      if (!token) {
        toast.error("You must be logged in to add a product.");
        return;
      }
      const response = await fetch(
        "http://localhost:4000/subcategories/non-brands",
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`, // Include the token here
          },
        },
      );
      const data = await response.json();
      setCategories(data);
    } catch (error) {
      console.error("Error fetching categories:", error);
    }
  };

  const fetchBrands = async () => {
    try {
      const token = getToken(); // Retrieve the token from localStorage

      if (!token) {
        toast.error("You must be logged in to add a product.");
        return;
      }
      const response = await fetch(
        "http://localhost:4000/subcategories/brands",
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`, // Include the token here
          },
        },
      );
      const data = await response.json();
      setBrands(data);
    } catch (error) {
      console.error("Error fetching brands:", error);
    }
  };

  const handleCategoryToggle = (categoryId) => {
    setProduct((prevProduct) => {
      const updatedCategories = prevProduct.categories.includes(categoryId)
        ? prevProduct.categories.filter((id) => id !== categoryId)
        : [...prevProduct.categories, categoryId];
      return { ...prevProduct, categories: updatedCategories };
    });
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setProduct((prevProduct) => ({
      ...prevProduct,
      [name]: value,
    }));
  };
  useEffect(() => {
    console.log("Updated product state:", product);
  }, [product]);
  const handleColorToggle = () => {
    setProduct({ ...product, hasColor: !product.hasColor, colors: [] });
  };

  const handleBrandChange = (e) => {
    setProduct({ ...product, brand: e.target.value });
  };

  const handleSizeToggle = () => {
    setProduct({
      ...product,
      hasSize: !product.hasSize,
      sizes: !product.hasSize ? [] : product.sizes,
    });
  };
  const [isSubmitting, setIsSubmitting] = useState(false); // Start submission]
  const handleAddColor = () => {
    setProduct((prevProduct) => {
      const newColor = {
        name: "",
        hasSize: false,
        sizes: [],
        price: "",
        qty: "",
        images: [],
        inheritImages: false,
      };

      return {
        ...prevProduct,
        colors: [...prevProduct.colors, newColor],
      };
    });
  };

  const handleColorChange = (index, field, value) => {
    setProduct((prevProduct) => {
      const newColors = [...prevProduct.colors];
      newColors[index] = {
        ...newColors[index],
        [field]: value,
      };
      return { ...prevProduct, colors: newColors };
    });
  };

  const handleColorSizeToggle = (colorIndex) => {
    const newColors = [...product.colors];
    newColors[colorIndex].hasSize = !newColors[colorIndex].hasSize;
    newColors[colorIndex].sizes = [];
    setProduct({ ...product, colors: newColors });
  };

  const handleAddSize = (colorIndex) => {
    setProduct((prevProduct) => {
      if (colorIndex === -1) {
        const newSize = {
          name: "",
          images: [],
          price: "",
          qty: "",
          inheritImages: false,
        };
        return {
          ...prevProduct,
          sizes: [...prevProduct.sizes, newSize],
        };
      } else {
        const newColors = [...prevProduct.colors];
        const newSize = {
          name: "",
          images: [],
          price: "",
          qty: "",
          inheritImages: false,
        };
        newColors[colorIndex] = {
          ...newColors[colorIndex],
          sizes: [...newColors[colorIndex].sizes, newSize],
        };
        return {
          ...prevProduct,
          colors: newColors,
        };
      }
    });
  };

  const handleSizeChange = (colorIndex, sizeIndex, field, value) => {
    setProduct((prevProduct) => {
      if (colorIndex === -1) {
        const newSizes = [...prevProduct.sizes];
        newSizes[sizeIndex] = {
          ...newSizes[sizeIndex],
          [field]: value,
        };
        return { ...prevProduct, sizes: newSizes };
      } else {
        const newColors = [...prevProduct.colors];
        newColors[colorIndex].sizes[sizeIndex] = {
          ...newColors[colorIndex].sizes[sizeIndex],
          [field]: value,
        };
        return { ...prevProduct, colors: newColors };
      }
    });
  };

  const handleImageUpload = (fileIds, variantType, colorIndex, sizeIndex) => {
    const formattedImages = fileIds.map((url) => ({ url }));

    setProduct((prevProduct) => {
      let updatedProduct = { ...prevProduct };

      if (variantType === "color") {
        updatedProduct.colors[colorIndex].images = formattedImages;
      } else if (variantType === "size") {
        if (colorIndex === -1) {
          updatedProduct.sizes[sizeIndex].images = formattedImages;
        } else {
          updatedProduct.colors[colorIndex].sizes[sizeIndex].images =
            formattedImages;
        }
      } else {
        updatedProduct.images = formattedImages;
      }

      return updatedProduct;
    });
  };
  const handleInheritImagesChange = (variantType, colorIndex, sizeIndex) => {
    setProduct((prevProduct) => {
      let updatedProduct = JSON.parse(JSON.stringify(prevProduct)); // Deep clone

      if (variantType === "color") {
        updatedProduct.colors[colorIndex].inheritImages =
          !updatedProduct.colors[colorIndex].inheritImages;

        if (updatedProduct.colors[colorIndex].inheritImages && colorIndex > 0) {
          const prevColor = updatedProduct.colors[colorIndex - 1];
          updatedProduct.colors[colorIndex].images = [...prevColor.images];
        }
      } else if (variantType === "size") {
        if (colorIndex === -1) {
          updatedProduct.sizes[sizeIndex].inheritImages =
            !updatedProduct.sizes[sizeIndex].inheritImages;

          if (updatedProduct.sizes[sizeIndex].inheritImages && sizeIndex > 0) {
            const prevSize = updatedProduct.sizes[sizeIndex - 1];
            updatedProduct.sizes[sizeIndex].images = [...prevSize.images];
          }
        } else {
          updatedProduct.colors[colorIndex].sizes[sizeIndex].inheritImages =
            !updatedProduct.colors[colorIndex].sizes[sizeIndex].inheritImages;

          if (
            updatedProduct.colors[colorIndex].sizes[sizeIndex].inheritImages &&
            sizeIndex > 0
          ) {
            const prevSize =
              updatedProduct.colors[colorIndex].sizes[sizeIndex - 1];
            updatedProduct.colors[colorIndex].sizes[sizeIndex].images = [
              ...prevSize.images,
            ];
          }
        }
      }

      return updatedProduct;
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);
    // Determine if any color has sizes
    const colorsHaveSizes =
      product.hasColor &&
      product.colors.some((color) => color.hasSize && color.sizes.length > 0);

    // Determine productType based on the presence of colors and sizes
    let productType;
    if (colorsHaveSizes) {
      productType = "color_size";
    } else if (product.hasColor) {
      productType = "color";
    } else if (product.hasSize) {
      productType = "size";
    } else {
      productType = "simple";
    }

    // Construct productData without using ||
    const productData = {
      name: product.name,
      description: product.description,
      brand_id: parseInt(product.brand, 10),
      has_color: product.hasColor,
      has_size: product.hasSize,
      product_type: productType,
      category_ids: product.categories,
      colors: product.colors.map((color) => ({
        name: color.name,
        images: color.images,
        has_size: color.hasSize,
        sizes: color.hasSize
          ? color.sizes.map((size) => ({
              name: size.name,
              price: parseFloat(size.price),
              qty: parseInt(size.qty, 10) || 0,
              images: size.images,
            }))
          : [],
        price: parseFloat(color.price),
        qty: parseInt(color.qty, 10) || 0,
      })),
      sizes: !product.hasColor
        ? product.sizes.map((size) => ({
            name: size.name,
            price: parseFloat(size.price),
            qty: parseInt(size.qty, 10) || 0,
            images: size.images,
          }))
        : [],
      price: parseFloat(product.price),
      qty: parseInt(product.qty, 10) || 0,
      images: product.images,
    };
    console.log(productData);
    try {
      const token = getToken(); // Retrieve the token from localStorage

      if (!token) {
        setIsSubmitting(true); // Start submission
        toast.error("You must be logged in to add a product.");
        return;
      }

      const response = await fetch("http://localhost:4000/products", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`, // Include the token here
        },
        body: JSON.stringify(productData),
      });

      if (!response.ok) {
        setIsSubmitting(true); // Start submission
        const errorData = await response.json();
        throw new Error(errorData.message || "Failed to create product");
      }

      // Reset the form after successful submission
      setProduct({
        name: "",
        description: "",
        category: "",
        subcategory: "",
        brand: "",
        hasColor: false,
        colors: [],
        hasSize: false,
        sizes: [],
        categories: [],
        price: "",
        qty: "",
        images: [],
      });

      toast.success("Product added successfully!");
      onClose();
    } catch (error) {
      console.error("Error creating product:", error);
      setIsSubmitting(true); // Start submission
      toast.error("Failed to add product. Please try again.");
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[99999999] flex h-screen transform items-center justify-center overflow-y-scroll bg-black bg-opacity-50">
      <div className="relative h-screen w-full max-w-2xl overflow-y-scroll rounded-lg bg-white p-8">
        <button
          onClick={onClose}
          className="absolute right-4 top-4 text-gray-500 hover:text-gray-700"
        >
          <X size={24} />
        </button>

        <h2 className="mb-6 text-2xl font-bold">Add New Product</h2>

        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Product Name */}
          <div>
            <label className="mb-2 block font-bold" htmlFor="name">
              Product Name
            </label>
            <input
              type="text"
              id="name"
              name="name"
              value={product.name}
              onChange={handleInputChange}
              className="w-full rounded-md border p-2"
              required
            />
          </div>

          {/* Description */}
          <div>
            <label className="mb-2 block font-bold" htmlFor="description">
              Description
            </label>
            <textarea
              id="description"
              name="description"
              value={product.description}
              onChange={handleInputChange}
              className="w-full rounded-md border p-2"
              style={{ direction: "rtl" }}
              required
            />
          </div>

          {/* Categories */}
          <div>
            <label className="mb-2 block font-bold">Categories</label>
            <div className="flex flex-wrap gap-2">
              {categories.map((category) => (
                <button
                  key={category.id}
                  type="button"
                  onClick={() => handleCategoryToggle(category.id)}
                  className={`rounded-full px-3 py-1 text-sm ${
                    product.categories.includes(category.id)
                      ? "bg-blue-500 text-white"
                      : "bg-gray-200 text-gray-700"
                  }`}
                >
                  {category.name}
                </button>
              ))}
            </div>
          </div>

          {/* Brand */}
          <div>
            <label className="mb-2 block font-bold" htmlFor="brand">
              Brand
            </label>
            <select
              id="brand"
              name="brand"
              value={product.brand}
              onChange={handleBrandChange}
              className="w-full rounded-md border p-2"
              required
            >
              <option value="">Select a brand</option>
              {brands.map((brand) => (
                <option key={brand.id} value={brand.id}>
                  {brand.name}
                </option>
              ))}
            </select>
          </div>

          {/* Has Color */}
          <div>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={product.hasColor}
                onChange={handleColorToggle}
                className="mr-2"
              />
              <span className="font-bold">Has Color?</span>
            </label>
          </div>

          {/* Colors */}
          {product.hasColor && (
            <div>
              <label className="mb-2 block font-bold">Colors</label>
              <div className="space-y-4">
                {product.colors.map((color, colorIndex) => (
                  <div key={colorIndex} className="rounded-md border p-4">
                    <input
                      type="text"
                      value={color.name}
                      onChange={(e) =>
                        handleColorChange(colorIndex, "name", e.target.value)
                      }
                      className="mb-2 rounded-md border p-2"
                      placeholder="Color name"
                    />

                    <label className="ml-2 flex items-center">
                      <input
                        type="checkbox"
                        checked={color.hasSize}
                        onChange={() => handleColorSizeToggle(colorIndex)}
                        className="mr-1"
                      />
                      <span>Has Size?</span>
                    </label>

                    {colorIndex > 0 && (
                      <label className="ml-2 flex items-center">
                        <input
                          type="checkbox"
                          checked={color.inheritImages}
                          onChange={() =>
                            handleInheritImagesChange("color", colorIndex)
                          }
                          className="mr-1"
                        />
                        <span>Inherit images</span>
                      </label>
                    )}

                    {color.hasSize ? (
                      <div className="mt-2 space-y-2">
                        {color.sizes.map((size, sizeIndex) => (
                          <div
                            key={sizeIndex}
                            className="space-y-2 rounded-md border p-2"
                          >
                            <input
                              type="text"
                              value={size.name}
                              onChange={(e) =>
                                handleSizeChange(
                                  colorIndex,
                                  sizeIndex,
                                  "name",
                                  e.target.value,
                                )
                              }
                              className="w-full rounded-md border p-2"
                              placeholder="Size name"
                            />
                            <div className="flex space-x-2">
                              <input
                                type="number"
                                value={size.price}
                                onChange={(e) =>
                                  handleSizeChange(
                                    colorIndex,
                                    sizeIndex,
                                    "price",
                                    e.target.value,
                                  )
                                }
                                className="w-1/2 rounded-md border p-2"
                                placeholder="Price"
                              />
                              <input
                                type="number"
                                value={size.qty}
                                onChange={(e) =>
                                  handleSizeChange(
                                    colorIndex,
                                    sizeIndex,
                                    "qty",
                                    e.target.value,
                                  )
                                }
                                className="w-1/2 rounded-md border p-2"
                                placeholder="Quantity"
                              />
                            </div>
                            {sizeIndex > 0 && (
                              <label className="flex items-center">
                                <input
                                  type="checkbox"
                                  checked={size.inheritImages}
                                  onChange={() =>
                                    handleInheritImagesChange(
                                      "size",
                                      colorIndex,
                                      sizeIndex,
                                    )
                                  }
                                  className="mr-1"
                                />
                                <span>Inherit images</span>
                              </label>
                            )}
                            {!size.inheritImages && (
                              <MultipartFileUploader
                                onUploadSuccess={(fileIds) =>
                                  handleImageUpload(
                                    fileIds,
                                    "size",
                                    colorIndex,
                                    sizeIndex,
                                  )
                                }
                              />
                            )}
                          </div>
                        ))}
                        <button
                          type="button"
                          onClick={() => handleAddSize(colorIndex)}
                          className="mt-2 rounded-md bg-blue-500 px-2 py-1 text-white hover:bg-blue-600"
                        >
                          Add Size
                        </button>
                      </div>
                    ) : (
                      <div className="mt-2 space-y-2">
                        <div className="flex space-x-2">
                          <input
                            type="number"
                            value={color.price}
                            onChange={(e) =>
                              handleColorChange(
                                colorIndex,
                                "price",
                                e.target.value,
                              )
                            }
                            className="w-1/2 rounded-md border p-2"
                            placeholder="Price"
                          />
                          <input
                            type="number"
                            value={color.qty}
                            onChange={(e) =>
                              handleColorChange(
                                colorIndex,
                                "qty",
                                e.target.value,
                              )
                            }
                            className="w-1/2 rounded-md border p-2"
                            placeholder="Quantity"
                          />
                        </div>
                        {!color.inheritImages && (
                          <MultipartFileUploader
                            onUploadSuccess={(fileIds) =>
                              handleImageUpload(fileIds, "color", colorIndex)
                            }
                          />
                        )}
                      </div>
                    )}
                  </div>
                ))}
              </div>
              <button
                type="button"
                onClick={handleAddColor}
                className="mt-2 rounded-md bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
              >
                <Plus className="mr-1 inline-block" size={16} />
                Add Color
              </button>
            </div>
          )}

          {/* Has Size (when no color) */}
          {!product.hasColor && (
            <div>
              <label className="flex items-center">
                <input
                  type="checkbox"
                  checked={product.hasSize}
                  onChange={handleSizeToggle}
                  className="mr-2"
                />
                <span className="font-bold">Has Size?</span>
              </label>
            </div>
          )}

          {/* Sizes (when no color) */}
          {!product.hasColor && product.hasSize && (
            <div>
              <label className="mb-2 block font-bold">Sizes</label>
              <div className="space-y-2">
                {product.sizes.map((size, index) => (
                  <div key={index} className="space-y-2 rounded-md border p-2">
                    <input
                      type="text"
                      value={size.name}
                      onChange={(e) =>
                        handleSizeChange(-1, index, "name", e.target.value)
                      }
                      className="w-full rounded-md border p-2"
                      placeholder="Size name"
                    />
                    <div className="flex space-x-2">
                      <input
                        type="number"
                        value={size.price}
                        onChange={(e) =>
                          handleSizeChange(-1, index, "price", e.target.value)
                        }
                        className="w-1/2 rounded-md border p-2"
                        placeholder="Price"
                      />
                      <input
                        type="number"
                        value={size.qty}
                        onChange={(e) =>
                          handleSizeChange(-1, index, "qty", e.target.value)
                        }
                        className="w-1/2 rounded-md border p-2"
                        placeholder="Quantity"
                      />
                    </div>
                    {index > 0 && (
                      <label className="flex items-center">
                        <input
                          type="checkbox"
                          checked={size.inheritImages}
                          onChange={() =>
                            handleInheritImagesChange("size", -1, index)
                          }
                          className="mr-1"
                        />
                        <span>Inherit images</span>
                      </label>
                    )}
                    {!size.inheritImages && (
                      <MultipartFileUploader
                        onUploadSuccess={(fileIds) =>
                          handleImageUpload(fileIds, "size", -1, index)
                        }
                      />
                    )}
                  </div>
                ))}
                <button
                  type="button"
                  onClick={() => handleAddSize(-1)}
                  className="rounded-md bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
                >
                  <Plus className="mr-1 inline-block" size={16} />
                  Add Size
                </button>
              </div>
            </div>
          )}

          {/* Product Details (when no color and no size) */}
          {!product.hasColor && !product.hasSize && (
            <div>
              <label className="mb-2 block font-bold">Product Details</label>
              <div className="flex items-center space-x-2">
                <input
                  type="number"
                  value={product.price}
                  onChange={(e) =>
                    handleInputChange({
                      target: { name: "price", value: e.target.value },
                    })
                  }
                  className="rounded-md border p-2"
                  placeholder="Price"
                />
                <input
                  type="number"
                  value={product.qty}
                  onChange={(e) =>
                    handleInputChange({
                      target: { name: "qty", value: e.target.value },
                    })
                  }
                  className="rounded-md border p-2"
                  placeholder="Quantity"
                />
              </div>
              <div className="mt-2">
                <MultipartFileUploader
                  onUploadSuccess={(fileIds) =>
                    handleImageUpload(fileIds, "product")
                  }
                />
              </div>
            </div>
          )}

          <div className="flex justify-end">
            <button
              disabled={isSubmitting}
              type="submit"
              className="rounded-md bg-green-500 px-4 py-2 text-white hover:bg-green-600"
            >
              Add Product
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
backend:
"use client";
import React, { useState, useEffect } from "react";
import { X, Plus } from "lucide-react";
import { MultipartFileUploader } from "@/components/MultipartFileUploader";
import { toast } from "react-toastify";
import { getToken } from "@/app/auth";

export default function AddProductDialog({ isOpen, onClose }) {
  const [product, setProduct] = useState({
    name: "",
    description: "",
    category: "",
    subcategory: "",
    brand: "",
    hasColor: false,
    colors: [],
    hasSize: false,
    sizes: [],
    categories: [],
    price: "",
    qty: "",
    images: [],
  });

  const [categories, setCategories] = useState([]);
  const [brands, setBrands] = useState([]);

  useEffect(() => {
    fetchCategories();
    fetchBrands();
  }, []);

  const fetchCategories = async () => {
    try {
      const token = getToken(); // Retrieve the token from localStorage

      if (!token) {
        toast.error("You must be logged in to add a product.");
        return;
      }
      const response = await fetch(
        "http://localhost:4000/subcategories/non-brands",
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`, // Include the token here
          },
        },
      );
      const data = await response.json();
      setCategories(data);
    } catch (error) {
      console.error("Error fetching categories:", error);
    }
  };

  const fetchBrands = async () => {
    try {
      const token = getToken(); // Retrieve the token from localStorage

      if (!token) {
        toast.error("You must be logged in to add a product.");
        return;
      }
      const response = await fetch(
        "http://localhost:4000/subcategories/brands",
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`, // Include the token here
          },
        },
      );
      const data = await response.json();
      setBrands(data);
    } catch (error) {
      console.error("Error fetching brands:", error);
    }
  };

  const handleCategoryToggle = (categoryId) => {
    setProduct((prevProduct) => {
      const updatedCategories = prevProduct.categories.includes(categoryId)
        ? prevProduct.categories.filter((id) => id !== categoryId)
        : [...prevProduct.categories, categoryId];
      return { ...prevProduct, categories: updatedCategories };
    });
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setProduct((prevProduct) => ({
      ...prevProduct,
      [name]: value,
    }));
  };
  useEffect(() => {
    console.log("Updated product state:", product);
  }, [product]);
  const handleColorToggle = () => {
    setProduct({ ...product, hasColor: !product.hasColor, colors: [] });
  };

  const handleBrandChange = (e) => {
    setProduct({ ...product, brand: e.target.value });
  };

  const handleSizeToggle = () => {
    setProduct({
      ...product,
      hasSize: !product.hasSize,
      sizes: !product.hasSize ? [] : product.sizes,
    });
  };
  const [isSubmitting, setIsSubmitting] = useState(false); // Start submission]
  const handleAddColor = () => {
    setProduct((prevProduct) => {
      const newColor = {
        name: "",
        hasSize: false,
        sizes: [],
        price: "",
        qty: "",
        images: [],
        inheritImages: false,
      };

      return {
        ...prevProduct,
        colors: [...prevProduct.colors, newColor],
      };
    });
  };

  const handleColorChange = (index, field, value) => {
    setProduct((prevProduct) => {
      const newColors = [...prevProduct.colors];
      newColors[index] = {
        ...newColors[index],
        [field]: value,
      };
      return { ...prevProduct, colors: newColors };
    });
  };

  const handleColorSizeToggle = (colorIndex) => {
    const newColors = [...product.colors];
    newColors[colorIndex].hasSize = !newColors[colorIndex].hasSize;
    newColors[colorIndex].sizes = [];
    setProduct({ ...product, colors: newColors });
  };

  const handleAddSize = (colorIndex) => {
    setProduct((prevProduct) => {
      if (colorIndex === -1) {
        const newSize = {
          name: "",
          images: [],
          price: "",
          qty: "",
          inheritImages: false,
        };
        return {
          ...prevProduct,
          sizes: [...prevProduct.sizes, newSize],
        };
      } else {
        const newColors = [...prevProduct.colors];
        const newSize = {
          name: "",
          images: [],
          price: "",
          qty: "",
          inheritImages: false,
        };
        newColors[colorIndex] = {
          ...newColors[colorIndex],
          sizes: [...newColors[colorIndex].sizes, newSize],
        };
        return {
          ...prevProduct,
          colors: newColors,
        };
      }
    });
  };

  const handleSizeChange = (colorIndex, sizeIndex, field, value) => {
    setProduct((prevProduct) => {
      if (colorIndex === -1) {
        const newSizes = [...prevProduct.sizes];
        newSizes[sizeIndex] = {
          ...newSizes[sizeIndex],
          [field]: value,
        };
        return { ...prevProduct, sizes: newSizes };
      } else {
        const newColors = [...prevProduct.colors];
        newColors[colorIndex].sizes[sizeIndex] = {
          ...newColors[colorIndex].sizes[sizeIndex],
          [field]: value,
        };
        return { ...prevProduct, colors: newColors };
      }
    });
  };

  const handleImageUpload = (fileIds, variantType, colorIndex, sizeIndex) => {
    const formattedImages = fileIds.map((url) => ({ url }));

    setProduct((prevProduct) => {
      let updatedProduct = { ...prevProduct };

      if (variantType === "color") {
        updatedProduct.colors[colorIndex].images = formattedImages;
      } else if (variantType === "size") {
        if (colorIndex === -1) {
          updatedProduct.sizes[sizeIndex].images = formattedImages;
        } else {
          updatedProduct.colors[colorIndex].sizes[sizeIndex].images =
            formattedImages;
        }
      } else {
        updatedProduct.images = formattedImages;
      }

      return updatedProduct;
    });
  };
  const handleInheritImagesChange = (variantType, colorIndex, sizeIndex) => {
    setProduct((prevProduct) => {
      let updatedProduct = JSON.parse(JSON.stringify(prevProduct)); // Deep clone

      if (variantType === "color") {
        updatedProduct.colors[colorIndex].inheritImages =
          !updatedProduct.colors[colorIndex].inheritImages;

        if (updatedProduct.colors[colorIndex].inheritImages && colorIndex > 0) {
          const prevColor = updatedProduct.colors[colorIndex - 1];
          updatedProduct.colors[colorIndex].images = [...prevColor.images];
        }
      } else if (variantType === "size") {
        if (colorIndex === -1) {
          updatedProduct.sizes[sizeIndex].inheritImages =
            !updatedProduct.sizes[sizeIndex].inheritImages;

          if (updatedProduct.sizes[sizeIndex].inheritImages && sizeIndex > 0) {
            const prevSize = updatedProduct.sizes[sizeIndex - 1];
            updatedProduct.sizes[sizeIndex].images = [...prevSize.images];
          }
        } else {
          updatedProduct.colors[colorIndex].sizes[sizeIndex].inheritImages =
            !updatedProduct.colors[colorIndex].sizes[sizeIndex].inheritImages;

          if (
            updatedProduct.colors[colorIndex].sizes[sizeIndex].inheritImages &&
            sizeIndex > 0
          ) {
            const prevSize =
              updatedProduct.colors[colorIndex].sizes[sizeIndex - 1];
            updatedProduct.colors[colorIndex].sizes[sizeIndex].images = [
              ...prevSize.images,
            ];
          }
        }
      }

      return updatedProduct;
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);
    // Determine if any color has sizes
    const colorsHaveSizes =
      product.hasColor &&
      product.colors.some((color) => color.hasSize && color.sizes.length > 0);

    // Determine productType based on the presence of colors and sizes
    let productType;
    if (colorsHaveSizes) {
      productType = "color_size";
    } else if (product.hasColor) {
      productType = "color";
    } else if (product.hasSize) {
      productType = "size";
    } else {
      productType = "simple";
    }

    // Construct productData without using ||
    const productData = {
      name: product.name,
      description: product.description,
      brand_id: parseInt(product.brand, 10),
      has_color: product.hasColor,
      has_size: product.hasSize,
      product_type: productType,
      category_ids: product.categories,
      colors: product.colors.map((color) => ({
        name: color.name,
        images: color.images,
        has_size: color.hasSize,
        sizes: color.hasSize
          ? color.sizes.map((size) => ({
              name: size.name,
              price: parseFloat(size.price),
              qty: parseInt(size.qty, 10) || 0,
              images: size.images,
            }))
          : [],
        price: parseFloat(color.price),
        qty: parseInt(color.qty, 10) || 0,
      })),
      sizes: !product.hasColor
        ? product.sizes.map((size) => ({
            name: size.name,
            price: parseFloat(size.price),
            qty: parseInt(size.qty, 10) || 0,
            images: size.images,
          }))
        : [],
      price: parseFloat(product.price),
      qty: parseInt(product.qty, 10) || 0,
      images: product.images,
    };
    console.log(productData);
    try {
      const token = getToken(); // Retrieve the token from localStorage

      if (!token) {
        setIsSubmitting(true); // Start submission
        toast.error("You must be logged in to add a product.");
        return;
      }

      const response = await fetch("http://localhost:4000/products", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`, // Include the token here
        },
        body: JSON.stringify(productData),
      });

      if (!response.ok) {
        setIsSubmitting(true); // Start submission
        const errorData = await response.json();
        throw new Error(errorData.message || "Failed to create product");
      }

      // Reset the form after successful submission
      setProduct({
        name: "",
        description: "",
        category: "",
        subcategory: "",
        brand: "",
        hasColor: false,
        colors: [],
        hasSize: false,
        sizes: [],
        categories: [],
        price: "",
        qty: "",
        images: [],
      });

      toast.success("Product added successfully!");
      onClose();
    } catch (error) {
      console.error("Error creating product:", error);
      setIsSubmitting(true); // Start submission
      toast.error("Failed to add product. Please try again.");
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[99999999] flex h-screen transform items-center justify-center overflow-y-scroll bg-black bg-opacity-50">
      <div className="relative h-screen w-full max-w-2xl overflow-y-scroll rounded-lg bg-white p-8">
        <button
          onClick={onClose}
          className="absolute right-4 top-4 text-gray-500 hover:text-gray-700"
        >
          <X size={24} />
        </button>

        <h2 className="mb-6 text-2xl font-bold">Add New Product</h2>

        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Product Name */}
          <div>
            <label className="mb-2 block font-bold" htmlFor="name">
              Product Name
            </label>
            <input
              type="text"
              id="name"
              name="name"
              value={product.name}
              onChange={handleInputChange}
              className="w-full rounded-md border p-2"
              required
            />
          </div>

          {/* Description */}
          <div>
            <label className="mb-2 block font-bold" htmlFor="description">
              Description
            </label>
            <textarea
              id="description"
              name="description"
              value={product.description}
              onChange={handleInputChange}
              className="w-full rounded-md border p-2"
              style={{ direction: "rtl" }}
              required
            />
          </div>

          {/* Categories */}
          <div>
            <label className="mb-2 block font-bold">Categories</label>
            <div className="flex flex-wrap gap-2">
              {categories.map((category) => (
                <button
                  key={category.id}
                  type="button"
                  onClick={() => handleCategoryToggle(category.id)}
                  className={`rounded-full px-3 py-1 text-sm ${
                    product.categories.includes(category.id)
                      ? "bg-blue-500 text-white"
                      : "bg-gray-200 text-gray-700"
                  }`}
                >
                  {category.name}
                </button>
              ))}
            </div>
          </div>

          {/* Brand */}
          <div>
            <label className="mb-2 block font-bold" htmlFor="brand">
              Brand
            </label>
            <select
              id="brand"
              name="brand"
              value={product.brand}
              onChange={handleBrandChange}
              className="w-full rounded-md border p-2"
              required
            >
              <option value="">Select a brand</option>
              {brands.map((brand) => (
                <option key={brand.id} value={brand.id}>
                  {brand.name}
                </option>
              ))}
            </select>
          </div>

          {/* Has Color */}
          <div>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={product.hasColor}
                onChange={handleColorToggle}
                className="mr-2"
              />
              <span className="font-bold">Has Color?</span>
            </label>
          </div>

          {/* Colors */}
          {product.hasColor && (
            <div>
              <label className="mb-2 block font-bold">Colors</label>
              <div className="space-y-4">
                {product.colors.map((color, colorIndex) => (
                  <div key={colorIndex} className="rounded-md border p-4">
                    <input
                      type="text"
                      value={color.name}
                      onChange={(e) =>
                        handleColorChange(colorIndex, "name", e.target.value)
                      }
                      className="mb-2 rounded-md border p-2"
                      placeholder="Color name"
                    />

                    <label className="ml-2 flex items-center">
                      <input
                        type="checkbox"
                        checked={color.hasSize}
                        onChange={() => handleColorSizeToggle(colorIndex)}
                        className="mr-1"
                      />
                      <span>Has Size?</span>
                    </label>

                    {colorIndex > 0 && (
                      <label className="ml-2 flex items-center">
                        <input
                          type="checkbox"
                          checked={color.inheritImages}
                          onChange={() =>
                            handleInheritImagesChange("color", colorIndex)
                          }
                          className="mr-1"
                        />
                        <span>Inherit images</span>
                      </label>
                    )}

                    {color.hasSize ? (
                      <div className="mt-2 space-y-2">
                        {color.sizes.map((size, sizeIndex) => (
                          <div
                            key={sizeIndex}
                            className="space-y-2 rounded-md border p-2"
                          >
                            <input
                              type="text"
                              value={size.name}
                              onChange={(e) =>
                                handleSizeChange(
                                  colorIndex,
                                  sizeIndex,
                                  "name",
                                  e.target.value,
                                )
                              }
                              className="w-full rounded-md border p-2"
                              placeholder="Size name"
                            />
                            <div className="flex space-x-2">
                              <input
                                type="number"
                                value={size.price}
                                onChange={(e) =>
                                  handleSizeChange(
                                    colorIndex,
                                    sizeIndex,
                                    "price",
                                    e.target.value,
                                  )
                                }
                                className="w-1/2 rounded-md border p-2"
                                placeholder="Price"
                              />
                              <input
                                type="number"
                                value={size.qty}
                                onChange={(e) =>
                                  handleSizeChange(
                                    colorIndex,
                                    sizeIndex,
                                    "qty",
                                    e.target.value,
                                  )
                                }
                                className="w-1/2 rounded-md border p-2"
                                placeholder="Quantity"
                              />
                            </div>
                            {sizeIndex > 0 && (
                              <label className="flex items-center">
                                <input
                                  type="checkbox"
                                  checked={size.inheritImages}
                                  onChange={() =>
                                    handleInheritImagesChange(
                                      "size",
                                      colorIndex,
                                      sizeIndex,
                                    )
                                  }
                                  className="mr-1"
                                />
                                <span>Inherit images</span>
                              </label>
                            )}
                            {!size.inheritImages && (
                              <MultipartFileUploader
                                onUploadSuccess={(fileIds) =>
                                  handleImageUpload(
                                    fileIds,
                                    "size",
                                    colorIndex,
                                    sizeIndex,
                                  )
                                }
                              />
                            )}
                          </div>
                        ))}
                        <button
                          type="button"
                          onClick={() => handleAddSize(colorIndex)}
                          className="mt-2 rounded-md bg-blue-500 px-2 py-1 text-white hover:bg-blue-600"
                        >
                          Add Size
                        </button>
                      </div>
                    ) : (
                      <div className="mt-2 space-y-2">
                        <div className="flex space-x-2">
                          <input
                            type="number"
                            value={color.price}
                            onChange={(e) =>
                              handleColorChange(
                                colorIndex,
                                "price",
                                e.target.value,
                              )
                            }
                            className="w-1/2 rounded-md border p-2"
                            placeholder="Price"
                          />
                          <input
                            type="number"
                            value={color.qty}
                            onChange={(e) =>
                              handleColorChange(
                                colorIndex,
                                "qty",
                                e.target.value,
                              )
                            }
                            className="w-1/2 rounded-md border p-2"
                            placeholder="Quantity"
                          />
                        </div>
                        {!color.inheritImages && (
                          <MultipartFileUploader
                            onUploadSuccess={(fileIds) =>
                              handleImageUpload(fileIds, "color", colorIndex)
                            }
                          />
                        )}
                      </div>
                    )}
                  </div>
                ))}
              </div>
              <button
                type="button"
                onClick={handleAddColor}
                className="mt-2 rounded-md bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
              >
                <Plus className="mr-1 inline-block" size={16} />
                Add Color
              </button>
            </div>
          )}

          {/* Has Size (when no color) */}
          {!product.hasColor && (
            <div>
              <label className="flex items-center">
                <input
                  type="checkbox"
                  checked={product.hasSize}
                  onChange={handleSizeToggle}
                  className="mr-2"
                />
                <span className="font-bold">Has Size?</span>
              </label>
            </div>
          )}

          {/* Sizes (when no color) */}
          {!product.hasColor && product.hasSize && (
            <div>
              <label className="mb-2 block font-bold">Sizes</label>
              <div className="space-y-2">
                {product.sizes.map((size, index) => (
                  <div key={index} className="space-y-2 rounded-md border p-2">
                    <input
                      type="text"
                      value={size.name}
                      onChange={(e) =>
                        handleSizeChange(-1, index, "name", e.target.value)
                      }
                      className="w-full rounded-md border p-2"
                      placeholder="Size name"
                    />
                    <div className="flex space-x-2">
                      <input
                        type="number"
                        value={size.price}
                        onChange={(e) =>
                          handleSizeChange(-1, index, "price", e.target.value)
                        }
                        className="w-1/2 rounded-md border p-2"
                        placeholder="Price"
                      />
                      <input
                        type="number"
                        value={size.qty}
                        onChange={(e) =>
                          handleSizeChange(-1, index, "qty", e.target.value)
                        }
                        className="w-1/2 rounded-md border p-2"
                        placeholder="Quantity"
                      />
                    </div>
                    {index > 0 && (
                      <label className="flex items-center">
                        <input
                          type="checkbox"
                          checked={size.inheritImages}
                          onChange={() =>
                            handleInheritImagesChange("size", -1, index)
                          }
                          className="mr-1"
                        />
                        <span>Inherit images</span>
                      </label>
                    )}
                    {!size.inheritImages && (
                      <MultipartFileUploader
                        onUploadSuccess={(fileIds) =>
                          handleImageUpload(fileIds, "size", -1, index)
                        }
                      />
                    )}
                  </div>
                ))}
                <button
                  type="button"
                  onClick={() => handleAddSize(-1)}
                  className="rounded-md bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
                >
                  <Plus className="mr-1 inline-block" size={16} />
                  Add Size
                </button>
              </div>
            </div>
          )}

          {/* Product Details (when no color and no size) */}
          {!product.hasColor && !product.hasSize && (
            <div>
              <label className="mb-2 block font-bold">Product Details</label>
              <div className="flex items-center space-x-2">
                <input
                  type="number"
                  value={product.price}
                  onChange={(e) =>
                    handleInputChange({
                      target: { name: "price", value: e.target.value },
                    })
                  }
                  className="rounded-md border p-2"
                  placeholder="Price"
                />
                <input
                  type="number"
                  value={product.qty}
                  onChange={(e) =>
                    handleInputChange({
                      target: { name: "qty", value: e.target.value },
                    })
                  }
                  className="rounded-md border p-2"
                  placeholder="Quantity"
                />
              </div>
              <div className="mt-2">
                <MultipartFileUploader
                  onUploadSuccess={(fileIds) =>
                    handleImageUpload(fileIds, "product")
                  }
                />
              </div>
            </div>
          )}

          <div className="flex justify-end">
            <button
              disabled={isSubmitting}
              type="submit"
              className="rounded-md bg-green-500 px-4 py-2 text-white hover:bg-green-600"
            >
              Add Product
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}