"use client";

import { useState, useEffect, useMemo, useRef } from "react";
import { Button } from "../../../../../src/components/ui/button";
import { Input } from "../../../../../src/components/ui/input";
import { Label } from "../../../../../src/components/ui/label";
import { Textarea } from "../../../../../src/components/ui/textarea";
import { Switch } from "../../../../../src/components/ui/switch";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../../../../../src/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "../../../../../src/components/ui/dialog";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../../../../../src/components/ui/table";
import { Badge } from "../../../../../src/components/ui/badge";
import {
  Plus,
  Edit,
  Trash2,
  X,
  Upload,
  Search,
  ChevronLeft,
  ChevronRight,
  Eye,
  Package,
  Image as ImageIcon,
  ChevronDown,
  ChevronUp,
  ArrowUp,
  ArrowDown,
  ArrowUpDown,
} from "lucide-react";
import { toast } from "sonner";
import Editor from "../../../../../src/app/admin/_components/editor/Editor";
import { Tooltip } from "../../../../../src/components/ui/tooltip";
import { useDebounce } from "../../../../../src/hooks/useDebounce";
import { SwitchThumb } from "@radix-ui/react-switch";
import ImagePreviewModal from "../../../../../src/components/ImagePreview/ImagePreviewer";
import { set } from "mongoose";
import { Interweave } from "interweave";
import ViewStocks from "./ViewStocks";

interface Category {
  _id: string;
  name: string;
  slug: string;
}

interface Color {
  _id: string;
  name: string;
  hexCode: string;
}

interface Size {
  _id: string;
  name: string;
}

interface Product {
  _id: string;
  name: string;
  slug: string;
  description: string;
  shortDescription?: string;
  category: Category;
  subcategory?: Category;
  productprice?: number;
  price: number;
  defaultImage?: string;
  weight: number;
  dimensions: {
    length: number;
    width: number;
    height: number;
  };
  isActive: boolean;
  isFeatured: boolean;
  createdAt: string;
  updatedAt: string;
}

interface ProductSKU {
  _id: string;
  product: string;
  sku: string;
  color: Color;
  size: Size;
  quantity: number;

  price: number;
  comparePrice?: number;
}

interface ProductColorImage {
  _id: string;
  product: string;
  color: Color;
  images: {
    url: string;
    altText?: string;
    sortOrder: number;
    isPrimary: boolean;
  }[];
}

export default function ProductsManagement() {
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [subCategories, setSubCategories] = useState<Category[]>([]);
  const [colors, setColors] = useState<Color[]>([]);
  const [sizes, setSizes] = useState<Size[]>([]);
  const [loading, setLoading] = useState(true);
  const [isAddEditDialogOpen, setIsAddEditDialogOpen] = useState(false);
  const [isViewDialogOpen, setIsViewDialogOpen] = useState(false);
  const [isSKUDialogOpen, setIsSKUDialogOpen] = useState(false);
  const [isImageDialogOpen, setIsImageDialogOpen] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [viewingProduct, setViewingProduct] = useState<Product | null>(null);
  const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [sortField, setSortField] = useState<"name" | "createdAt" | "category">(
    "createdAt",
  );
  const [sortOrder, setSortOrder] = useState<"desc" | "asc">("desc");
  const [selectedColors, setSelectedColors] = useState<string[]>([]);
  const [activeIndex, setActiveIndex] = useState(0);
  const [open, setOpen] = useState(false);
  const openPreview = (index: number) => {
    setActiveIndex(index);
    setOpen(true);
  };
  const [pagination, setPagination] = useState({
    total: 0,
    pages: 0,
    page: 1,
    limit: 10,
  });

  // Collapsible state for SKU form
  const [isSKUFormOpen, setIsSKUFormOpen] = useState(false);

  // SKU management states
  const [skus, setSkus] = useState<ProductSKU[]>([]);
  const [editingSKU, setEditingSKU] = useState<ProductSKU | null>(null);
  const [skuForm, setSkuForm] = useState({
    color: "",
    size: "",
    sku: "",
    quantity: 0,
    price: 0,
    comparePrice: 0,
  });
  const [skuSort, setSkuSort] = useState<{
    field: string;
    order: "asc" | "desc";
  }>({ field: "", order: "asc" });
  const [viewStocksOpen, setViewStocksOpen] = useState(false);

  // Color Image management states
  const [colorImages, setColorImages] = useState<ProductColorImage[]>([]);
  const [imageFiles, setImageFiles] = useState<File[]>([]);
  const [selectedColor, setSelectedColor] = useState<string>();
  const [isImageUploadOpen, setIsImageUploadOpen] = useState(false);
  const [displayColors, setDisplayColors] = useState<Color[]>([]);
  const fileInputRef = useRef<HTMLInputElement | null>(null);

  // Product form state
  const [productForm, setProductForm] = useState({
    name: "",
    description: "",
    shortDescription: "",
    category: "",
    subcategory: "",
    productprice: 0,
    price: "",
    weight: "0",
    dimensions: {
      length: "0",
      width: "0",
      height: "0",
    },
    defaultImage: null as File | null,
    existingImage: "",
    isActive: true,
    isFeatured: false,
  });

  const debouncedSearch = useDebounce(search, 500);

  // Fetch data
  useEffect(() => {
    fetchData();
  }, [debouncedSearch, page, limit, sortField, sortOrder]);

  const fetchData = async () => {
    try {
      setLoading(true);

      const params = new URLSearchParams({
        page: page.toString(),
        limit: limit.toString(),
        sort: sortField,
        order: sortOrder,
        ...(debouncedSearch && { search: debouncedSearch }),
      });

      const [productsRes, categoriesRes, subCategoryRes, colorsRes, sizesRes] =
        await Promise.all([
          fetch(`/api/products?${params}`),
          fetch("/api/categories?level=1&limit=100"),
          fetch("/api/categories?level=2&limit=100"),
          fetch("/api/colors"),
          fetch("/api/sizes"),
        ]);

      const [
        productsData,
        categoriesData,
        subCategoriesData,
        colorsData,
        sizesData,
      ] = await Promise.all([
        productsRes.json(),
        categoriesRes.json(),
        subCategoryRes.json(),
        colorsRes.json(),
        sizesRes.json(),
      ]);

      if (productsData.success) {
        setProducts(productsData.data);
        setPagination(
          productsData.pagination || {
            total: productsData.data.length,
            pages: 1,
            page,
            limit,
          },
        );
      }
      if (categoriesData.success) setCategories(categoriesData.data);
      if (subCategoriesData.success) setSubCategories(subCategoriesData.data);
      if (colorsData.success) setDisplayColors(colorsData.data);
      if (sizesData.success) setSizes(sizesData.data);
    } catch (error) {
      console.error("Error fetching data:", error);
      toast.error("Failed to load data");
    } finally {
      setLoading(false);
    }
  };

  const handleLimitChange = (value: string) => {
    const newLimit = parseInt(value);
    setLimit(newLimit);
    setPage(1);
  };

  const handleSort = (field: "name" | "createdAt" | "category") => {
    if (sortField === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortField(field);
      if (field === "name") {
        setSortOrder("asc");
      } else if (field === "category") {
        setSortOrder("asc");
      } else {
        setSortOrder("desc");
      }
    }
    setPage(1);
  };

  const fetchSKUs = async (productId: string) => {
    try {
      const response = await fetch(`/api/product-skus?productId=${productId}`);
      const data = await response.json();
      if (data.success) setSkus(data.data);
      else toast.error("Failed to fetch SKUs");
    } catch (error) {
      console.error("Error fetching SKUs:", error);
      toast.error("Failed to fetch SKUs");
    }
  };

  const sortedSkus = useMemo(() => {
    if (!skuSort.field) return skus;
    return [...skus].sort((a, b) => {
      let aVal: any;
      let bVal: any;

      switch (skuSort.field) {
        case "color":
          aVal = a.color.name;
          bVal = b.color.name;
          break;
        case "size":
          aVal = a.size.name;
          bVal = b.size.name;
          break;
        case "sku":
          aVal = a.sku;
          bVal = b.sku;
          break;
        case "price":
          aVal = a.price;
          bVal = b.price;
          break;
        default:
          return 0;
      }

      if (typeof aVal === "string") {
        return skuSort.order === "asc"
          ? aVal.localeCompare(bVal)
          : bVal.localeCompare(aVal);
      }
      return skuSort.order === "asc" ? aVal - bVal : bVal - aVal;
    });
  }, [skus, skuSort]);

  const handleSkuSort = (field: string) => {
    setSkuSort((prev) =>
      prev.field === field
        ? { field, order: prev.order === "asc" ? "desc" : "asc" }
        : { field, order: "asc" },
    );
  };

  const fetchColorImages = async (productId: string) => {
    try {
      // Fetch both endpoints in parallel for better performance
      const [colorImagesRes, skusRes] = await Promise.all([
        fetch(`/api/product-color-images?productId=${productId}`),
        fetch(`/api/product-skus?productId=${productId}`),
      ]);

      const colorImagesData = await colorImagesRes.json();
      const skusData = await skusRes.json();

      // Set color images if successful
      if (colorImagesData.success) {
        setColorImages(colorImagesData.data);
      } else {
        toast.error("Failed to fetch color images");
      }

      // Extract unique colors from SKUs
      if (skusData.success && skusData.data.length > 0) {
        // Use Map to get unique colors
        const uniqueColorsMap = new Map();
        skusData.data.forEach((sku: ProductSKU) => {
          if (sku.color && !uniqueColorsMap.has(sku.color._id)) {
            uniqueColorsMap.set(sku.color._id, sku.color);
          }
        });
        const uniqueColors = Array.from(uniqueColorsMap.values());
        setColors(uniqueColors);
      } else {
        // No SKUs found, set empty array
        setColors([]);
      }
    } catch (error) {
      console.error("Error fetching color images:", error);
      toast.error("Failed to fetch color images");
    }
  };

  const resetForm = () => {
    setProductForm({
      name: "",
      productprice: 0,
      price: "",
      description: "",
      shortDescription: "",
      category: "",
      subcategory: "",
      weight: "0",
      dimensions: {
        length: "0",
        width: "0",
        height: "0",
      },
      defaultImage: null,
      existingImage: "",
      isActive: true,
      isFeatured: false,
    });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!productForm?.defaultImage && !productForm?.existingImage)
      return toast.error("Product image reqquired");
    try {
      const url = editingProduct
        ? `/api/products/${editingProduct._id}`
        : "/api/products";
      const method = editingProduct ? "PUT" : "POST";

      const formData = new FormData();
      formData.append("name", productForm.name);
      formData.append("description", productForm.description);
      formData.append("shortDescription", productForm.shortDescription);
      formData.append("category", productForm.category);
      if (productForm.subcategory)
        formData.append("subcategory", productForm.subcategory);
      formData.append("productprice", productForm.productprice.toString());
      formData.append("price", productForm.price.toString());
      formData.append("weight", productForm.weight.toString());
      formData.append("length", productForm.dimensions.length.toString());
      formData.append("width", productForm.dimensions.width.toString());
      formData.append("height", productForm.dimensions.height.toString());
      formData.append("isActive", productForm.isActive.toString());
      formData.append("isFeatured", productForm.isFeatured.toString());

      if (productForm.defaultImage) {
        formData.append("defaultImage", productForm.defaultImage);
      } else if (
        editingProduct &&
        productForm.existingImage === "" &&
        !productForm.defaultImage
      ) {
        formData.append("removeImage", "true");
      }
      console.log("formdata is formdata", formData);

      const response = await fetch(url, {
        method,
        body: formData,
      });

      const data = await response.json();

      if (data.success) {
        toast.success(
          editingProduct
            ? "Product updated successfully"
            : "Product created successfully",
        );
        setIsAddEditDialogOpen(false);
        resetForm();
        setEditingProduct(null);
        fetchData();
      } else {
        toast.error(data.error || "Failed to save product");
      }
    } catch (error) {
      console.error("Error saving product:", error);
      toast.error("Failed to save product");
    }
  };

  const handleEdit = (product: Product) => {
    setEditingProduct(product);
    setProductForm({
      name: product.name,
      description: product.description,
      shortDescription: product.shortDescription || "",
      category: product.category._id,
      subcategory: product.subcategory?._id || "",
      productprice: product.productprice || 0,
      price: product.price?.toString() || "",
      weight: product.weight?.toString(),
      dimensions: {
        length: product?.dimensions?.length?.toString(),
        width: product?.dimensions?.width?.toString(),
        height: product?.dimensions?.height?.toString(),
      },
      defaultImage: null,
      existingImage: product.defaultImage || "",
      isActive: product.isActive,
      isFeatured: product.isFeatured,
    });
    setIsAddEditDialogOpen(true);
  };

  const handleView = (product: Product) => {
    setViewingProduct(product);
    setIsViewDialogOpen(true);
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Are you sure you want to delete this product?")) return;

    try {
      const response = await fetch(`/api/products/${id}`, {
        method: "DELETE",
      });

      const data = await response.json();

      if (data.success) {
        toast.success("Product deleted successfully");
        if (products.length === 1 && page > 1) {
          setPage((prev) => prev - 1);
        } else {
          fetchData();
        }
      } else {
        toast.error(data.error || "Failed to delete product");
      }
    } catch (error) {
      console.error("Error deleting product:", error);
      toast.error("Failed to delete product");
    }
  };

  // SKU Management Functions
  const openSKUManager = (product: Product) => {
    setSelectedProduct(product);
    fetchSKUs(product._id);
    setIsSKUFormOpen(false);
    setEditingSKU(null);
    setIsSKUDialogOpen(true);
  };
  const previewImages = useMemo(
    () =>
      products
        .map((item: any) => ({
          src: item.defaultImage, // Changed from 'item.image' to 'item.defaultImage'
          name: item.name,
        }))
        .filter((i) => typeof i.src === "string" && i.src.trim()),
    [products],
  );
  const handleSKUSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    try {
      const url = editingSKU
        ? `/api/product-skus/${editingSKU._id}`
        : "/api/product-skus";
      const method = editingSKU ? "PUT" : "POST";

      const response = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          product: selectedProduct?._id,
          ...skuForm,
        }),
      });

      const data = await response.json();

      if (data.success) {
        toast.success(
          editingSKU ? "SKU updated successfully" : "SKU created successfully",
        );
        resetSKUForm();
        setIsSKUFormOpen(false);
        fetchSKUs(selectedProduct!._id);
      } else {
        toast.error(data.error || "Failed to save SKU");
      }
    } catch (error) {
      console.error("Error saving SKU:", error);
      toast.error("Failed to save SKU");
    }
  };

  const handleEditSKU = (sku: ProductSKU) => {
    setEditingSKU(sku);
    setSkuForm({
      color: sku.color._id,
      size: sku.size._id,
      sku: sku.sku,
      quantity: sku.quantity,
      price: sku.price,
      comparePrice: sku.comparePrice || 0,
    });
    setIsSKUFormOpen(true);
  };

  const handleDeleteSKU = async (id: string) => {
    if (!confirm("Are you sure you want to delete this SKU?")) return;

    try {
      const response = await fetch(`/api/product-skus/${id}`, {
        method: "DELETE",
      });

      const data = await response.json();

      if (data.success) {
        toast.success("SKU deleted successfully");
        fetchSKUs(selectedProduct!._id);
      } else {
        toast.error(data.error || "Failed to delete SKU");
      }
    } catch (error) {
      console.error("Error deleting SKU:", error);
      toast.error("Failed to delete SKU");
    }
  };

  const resetSKUForm = () => {
    setSkuForm({
      color: "",
      size: "",
      sku: "",
      quantity: 0,
      price: 0,
      comparePrice: 0,
    });
    setEditingSKU(null);
  };

  // Color Image Management Functions
  const openImageManager = (product: Product) => {
    setSelectedProduct(product);
    fetchColorImages(product._id);
    setIsImageUploadOpen(false);
    setSelectedColor(undefined);
    setImageFiles([]);
    setIsImageDialogOpen(true);
  };

  const handleImageUpload = async () => {
    if (!selectedColor || imageFiles.length === 0) {
      toast.error("Please select a color and at least one image");
      return;
    }

    try {
      const formData = new FormData();
      formData.append("productId", selectedProduct!._id);
      formData.append("colorId", selectedColor);
      imageFiles.forEach((file) => {
        formData.append("images", file);
      });

      const response = await fetch("/api/product-color-images", {
        method: "POST",
        body: formData,
      });

      const data = await response.json();

      if (data.success) {
        toast.success(`Successfully uploaded ${imageFiles.length} image(s)`);
        setImageFiles([]);
        setSelectedColor(undefined);
        setIsImageUploadOpen(false);
        fetchColorImages(selectedProduct!._id);
      } else {
        toast.error("Failed to upload images");
      }
    } catch (error) {
      console.error("Error uploading images:", error);
      toast.error("Failed to upload images");
    }
  };

  const handleDeleteImage = async (imageId: string, imageUrl: string) => {
    if (!confirm("Are you sure you want to delete this image?")) return;

    try {
      // Pass id as query parameter, not in the path
      const response = await fetch(
        `/api/product-color-images?id=${imageId}&imageUrl=${encodeURIComponent(imageUrl)}`,
        { method: "DELETE" },
      );

      const data = await response.json();

      if (data.success) {
        toast.success("Image deleted successfully");
        fetchColorImages(selectedProduct!._id);
      } else {
        toast.error(data.error || "Failed to delete image");
      }
    } catch (error) {
      console.error("Error deleting image:", error);
      toast.error("Failed to delete image");
    }
  };

  const handleSearch = (value: string) => {
    setSearch(value);
    setPage(1);
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const openChnageViewStock = (open: boolean) => {
    // console.log('Open ^^^^', open)
    setViewStocksOpen(open);
  };

  return (
    <div className="space-y-4">
      {/* Header */}

      {/* View Product Dialog */}
      <Dialog open={isViewDialogOpen} onOpenChange={setIsViewDialogOpen}>
        <DialogContent className="max-w-3xl">
          <div className="mx-auto my-1 flex min-h-[calc(100%-0.5rem)] max-w-lg items-center">
            <div className="relative flex w-full flex-col gap-0 rounded-lg border-0 border-stroke bg-white p-0 text-dark-5 shadow-lg dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              <DialogHeader>
                <DialogTitle>Product Details</DialogTitle>
                <X
                  className="h-6 w-6 cursor-pointer p-1 text-white"
                  onClick={() => {
                    setIsViewDialogOpen(false);
                  }}
                />
              </DialogHeader>

              {viewingProduct && (
                <div className="flex flex-grow flex-col p-4 pb-0 pl-2 pr-2">
                  <div className="max-h-[60vh] min-h-[60vh] flex-1 overflow-y-auto pl-2 pr-2">
                    <div className="space-y-6 pb-4">
                      {viewingProduct.defaultImage && (
                        <div className="flex justify-center">
                          <img
                            src={viewingProduct.defaultImage}
                            alt={viewingProduct.name}
                            className="w-140 h-40 rounded-lg border-2 border-gray-200 object-cover shadow-md"
                          />
                        </div>
                      )}

                      <div className="grid grid-cols-2 gap-4">
                        <div className="space-y-1">
                          <Label className="text-xs text-gray-500">
                            Product Name
                          </Label>
                          <p className="text-base font-medium">
                            {viewingProduct.name}
                          </p>
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs text-gray-500">Slug</Label>
                          <p className="font-mono text-sm">
                            {viewingProduct.slug}
                          </p>
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs text-gray-500">Price</Label>
                          <p className="font-mono text-sm">
                            ₹ {viewingProduct.productprice?.toString() || null}
                          </p>
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs text-gray-500">Price</Label>
                          <p className="font-mono text-sm">
                            ₹ {viewingProduct.price?.toString() || null}
                          </p>
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs text-gray-500">
                            Category
                          </Label>
                          <p className="text-base">
                            {viewingProduct.category?.name}
                          </p>
                        </div>
                        {viewingProduct.subcategory && (
                          <div className="space-y-1">
                            <Label className="text-xs text-gray-500">
                              Subcategory
                            </Label>
                            <p className="text-base">
                              {viewingProduct.subcategory.name}
                            </p>
                          </div>
                        )}
                        <div className="space-y-1">
                          <Label className="mr-2 text-xs text-gray-500">
                            Status
                          </Label>
                          <div className="flex gap-2">
                            {viewingProduct.isActive && (
                              <Badge variant="default" className="text-white">
                                Active
                              </Badge>
                            )}
                            {viewingProduct.isFeatured && (
                              <Badge variant="secondary" className="text-white">
                                Featured
                              </Badge>
                            )}
                          </div>
                        </div>
                      </div>

                      {viewingProduct.description && (
                        <div className="space-y-1">
                          <Label className="text-xs text-gray-500">
                            <Interweave content={viewingProduct.description} />
                          </Label>
                          <p className="whitespace-pre-wrap rounded-lg bg-gray-100 p-3 text-sm dark:bg-gray-500">
                            <Interweave content={viewingProduct.description} />
                          </p>
                        </div>
                      )}

                      {viewingProduct.shortDescription && (
                        <div className="space-y-1">
                          <Label className="text-xs text-gray-500">
                            Short Description
                          </Label>
                          <p className="rounded-lg bg-gray-100 p-3 text-sm dark:bg-gray-500">
                            <Interweave
                              content={viewingProduct.shortDescription}
                            />
                          </p>
                        </div>
                      )}

                      <div className="grid grid-cols-2 gap-4">
                        <div className="space-y-1">
                          <Label className="text-xs text-gray-500">
                            Weight
                          </Label>
                          <p className="text-base">
                            {viewingProduct.weight} kg
                          </p>
                        </div>
                      </div>

                      <div className="space-y-1">
                        <Label className="text-xs text-gray-500">
                          Dimensions (L × W × H)
                        </Label>
                        <p className="text-base">
                          {viewingProduct.dimensions.length} ×{" "}
                          {viewingProduct.dimensions.width} ×{" "}
                          {viewingProduct.dimensions.height} cm
                        </p>
                      </div>

                      <div className="mt-2 border-t pt-2">
                        <div className="grid grid-cols-2 gap-4">
                          <div className="space-y-0.5">
                            <Label className="text-xs text-gray-500">
                              Created At
                            </Label>
                            <p className="text-xs">
                              {formatDate(viewingProduct.createdAt)}
                            </p>
                          </div>
                          <div className="space-y-0.5">
                            <Label className="text-xs text-gray-500">
                              Last Updated
                            </Label>
                            <p className="text-xs">
                              {formatDate(viewingProduct.updatedAt)}
                            </p>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div className="-mx-2 flex justify-end space-x-3 border-t px-4 pb-3 pt-3">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        setIsViewDialogOpen(false);
                        handleEdit(viewingProduct);
                      }}
                    >
                      <Edit className="h-4 w-4" />
                      Edit Product
                    </Button>
                    <Button
                      variant="danger"
                      size="sm"
                      onClick={() => {
                        setIsViewDialogOpen(false);
                        handleDelete(viewingProduct._id);
                      }}
                    >
                      <Trash2 className="h-4 w-4" />
                      Delete Product
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {open && (
        <ImagePreviewModal
          images={previewImages}
          activeIndex={activeIndex}
          setActiveIndex={setActiveIndex}
          onClose={() => setOpen(false)}
        />
      )}

      {/* Search and Pagination Limit Dropdown */}
      <div className="flex flex-col gap-4 py-1 pt-0 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex w-full flex-row gap-4 py-1 pt-0 sm:max-w-[500px] sm:items-center">
          <div className="relative w-full max-w-md">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
            <Input
              placeholder="Search products..."
              value={search}
              onChange={(e) => handleSearch(e.target.value)}
              className="pl-10"
            />
            <X
              className="absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 cursor-pointer text-gray-400"
              onClick={() => handleSearch("")}
            />
          </div>
          {/* PAGINATION LIMIT DROPDOWN */}
          <div className="flex items-center gap-2">
            <Label className="whitespace-nowrap text-sm">Show:</Label>
            <select
              value={limit.toString()}
              onChange={(e) => handleLimitChange(e.target.value)}
              className="border-input focus:ring-ring rounded-md border bg-white px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-[#3B3B3B]"
            >
              <option value="6">6</option>
              <option value="10">10</option>
              <option value="20">20</option>
              <option value="50">50</option>
            </select>
          </div>
        </div>
        <Dialog
          open={isAddEditDialogOpen}
          onOpenChange={setIsAddEditDialogOpen}
        >
          <DialogTrigger asChild>
            <Button
              className="text-white"
              onClick={() => {
                resetForm();
                setEditingProduct(null);
                setIsAddEditDialogOpen(true);
              }}
            >
              <Plus className="h-4 w-4" />
              Add Product
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-4xl">
            <div className="mx-auto my-1 flex min-h-[calc(100%-0.5rem)] max-w-lg items-center">
              <div className="relative flex w-full flex-col gap-0 rounded-lg border-0 border-stroke bg-white p-0 text-dark-5 shadow-lg dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
                <DialogHeader>
                  <DialogTitle>
                    {editingProduct ? "Edit Product" : "Add New Product"}
                  </DialogTitle>
                  <X
                    className="h-6 w-6 cursor-pointer p-1 text-white"
                    onClick={() => {
                      setIsAddEditDialogOpen(false);
                    }}
                  />
                </DialogHeader>

                <form
                  onSubmit={handleSubmit}
                  className="flex flex-1 flex-col p-4 pb-0 pl-2 pr-2"
                >
                  <div className="max-h-[60vh] min-h-[60vh] flex-1 space-y-4 overflow-y-auto pb-4 pl-2 pr-2 pt-2">
                    {/* Basic Information */}
                    <div className="grid gap-3 md:grid-cols-3">
                      <div>
                        <Label className="mb-2 block" htmlFor="name">
                          Product Name <span className="text-red">*</span>
                        </Label>
                        <Input
                          id="name"
                          value={productForm.name}
                          onChange={(e) => {
                            const value = e.target.value;
                            if (
                              /^[a-zA-Z0-9\s\-_,.&()]*$/.test(value) ||
                              value === ""
                            ) {
                              setProductForm((prev) => ({
                                ...prev,
                                name: value,
                              }));
                            }
                          }}
                          pattern="[a-zA-Z0-9\s\-_,.&()]+"
                          title="Product name can only contain letters, numbers, spaces, and basic punctuation (-_,.&())"
                          required
                        />
                        <p className="mt-1 text-xs text-gray-500">
                          Only letters, numbers, spaces, and basic punctuation
                          (-_,.&())
                        </p>
                      </div>
                      <div>
                        <Label className="mb-2 block" htmlFor="category">
                          Category <span className="text-red">*</span>
                        </Label>
                        <select
                          id="category"
                          value={productForm.category}
                          onChange={(e) =>
                            setProductForm((prev) => ({
                              ...prev,
                              category: e.target.value,
                            }))
                          }
                          className="border-input focus:ring-ring w-full rounded-md border bg-white px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-[#3B3B3B]"
                          required
                        >
                          <option value="" disabled>
                            Select category
                          </option>
                          {categories
                            .filter((item: any) => item.isActive)
                            ?.map((category) => (
                              <option key={category._id} value={category._id}>
                                {category.name}
                              </option>
                            ))}
                        </select>
                      </div>
                      <div>
                        <Label className="mb-2 block" htmlFor="category">
                          Subcategory
                        </Label>
                        <select
                          id="subcategory"
                          value={productForm.subcategory}
                          onChange={(e) =>
                            setProductForm((prev) => ({
                              ...prev,
                              subcategory: e.target.value,
                            }))
                          }
                          className="border-input focus:ring-ring w-full rounded-md border bg-white px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-[#3B3B3B]"
                        >
                          <option value="" disabled>
                            Select subcategory
                          </option>
                          {subCategories
                            ?.filter((item: any) => item.isActive)
                            ?.map((subcategory) => (
                              <option
                                key={subcategory._id}
                                value={subcategory._id}
                              >
                                {subcategory.name}
                              </option>
                            ))}
                        </select>
                      </div>
                    </div>

                    <div>
                      <Label className="mb-2 block" htmlFor="description">
                        Description <span className="text-red">*</span>
                      </Label>
                      <Editor
                        value={productForm.description}
                        onChange={(value: any) =>
                          setProductForm((prev) => ({
                            ...prev,
                            description: value,
                          }))
                        }
                        rows={4}
                      />
                    </div>

                    <div>
                      <Label className="mb-2 block" htmlFor="shortDescription">
                        Short Description
                      </Label>
                      <Editor
                        value={productForm.shortDescription}
                        onChange={(value: any) =>
                          setProductForm((prev) => ({
                            ...prev,
                            shortDescription: value,
                          }))
                        }
                        rows={2}
                      />
                    </div>

                    {/* Weight & Dimensions */}
                    <div className="grid flex-1 grid-cols-2 gap-3">
                      <div>
                        <Label className="mb-2 block" htmlFor="weight">
                          Weight (kg) <span className="text-red">*</span>
                        </Label>
                        <Input
                          id="weight"
                          type="number"
                          step="0.01"
                          min={0}
                          value={productForm.weight}
                          onChange={(e) => {
                            const value =
                              e.target.value === ""
                                ? ""
                                : Math.max(
                                    0,
                                    Number(e.target.value),
                                  )?.toString();
                            if (/^\d*\.?\d{0,2}$/.test(value)) {
                              setProductForm((prev) => ({
                                ...prev,
                                weight: value === "" ? "" : value,
                              }));
                            }
                          }}
                          onKeyDown={(e) => {
                            if (e.key === "-" || e.key === "e") {
                              e.preventDefault();
                            }
                          }}
                          required
                        />
                      </div>
                      <div>
                        <Label className="mb-2 block" htmlFor="name">
                          Best Selling Price(₹){" "}
                          <span className="text-red">*</span>
                        </Label>
                        <Input
                          id="name"
                          type="number"
                          value={productForm.productprice}
                          min={0}
                          onChange={(e) => {
                            const value = e.target.value;

                            if (/^\d*\.?\d*$/.test(value) || value === "") {
                              setProductForm((prev) => ({
                                ...prev,
                                productprice: value === "" ? 0 : Number(value),
                              }));
                            }
                          }}
                          pattern="[a-zA-Z0-9\s\-_,.&()]+"
                          title="Product price can only contain numbers and basic punctuation (-_,.&())"
                          required
                        />
                      </div>
                      <div>
                        <Label className="mb-2 block" htmlFor="name">
                          Product Price(₹) <span className="text-red">*</span>
                        </Label>
                        <Input
                          id="name"
                          type="number"
                          value={productForm.price}
                          min={0}
                          onChange={(e) => {
                            const value = e.target.value;
                            if (
                              (/^[a-zA-Z0-9\s\-_,.&()]*$/.test(value) ||
                                value === "") &&
                              Number(value) >= 0
                            ) {
                              setProductForm((prev) => ({
                                ...prev,
                                price: value,
                              }));
                            }
                          }}
                          pattern="[a-zA-Z0-9\s\-_,.&()]+"
                          title="Product price can only contain numbers and basic punctuation (-_,.&())"
                          required
                        />
                      </div>
                    </div>

                    <div>
                      <Label className="mb-2 block">
                        Dimensions (cm) L × W × H{" "}
                        <span className="text-red">*</span>
                      </Label>
                      <div className="mt-2 grid grid-cols-3 gap-4">
                        <Input
                          placeholder="Length"
                          type="number"
                          step="0.01"
                          min="0"
                          value={productForm.dimensions.length}
                          onChange={(e) => {
                            const value =
                              e.target.value === ""
                                ? ""
                                : Math.max(
                                    0,
                                    Number(e.target.value),
                                  ).toString();
                            if (/^\d*\.?\d{0,2}$/.test(value)) {
                              setProductForm((prev) => ({
                                ...prev,
                                dimensions: {
                                  ...prev.dimensions,
                                  length: value === "" ? "" : value,
                                },
                              }));
                            }
                          }}
                          onKeyDown={(e) => {
                            if (e.key === "-" || e.key === "e") {
                              e.preventDefault();
                            }
                          }}
                        />
                        <Input
                          placeholder="Width"
                          type="number"
                          step="0.01"
                          min="0"
                          value={productForm.dimensions.width}
                          onChange={(e) => {
                            const value =
                              e.target.value === ""
                                ? ""
                                : Math.max(
                                    0,
                                    Number(e.target.value),
                                  ).toString();
                            if (/^\d*\.?\d{0,2}$/.test(value)) {
                              setProductForm((prev) => ({
                                ...prev,
                                dimensions: {
                                  ...prev.dimensions,
                                  width: value === "" ? "" : value,
                                },
                              }));
                            }
                          }}
                          onKeyDown={(e) => {
                            if (e.key === "-" || e.key === "e") {
                              e.preventDefault();
                            }
                          }}
                        />
                        <Input
                          placeholder="Height"
                          type="number"
                          step="0.01"
                          min="0"
                          value={productForm.dimensions.height}
                          onChange={(e) => {
                            const value =
                              e.target.value === ""
                                ? ""
                                : Math.max(
                                    0,
                                    Number(e.target.value),
                                  ).toString();
                            if (/^\d*\.?\d{0,2}$/.test(value)) {
                              setProductForm((prev) => ({
                                ...prev,
                                dimensions: {
                                  ...prev.dimensions,
                                  height: value === "" ? "" : value,
                                },
                              }));
                            }
                          }}
                          onKeyDown={(e) => {
                            if (e.key === "-" || e.key === "e") {
                              e.preventDefault();
                            }
                          }}
                        />
                      </div>
                      <p className="mt-1 text-xs text-gray-500">
                        Values must be positive numbers
                      </p>
                    </div>

                    {/* Default Image */}
                    <div className="space-y-2">
                      <Label className="mb-2 block" htmlFor="defaultImage">
                        Default Product Image{" "}
                        <span className="text-red">*</span>
                      </Label>

                      {productForm.existingImage &&
                        !productForm.defaultImage && (
                          <div className="mb-3 rounded-lg border border-gray-200 bg-gray-50 p-3 dark:bg-gray-800">
                            <p className="mb-2 text-xs text-gray-500">
                              Current Image:
                            </p>

                            <div className="relative inline-block dark:bg-gray-800">
                              <img
                                src={productForm.existingImage}
                                alt="Current product"
                                className="h-20 w-20 rounded-lg border border-gray-300 object-cover"
                              />

                              <button
                                type="button"
                                onClick={() => {
                                  setProductForm((prev) => ({
                                    ...prev,
                                    existingImage: "",
                                  }));
                                }}
                                className="absolute -right-2 -top-2 flex h-6 w-6 items-center justify-center rounded-full bg-red-500 text-xs text-white shadow-md transition hover:bg-red-600"
                              >
                                ✕
                              </button>
                            </div>
                          </div>
                        )}

                      {productForm.defaultImage && (
                        <div className="mb-3 rounded-lg border border-green-200 bg-green-50 p-3">
                          <p className="mb-2 text-xs text-green-600">
                            New Image Preview:
                          </p>

                          <div className="relative inline-block">
                            <img
                              src={URL.createObjectURL(
                                productForm.defaultImage,
                              )}
                              alt="Preview"
                              className="h-20 w-20 rounded-lg border border-green-500 object-cover"
                            />

                            <button
                              type="button"
                              onClick={() => {
                                setProductForm((prev) => ({
                                  ...prev,
                                  defaultImage: null,
                                }));
                              }}
                              className="absolute -right-2 -top-2 flex h-5 w-5 items-center justify-center rounded-full bg-red-500 text-xs text-white shadow hover:bg-red-600"
                            >
                              ×
                            </button>
                          </div>
                        </div>
                      )}

                      <div className="flex items-center gap-3">
                        <div className="flex-1">
                          <label className="flex cursor-pointer items-center justify-center rounded-md border border-gray-200 bg-gray-50 px-3 py-2 transition-colors hover:bg-gray-100">
                            <Upload className="mr-1.5 h-3.5 w-3.5 text-gray-500" />
                            <span className="text-xs text-gray-600">
                              {productForm.defaultImage
                                ? "Change File"
                                : productForm.existingImage
                                  ? "Replace Image"
                                  : "Upload Image"}
                            </span>
                            <Input
                              type="file"
                              accept="image/*"
                              className="hidden"
                              onChange={(e) => {
                                const file = e.target.files?.[0];
                                if (file) {
                                  if (file.size > 2 * 1024 * 1024) {
                                    toast.error(
                                      "File size must be less than 2MB",
                                    );
                                    return;
                                  }
                                  setProductForm((prev) => ({
                                    ...prev,
                                    defaultImage: file,
                                  }));
                                }
                              }}
                            />
                          </label>
                          <p className="mt-1 text-xs text-gray-400">Max 2MB</p>
                        </div>
                      </div>
                    </div>

                    {/* Settings */}
                    <div className="flex items-center space-x-4">
                      <div className="flex items-center space-x-2">
                        <Switch
                          id="isActive"
                          checked={productForm.isActive}
                          onCheckedChange={(checked) =>
                            setProductForm((prev) => ({
                              ...prev,
                              isActive: checked,
                            }))
                          }
                          className="peer data-[state=checked]:border-purple-300 data-[state=unchecked]:border-gray-400 data-[state=unchecked]:bg-gray-100"
                        />
                        <Label htmlFor="isActive">
                          {productForm?.isActive ? "Active" : "Inactive"}
                        </Label>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Switch
                          id="isFeatured"
                          checked={productForm.isFeatured}
                          onCheckedChange={(checked) =>
                            setProductForm((prev) => ({
                              ...prev,
                              isFeatured: checked,
                            }))
                          }
                          className="peer data-[state=checked]:border-purple-300 data-[state=unchecked]:border-gray-400 data-[state=unchecked]:bg-gray-100"
                        />
                        <Label htmlFor="isFeatured">
                          {productForm?.isFeatured
                            ? "Featured"
                            : "Not Featured"}
                        </Label>
                      </div>
                    </div>
                  </div>

                  <div className="-mx-2 flex justify-end space-x-3 border-t px-4 pb-3 pt-3">
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => setIsAddEditDialogOpen(false)}
                    >
                      Cancel
                    </Button>
                    <Button type="submit">
                      {editingProduct ? "Update" : "Create"} Product
                    </Button>
                  </div>
                </form>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {/* Products Table */}
      <div className="rounded-md border bg-white dark:bg-gray-900">
        <Table className="bg-white dark:bg-gray-900">
          <TableHeader className="bg-gray-100 dark:bg-gray-800">
            <TableRow className="bg-white hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800">
              <TableHead
                className="cursor-pointer text-center hover:bg-gray-50"
                onClick={() => handleSort("createdAt")}
              >
                <div className="flex items-center justify-center gap-2">
                  ID
                  {sortField === "createdAt" ? (
                    sortOrder === "asc" ? (
                      <ArrowUp className="h-4 w-4" />
                    ) : (
                      <ArrowDown className="h-4 w-4" />
                    )
                  ) : (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>

              {/* Name Column with Sort */}
              <TableHead
                className="cursor-pointer text-center hover:bg-gray-50"
                onClick={() => handleSort("name")}
              >
                <div className="flex items-center justify-center gap-2">
                  Name
                  {sortField === "name" ? (
                    sortOrder === "asc" ? (
                      <ArrowUp className="h-4 w-4" />
                    ) : (
                      <ArrowDown className="h-4 w-4" />
                    )
                  ) : (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>
              <TableHead className="text-center">Image</TableHead>

              {/* Category Column with Sort */}
              <TableHead className="text-center">
                <div className="flex items-center justify-center gap-2">
                  Category
                </div>
              </TableHead>

              {/* ID Column with Sort (Created At) */}

              <TableHead className="text-center">Status</TableHead>
              <TableHead>Stocks</TableHead>
              <TableHead className="text-center">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow className="bg-white hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800">
                <TableCell colSpan={6} className="px-4 py-8 text-center">
                  <div className="flex items-center justify-center">
                    <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
                    <span className="ml-2">Loading...</span>
                  </div>
                </TableCell>
              </TableRow>
            ) : products.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="py-8 text-center">
                  No products found
                </TableCell>
              </TableRow>
            ) : (
              products.map((product, index) => (
                <TableRow
                  key={product._id}
                  className="bg-white hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800"
                >
                  <TableCell className="text-center">
                    {
                      sortField === "createdAt" && sortOrder === "asc"
                        ? pagination.total -
                          (pagination.page - 1) * pagination.limit -
                          index // desc
                        : (pagination.page - 1) * pagination.limit + index + 1 // asc
                    }
                  </TableCell>
                  <TableCell className="text-center font-medium">
                    {product.name}
                  </TableCell>
                  <TableCell className="text-center">
                    {product.defaultImage ? (
                      <img
                        src={product.defaultImage}
                        alt={product.name}
                        className="mx-auto h-12 w-12 cursor-pointer rounded object-cover"
                        onClick={() => openPreview(index)}
                      />
                    ) : (
                      <div className="mx-auto flex h-12 w-12 items-center justify-center rounded bg-gray-100">
                        <ImageIcon className="h-6 w-6 text-gray-400" />
                      </div>
                    )}
                  </TableCell>

                  <TableCell className="text-center">
                    {product.category?.name}
                  </TableCell>

                  <TableCell className="text-center">
                    <div className="flex justify-center gap-1">
                      {product.isActive && (
                        <Badge variant="default" className="text-white">
                          Active
                        </Badge>
                      )}
                      {product.isFeatured && (
                        <Badge variant="default" className="text-white">
                          Featured
                        </Badge>
                      )}
                    </div>
                  </TableCell>
                  <TableCell className="text-center">
                    <div
                      className="cursor-pointer rounded-md bg-blue-400 p-1 text-xs text-white"
                      onClick={() => setViewStocksOpen(true)}
                    >
                      View Stocks
                    </div>
                  </TableCell>
                  <TableCell className="text-center">
                    <div className="flex justify-center gap-1">
                      <Tooltip text="SKUs">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => openSKUManager(product)}
                        >
                          <Package className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Image">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => openImageManager(product)}
                        >
                          <ImageIcon className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="View">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleView(product)}
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Edit">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleEdit(product)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Delete">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleDelete(product._id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* Pagination */}
      {pagination.pages > 1 && (
        <div className="mt-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div className="text-sm text-gray-500">
            Showing {(page - 1) * limit + 1} to{" "}
            {Math.min(page * limit, pagination.total)} of {pagination.total}{" "}
            products
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPage(page - 1)}
              disabled={page === 1}
            >
              <ChevronLeft className="h-4 w-4" />
              Previous
            </Button>
            <span className="text-sm">
              Page {page} of {pagination.pages}
            </span>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPage(page + 1)}
              disabled={page === pagination.pages}
            >
              Next
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      {/* SKU Management Dialog */}
      <Dialog open={isSKUDialogOpen} onOpenChange={setIsSKUDialogOpen}>
        <DialogContent className="max-w-3xl">
          <div className="mx-auto my-1 flex min-h-[calc(100%-0.5rem)] max-w-lg items-center">
            <div className="relative flex w-full flex-col gap-0 rounded-lg border-0 border-stroke bg-white p-0 text-dark-5 shadow-lg dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              {/* Header */}
              <DialogHeader>
                <div>
                  <p className="mb-0.5 text-xs uppercase tracking-wide text-white">
                    Product
                  </p>
                  <DialogTitle className="text-base font-medium text-white">
                    {selectedProduct?.name} — SKU Manager
                  </DialogTitle>
                </div>
                <X
                  className="h-6 w-6 cursor-pointer p-1 text-white"
                  onClick={() => {
                    setIsSKUDialogOpen(false);
                  }}
                />
              </DialogHeader>
              <div className="flex flex-grow flex-col p-4 pb-0 pl-2 pr-2">
                <div className="max-h-[60vh] min-h-[60vh] flex-1 overflow-y-auto pl-2 pr-2">
                  {/* Collapsible Form */}
                  <div className="border-b">
                    <button
                      type="button"
                      onClick={() => {
                        setIsSKUFormOpen(!isSKUFormOpen);
                        if (!isSKUFormOpen) resetSKUForm();
                      }}
                      className="hover:bg-muted/40 flex w-full items-center justify-between px-3 py-2 transition-colors"
                    >
                      <div className="flex items-center gap-2">
                        <span className="text-sm font-medium">
                          {editingSKU ? "Edit SKU" : "Add New SKU"}
                        </span>
                        {/* {!isSKUFormOpen && (
                          <Badge variant="secondary" className="text-xs">
                            Click to expand
                          </Badge>
                        )} */}
                      </div>
                      {isSKUFormOpen ? (
                        <ChevronUp className="text-muted-foreground h-4 w-4" />
                      ) : (
                        <ChevronDown className="text-muted-foreground h-4 w-4" />
                      )}
                    </button>

                    {isSKUFormOpen && (
                      <div className="bg-muted/40 mt-2 border-t px-0 py-5">
                        <form onSubmit={handleSKUSubmit} className="space-y-4">
                          <div className="grid grid-cols-4 gap-3">
                            <div>
                              <Label className="mb-1.5 block text-xs">
                                Color <span className="text-red-500">*</span>
                              </Label>
                              <select
                                value={skuForm.color}
                                onChange={(e) =>
                                  setSkuForm((prev) => ({
                                    ...prev,
                                    color: e.target.value,
                                  }))
                                }
                                required
                                className="border-input focus:ring-ring w-full rounded-md border bg-white px-3 py-2.5 text-sm focus:outline-none focus:ring-1 dark:bg-[#3B3B3B]"
                              >
                                <option value="">Select color</option>
                                {displayColors.map((color) => (
                                  <option key={color._id} value={color._id}>
                                    {color.name}
                                  </option>
                                ))}
                              </select>
                            </div>
                            <div>
                              <Label className="mb-1.5 block text-xs">
                                Size <span className="text-red-500">*</span>
                              </Label>
                              <select
                                value={skuForm.size}
                                onChange={(e) =>
                                  setSkuForm((prev) => ({
                                    ...prev,
                                    size: e.target.value,
                                  }))
                                }
                                required
                                className="border-input focus:ring-ring w-full rounded-md border bg-white px-3 py-2.5 text-sm focus:outline-none focus:ring-1 dark:bg-[#3B3B3B]"
                              >
                                <option value="">Select size</option>
                                {sizes.map((size) => (
                                  <option key={size._id} value={size._id}>
                                    {size.name}
                                  </option>
                                ))}
                              </select>
                            </div>
                            <div>
                              <Label className="mb-1.5 block text-xs">
                                SKU code <span className="text-red-500">*</span>
                              </Label>
                              <Input
                                value={skuForm.sku}
                                onChange={(e) =>
                                  setSkuForm((prev) => ({
                                    ...prev,
                                    sku: e.target.value.toUpperCase(),
                                  }))
                                }
                                placeholder="e.g. PROD-RED-M"
                                className="font-mono text-sm"
                                required
                              />
                            </div>
                            <div>
                              <Label className="mb-1.5 block text-xs">
                                Stock quantity{" "}
                                <span className="text-red-500">*</span>
                              </Label>
                              <Input
                                type="number"
                                min={0}
                                value={skuForm.quantity}
                                onChange={(e) => {
                                  const value = e.target.value;
                                  if (Number(value) >= 0)
                                    setSkuForm((prev) => ({
                                      ...prev,
                                      quantity: parseInt(e.target.value) || 0,
                                    }));
                                }}
                                placeholder="0"
                                required
                              />
                            </div>
                          </div>

                          {/* <div className="grid grid-cols-3 gap-3">               
                            <div>
                              <Label className="text-xs mb-1.5 block">Price ₹ <span className="text-red-500">*</span></Label>
                              <Input
                                type="number"
                                value={skuForm.price}
                                onChange={(e) => setSkuForm(prev => ({ ...prev, price: parseFloat(e.target.value) || 0 }))}
                                placeholder="0"
                                required
                              />
                            </div>
                            <div>
                              <Label className="text-xs mb-1.5 block">MRP ₹</Label>
                              <Input
                                type="number"
                                value={skuForm.comparePrice || ''}
                                onChange={(e) => setSkuForm(prev => ({ ...prev, comparePrice: parseFloat(e.target.value) || 0 }))}
                                placeholder="0"
                              />
                            </div>
                          
                          </div>               */}

                          <div className="flex justify-end gap-2 pt-1">
                            <Button
                              type="button"
                              variant="danger"
                              size="sm"
                              onClick={() => {
                                setIsSKUFormOpen(false);
                                resetSKUForm();
                              }}
                            >
                              Cancel
                            </Button>
                            <Button
                              type="submit"
                              size="sm"
                              className="text-white"
                            >
                              {editingSKU ? "Update SKU" : "Add SKU"}
                            </Button>
                          </div>
                        </form>
                      </div>
                    )}
                  </div>

                  {/* SKU List */}
                  <div className="mt-3">
                    <div className="flex items-center justify-between rounded-t-lg border-b bg-primary px-6 py-5 dark:bg-[#1f2a37]">
                      <p className="text-xs font-medium uppercase tracking-wide text-white">
                        Existing SKUs
                      </p>
                      <span className="bg-muted rounded-full border px-2.5 py-0.5 text-xs text-white">
                        {skus.length} SKU{skus.length !== 1 ? "s" : ""}
                      </span>
                    </div>
                    <Table>
                      <TableHeader className="dark:bg-[#1f2a37]">
                        <TableRow>
                          {[
                            { key: "color", label: "Color", className: "pl-6" },
                            { key: "size", label: "Size" },
                            { key: "sku", label: "SKU code" },
                          ].map(({ key, label, className }) => (
                            <TableHead
                              key={key}
                              className={`hover:bg-muted/40 cursor-pointer select-none text-xs ${className || ""}`}
                              onClick={() => handleSkuSort(key)}
                            >
                              <div className="flex items-center gap-1">
                                {label}
                                {skuSort.field === key ? (
                                  skuSort.order === "asc" ? (
                                    <ArrowUp className="h-3 w-3" />
                                  ) : (
                                    <ArrowDown className="h-3 w-3" />
                                  )
                                ) : (
                                  <ArrowDown className="text-muted-foreground/40 h-3 w-3" />
                                )}
                              </div>
                            </TableHead>
                          ))}
                          {/* <TableHead className="text-xs text-right cursor-pointer hover:bg-muted/40 select-none" onClick={() => handleSkuSort('price')}>
                            <div className="flex items-center justify-end gap-1">
                              Price
                              {skuSort.field === 'price'
                                ? skuSort.order === 'asc'
                                  ? <ArrowUp className="h-3 w-3" />
                                  : <ArrowDown className="h-3 w-3" />
                                : <ArrowDown className="h-3 w-3 text-muted-foreground/40" />
                              }
                            </div>
                          </TableHead> */}
                          <TableHead className="text-right text-xs">
                            Qty
                          </TableHead>
                          {/* <TableHead className="text-xs text-right">MRP</TableHead> */}
                          <TableHead className="pr-6 text-center text-xs">
                            Action
                          </TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody className="dark:bg-[#1f2a37]">
                        {sortedSkus.length === 0 ? (
                          <TableRow>
                            <TableCell
                              colSpan={7}
                              className="text-muted-foreground py-10 text-center text-sm"
                            >
                              No SKUs added yet
                            </TableCell>
                          </TableRow>
                        ) : (
                          sortedSkus.map((sku) => (
                            <TableRow
                              key={sku._id}
                              className={
                                editingSKU?._id === sku._id ? "bg-muted/40" : ""
                              }
                            >
                              <TableCell className="pl-6">
                                <div className="flex items-center gap-2">
                                  <span
                                    className="h-2.5 w-2.5 flex-shrink-0 rounded-full border"
                                    style={{
                                      backgroundColor: sku.color?.hexCode,
                                    }}
                                  />
                                  <span className="text-sm capitalize">
                                    {sku.color?.name}
                                  </span>
                                </div>
                              </TableCell>
                              <TableCell className="text-sm">
                                {sku.size?.name}
                              </TableCell>
                              <TableCell className="text-muted-foreground font-mono text-xs">
                                {sku.sku}
                              </TableCell>
                              <TableCell className="text-right text-sm">
                                {sku.quantity}
                              </TableCell>
                              {/* <TableCell className="text-right text-sm font-medium">₹{sku.price.toLocaleString()}</TableCell> */}
                              {/* <TableCell className="text-right text-xs text-muted-foreground line-through">
                                {sku.comparePrice ? `₹${sku.comparePrice.toLocaleString()}` : '—'}
                              </TableCell> */}
                              <TableCell className="pr-6 text-right">
                                <div className="flex justify-end gap-1.5">
                                  <Button
                                    size="sm"
                                    variant="outline"
                                    className="h-7 px-3 text-xs"
                                    onClick={() => {
                                      handleEditSKU(sku);
                                      setIsSKUFormOpen(true);
                                    }}
                                  >
                                    Edit
                                  </Button>
                                  <Button
                                    size="sm"
                                    variant="danger"
                                    className="h-7 px-3 text-xs"
                                    onClick={() => handleDeleteSKU(sku._id)}
                                  >
                                    Delete
                                  </Button>
                                </div>
                              </TableCell>
                            </TableRow>
                          ))
                        )}
                      </TableBody>
                    </Table>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Color Images Management Dialog */}
      <Dialog open={isImageDialogOpen} onOpenChange={setIsImageDialogOpen}>
        <DialogContent className="max-w-3xl">
          <div className="mx-auto my-2 flex min-h-[calc(100%-0.5rem)] max-w-lg items-center">
            <div className="relative flex w-full flex-col gap-0 rounded-lg border-0 border-stroke bg-white p-0 text-dark-5 shadow-lg dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              {/* Header */}
              <DialogHeader>
                <div>
                  <p className="mb-0.5 text-xs uppercase tracking-wide text-white">
                    Product
                  </p>
                  <DialogTitle className="text-base font-medium">
                    {selectedProduct?.name} — Color images
                  </DialogTitle>
                </div>
                <X
                  className="h-6 w-6 cursor-pointer p-1 text-white"
                  onClick={() => {
                    setIsImageDialogOpen(false);
                  }}
                />
              </DialogHeader>
              <div className="flex flex-grow flex-col p-4 pb-0 pl-2 pr-2">
                <div className="max-h-[60vh] flex-1 overflow-y-auto pl-2 pr-2">
                  {colors.length > 0 ? (
                    <div className="border-b">
                      <button
                        type="button"
                        onClick={() => {
                          setIsImageUploadOpen(!isImageUploadOpen);
                          if (!isImageUploadOpen) {
                            setSelectedColor(undefined);
                            setImageFiles([]);
                          }
                        }}
                        className="hover:bg-muted/40 flex w-full items-center justify-between px-6 py-4 transition-colors"
                      >
                        <div className="flex items-center gap-2">
                          <span className="text-sm font-medium">
                            Upload Images for Color
                          </span>
                          {/* {!isImageUploadOpen && (
                          <Badge variant="secondary" className="text-xs">
                            Click to expand
                          </Badge>
                        )} */}
                        </div>
                        {isImageUploadOpen ? (
                          <ChevronUp className="text-muted-foreground h-4 w-4" />
                        ) : (
                          <ChevronDown className="text-muted-foreground h-4 w-4" />
                        )}
                      </button>
                      {isImageUploadOpen && (
                        <div className="bg-muted/40 border-t px-6 py-5">
                          <div className="space-y-4">
                            {/* Color pills - radio style */}
                            <div>
                              <p className="text-muted-foreground mb-2 text-xs">
                                Select color{" "}
                                <span className="text-red-500">*</span>
                              </p>
                              <div className="flex flex-wrap gap-2">
                                {colors.map((color) => {
                                  const isSelected =
                                    selectedColor === color._id;
                                  return (
                                    <label
                                      key={color._id}
                                      className={`flex cursor-pointer items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-all duration-150 ${
                                        isSelected
                                          ? "bg-background text-primary-foreground scale-[1.03] border-primary shadow-md"
                                          : "bg-background border-border hover:bg-muted/60"
                                      }`}
                                      style={
                                        isSelected
                                          ? {
                                              boxShadow: `0 0 0 2px ${color.hexCode}`,
                                            }
                                          : {}
                                      }
                                    >
                                      <input
                                        type="radio"
                                        name="uploadColor"
                                        value={color._id}
                                        checked={isSelected}
                                        onChange={(e) =>
                                          setSelectedColor(e.target.value)
                                        }
                                        className="sr-only"
                                      />
                                      <span
                                        className="h-3 w-3 flex-shrink-0 rounded-full border"
                                        style={{
                                          backgroundColor: color.hexCode,
                                        }}
                                      />
                                      <span className="font-medium">
                                        {color.name}
                                      </span>
                                    </label>
                                  );
                                })}
                              </div>
                            </div>

                            {/* File drop zone */}
                            <div>
                              <p className="text-muted-foreground mb-2 text-xs">
                                Images <span className="text-red-500">*</span>
                                <span className="text-muted-foreground/60 ml-1">
                                  Max 2MB each
                                </span>
                              </p>
                              <label className="hover:bg-muted/40 bg-background flex cursor-pointer flex-col items-center justify-center rounded-md border border-dashed px-4 py-5 transition-colors">
                                <Upload className="text-muted-foreground mb-2 h-5 w-5" />
                                <p className="text-muted-foreground text-sm">
                                  Click to select images
                                </p>
                                <p className="text-muted-foreground/60 mt-0.5 text-xs">
                                  PNG, JPG, WEBP supported
                                </p>
                                <input
                                  ref={fileInputRef}
                                  type="file"
                                  accept="image/*"
                                  multiple
                                  className="hidden"
                                  onChange={(e) => {
                                    const files = Array.from(
                                      e.target.files || [],
                                    );

                                    const valid = files.filter(
                                      (f) => f.size <= 2 * 1024 * 1024,
                                    );

                                    if (valid.length !== files.length) {
                                      toast.error(
                                        "Some files exceed 2MB and were skipped",
                                        {
                                          id: Date.now().toString(),
                                        },
                                      );
                                    }

                                    setImageFiles((prev) => [
                                      ...prev,
                                      ...valid,
                                    ]);

                                    // Important
                                    if (fileInputRef.current) {
                                      fileInputRef.current.value = "";
                                    }
                                  }}
                                />
                              </label>
                            </div>

                            {/* Previews */}
                            {imageFiles.length > 0 && (
                              <div>
                                <p className="text-muted-foreground mb-2 text-xs">
                                  {imageFiles.length} image
                                  {imageFiles.length > 1 ? "s" : ""} ready to
                                  upload
                                </p>
                                <div className="flex flex-wrap gap-2">
                                  {imageFiles.map((file, index) => (
                                    <div key={index} className="relative">
                                      <img
                                        src={URL.createObjectURL(file)}
                                        className="h-14 w-14 rounded-md border object-cover"
                                      />
                                      <button
                                        type="button"
                                        onClick={() =>
                                          setImageFiles((prev) =>
                                            prev.filter((_, i) => i !== index),
                                          )
                                        }
                                        className="absolute -right-1.5 -top-1.5 flex h-4 w-4 items-center justify-center rounded-full border border-red-200 bg-red-100"
                                      >
                                        <X className="h-2.5 w-2.5 text-red-600" />
                                      </button>
                                      <div
                                        className="absolute bottom-0 left-0 right-0 rounded-b-md bg-black/50 py-px text-center text-white"
                                        style={{ fontSize: "9px" }}
                                      >
                                        {Math.round(file.size / 1024)}KB
                                      </div>
                                    </div>
                                  ))}
                                </div>
                              </div>
                            )}

                            <Button
                              type="button"
                              onClick={handleImageUpload}
                              disabled={
                                !selectedColor || imageFiles.length === 0
                              }
                              className="w-full text-white"
                            >
                              <Upload className="mr-2 h-4 w-4" />
                              {selectedColor && imageFiles.length > 0
                                ? `Upload ${imageFiles.length} image${imageFiles.length > 1 ? "s" : ""} to ${colors.find((c) => c._id === selectedColor)?.name}`
                                : "Upload images"}
                            </Button>
                          </div>
                        </div>
                      )}{" "}
                      {/* Gallery */}
                      <div>
                        <div className="flex items-center justify-between border-b px-6 py-3">
                          <p className="text-muted-foreground text-xs font-medium uppercase tracking-wide">
                            Uploaded by color
                          </p>
                          <span className="text-muted-foreground rounded-full border px-2.5 py-0.5 text-xs">
                            {colorImages.length} color
                            {colorImages.length !== 1 ? "s" : ""}
                          </span>
                        </div>

                        <div className="flex flex-col gap-4 p-6">
                          {colorImages.length === 0 ? (
                            <div className="text-muted-foreground rounded-lg border border-dashed py-8 text-center text-sm">
                              No images uploaded yet. Select a color above and
                              upload images to get started.
                            </div>
                          ) : (
                            colorImages.map((colorImage) => (
                              <div
                                key={colorImage?._id}
                                className="overflow-hidden rounded-lg border"
                              >
                                {/* Color row header */}
                                <div className="bg-muted/40 flex items-center justify-between border-b px-4 py-3">
                                  <div className="flex items-center gap-2">
                                    <span
                                      className="h-3 w-3 flex-shrink-0 rounded-full"
                                      style={{
                                        backgroundColor:
                                          colorImage?.color?.hexCode,
                                      }}
                                    />
                                    <span className="text-sm font-medium capitalize">
                                      {colorImage?.color?.name}
                                    </span>
                                    <span className="text-muted-foreground rounded-full border px-2 py-0.5 text-xs">
                                      {colorImage?.images?.length} image
                                      {colorImage?.images?.length !== 1
                                        ? "s"
                                        : ""}
                                    </span>
                                  </div>
                                  <label className="bg-background hover:bg-muted/60 text-muted-foreground flex cursor-pointer items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs transition-colors">
                                    <Plus className="h-3 w-3" />
                                    Add more
                                    <input
                                      type="file"
                                      accept="image/*"
                                      multiple
                                      className="hidden"
                                      onChange={async (e) => {
                                        const files = Array.from(
                                          e.target.files || [],
                                        );
                                        const formData = new FormData();
                                        formData.append(
                                          "productId",
                                          selectedProduct!._id,
                                        );
                                        formData.append(
                                          "colorId",
                                          colorImage?.color._id,
                                        );
                                        files.forEach((file) =>
                                          formData.append("images", file),
                                        );
                                        const res = await fetch(
                                          "/api/product-color-images",
                                          { method: "POST", body: formData },
                                        );
                                        const data = await res.json();
                                        if (data.success) {
                                          toast.success(
                                            `Added ${files.length} image(s) to ${colorImage?.color?.name}`,
                                          );
                                          fetchColorImages(
                                            selectedProduct!._id,
                                          );
                                        } else
                                          toast.error(
                                            data.error ||
                                              "Failed to add images",
                                          );
                                      }}
                                    />
                                  </label>
                                </div>

                                {/* Images grid */}
                                <div className="flex flex-wrap gap-3 p-4">
                                  {colorImage?.images?.map((image, index) => (
                                    <div key={index} className="group relative">
                                      <img
                                        src={image.url}
                                        alt={
                                          image.altText ||
                                          `${colorImage?.color?.name} ${index + 1}`
                                        }
                                        className={`h-20 w-20 rounded-md border-2 object-cover ${
                                          image.isPrimary
                                            ? "border-green-500"
                                            : "border-border border border-transparent"
                                        }`}
                                      />
                                      {/* {image.isPrimary && (
                                    <span className="absolute top-1 left-1 bg-green-100 text-green-800 text-xs px-1.5 py-0.5 rounded font-medium" style={{ fontSize: '9px' }}>
                                      Primary
                                    </span>
                                  )} */}
                                      <div className="absolute inset-0 flex flex-col items-center justify-center gap-1 rounded-md bg-black/0 opacity-0 transition-all group-hover:bg-black/50 group-hover:opacity-100">
                                        {/* {!image.isPrimary && (
                                      <button
                                        onClick={async () => {
                                          const res = await fetch(`/api/product-color-images/${colorImage._id}`, {
                                            method: 'PUT',
                                            headers: { 'Content-Type': 'application/json' },
                                            body: JSON.stringify({ action: 'setPrimary', imageIndex: index })
                                          });
                                          if (res.ok) { toast.success('Primary image updated'); fetchColorImages(selectedProduct!._id); }
                                        }}
                                        className="px-2 py-1 bg-white/90 rounded text-xs font-medium text-gray-800 hover:bg-white"
                                      >
                                        Set primary
                                      </button>
                                    )} */}
                                        <button
                                          onClick={() =>
                                            handleDeleteImage(
                                              colorImage?._id,
                                              image.url,
                                            )
                                          }
                                          className="rounded bg-red-500/90 px-2 py-1 text-xs font-medium text-white hover:bg-red-500"
                                        >
                                          Delete
                                        </button>
                                      </div>
                                    </div>
                                  ))}
                                </div>
                              </div>
                            ))
                          )}
                        </div>
                      </div>
                    </div>
                  ) : (
                    <div className="bg-muted/40 border-b px-6 py-5">
                      <p className="text-muted-foreground text-sm">
                        No colors found for this product. Please add colors in
                        the SKU manager before uploading images.
                      </p>
                    </div>
                  )}
                  {/* Collapsible Upload Section */}
                </div>
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* View Stocks */}
      {viewStocksOpen && (
        <ViewStocks
          open={viewStocksOpen}
          onOpenChange={openChnageViewStock}
          data={skus as any}
        />
      )}
    </div>
  );
}
// "use client";

// import { useState, useEffect } from "react";

// import { Button } from "@/components/ui/button";
// import { Input } from "@/components/ui/input";
// import { Label } from "@/components/ui/label";

// import { useDebounce } from "@/hooks/useDebounce";

// import { Plus, Search } from "lucide-react";

// // ================= COMPONENTS =================

// import ProductFormDialog from "./components/ProductFormDialog";
// import ProductViewDialog from "./components/ProductViewDialog";
// import SKUManagerDialog from "./components/SKUManagerDialog";
// import ColorImageManagerDialog from "./components/ColorImageManagerDialog";
// import ProductsTable from "./components/ProductsTable";
// import Pagination from "./components/Pagination";

// // ================= HOOKS =================

// import { useProducts } from "./hooks/useProducts";
// import { useCategories } from "./hooks/useCategories";
// import { useColors } from "./hooks/useColors";
// import { useSizes } from "./hooks/useSizes";

// // ================= TYPES =================

// interface Category {
//   _id: string;
//   name: string;
//   isActive?: boolean;
// }

// interface SubCategory {
//   _id: string;
//   name: string;
//   isActive?: boolean;
// }

// interface Color {
//   _id: string;
//   name: string;
//   hexCode?: string;
// }

// interface Size {
//   _id: string;
//   name: string;
// }

// interface ProductDimensions {
//   length: string;
//   width: string;
//   height: string;
// }

// export interface Product {
//   _id: string;
//   name: string;
//   slug?: string;
//   description?: string;
//   shortDescription?: string;

//   category?: Category;

//   subcategory?: SubCategory;

//   weight?: string | number;

//   dimensions?: ProductDimensions;

//   defaultImage?: string;

//   existingImage?: string;

//   isActive?: boolean;

//   isFeatured?: boolean;

//   createdAt?: string;

//   updatedAt?: string;
// }

// export default function ProductsManagement() {
//   // ================= STATES =================

//   const [search, setSearch] =
//     useState<string>("");

//   const [page, setPage] =
//     useState<number>(1);

//   const [limit, setLimit] =
//     useState<number>(10);

//   const [sortField, setSortField] =
//     useState<string>("createdAt");

//   const [sortOrder, setSortOrder] =
//     useState<"asc" | "desc">("asc");

//   // ================= DIALOG STATES =================

//   const [
//     isAddEditDialogOpen,
//     setIsAddEditDialogOpen,
//   ] = useState<boolean>(false);

//   const [
//     isViewDialogOpen,
//     setIsViewDialogOpen,
//   ] = useState<boolean>(false);

//   const [
//     isSKUDialogOpen,
//     setIsSKUDialogOpen,
//   ] = useState<boolean>(false);

//   const [
//     isImageDialogOpen,
//     setIsImageDialogOpen,
//   ] = useState<boolean>(false);

//   // ================= PRODUCT STATES =================

//   const [
//     editingProduct,
//     setEditingProduct,
//   ] = useState<Product | null>(null);

//   const [
//     viewingProduct,
//     setViewingProduct,
//   ] = useState<Product | null>(null);

//   const [
//     selectedProduct,
//     setSelectedProduct,
//   ] = useState<Product | null>(null);

//   // ================= DEBOUNCE =================

//   const debouncedSearch =
//     useDebounce(search, 500);

//   // ================= HOOKS =================

//   const {
//     products,
//     pagination,
//     loading,
//     fetchProducts,
//     deleteProduct,
//   } = useProducts();

//   const {
//     categories,
//     subCategories,
//   } = useCategories() as {
//     categories: Category[];
//     subCategories: SubCategory[];
//   };

//   const { colors } = useColors() as {
//     colors: Color[];
//   };

//   const { sizes } = useSizes() as {
//     sizes: Size[];
//   };

//   // ================= FETCH PRODUCTS =================

//   useEffect(() => {
//     fetchProducts({
//       page,
//       limit,
//       sortField,
//       sortOrder,
//       search: debouncedSearch,
//     });
//   }, [
//     debouncedSearch,
//     page,
//     limit,
//     sortField,
//     sortOrder,
//   ]);

//   // ================= HANDLERS =================

//   const handleEdit = (
//     product: Product
//   ): void => {
//     setEditingProduct(product);

//     setIsAddEditDialogOpen(true);
//   };

//   const handleView = (
//     product: Product
//   ): void => {
//     setViewingProduct(product);

//     setIsViewDialogOpen(true);
//   };

//   const handleDelete = async (
//     id: string
//   ): Promise<void> => {
//     const confirmDelete = window.confirm(
//       "Are you sure you want to delete this product?"
//     );

//     if (!confirmDelete) return;

//     const success = await deleteProduct(id);

//     if (success) {
//       fetchProducts({
//         page,
//         limit,
//         sortField,
//         sortOrder,
//         search: debouncedSearch,
//       });
//     }
//   };

//   const openSKUManager = (
//     product: Product
//   ): void => {
//     setSelectedProduct(product);

//     setIsSKUDialogOpen(true);
//   };

//   const openImageManager = (
//     product: Product
//   ): void => {
//     setSelectedProduct(product);

//     setIsImageDialogOpen(true);
//   };

//   const handleSearch = (
//     value: string
//   ): void => {
//     setSearch(value);

//     setPage(1);
//   };

//   const handleLimitChange = (
//     value: string
//   ): void => {
//     setLimit(parseInt(value));

//     setPage(1);
//   };

//   const handleSort = (
//     field: string
//   ): void => {
//     if (sortField === field) {
//       setSortOrder(
//         sortOrder === "asc"
//           ? "desc"
//           : "asc"
//       );
//     } else {
//       setSortField(field);

//       setSortOrder(
//         field === "name" ||
//           field === "category"
//           ? "asc"
//           : "desc"
//       );
//     }

//     setPage(1);
//   };

//   // ================= RENDER =================

//   return (
//     <div className="space-y-6">
//       {/* Header */}
//       <div className="flex items-center justify-between">
//         <div className="flex items-center gap-3">
//           <Button
//             className="text-white"
//             onClick={() => {
//               setEditingProduct(null);

//               setIsAddEditDialogOpen(
//                 true
//               );
//             }}
//           >
//             <Plus className="w-4 h-4" />

//             Add Product
//           </Button>
//         </div>
//       </div>

//       {/* Search & Limit */}
//       <div className="flex flex-col gap-4 py-6 sm:flex-row sm:items-center sm:justify-between">
//         {/* Search */}
//         <div className="relative max-w-md w-full">
//           <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />

//           <Input
//             placeholder="Search products..."
//             value={search}
//             onChange={(e) =>
//               handleSearch(
//                 e.target.value
//               )
//             }
//             className="pl-10"
//           />
//         </div>

//         {/* Limit */}
//         <div className="flex items-center gap-2">
//           <Label className="text-sm whitespace-nowrap">
//             Show:
//           </Label>

//           <select
//             value={limit.toString()}
//             onChange={(e) =>
//               handleLimitChange(
//                 e.target.value
//               )
//             }
//             className="rounded-md border border-input bg-white px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-ring dark:bg-[#3B3B3B]"
//           >
//             <option value="6">
//               6
//             </option>

//             <option value="10">
//               10
//             </option>

//             <option value="20">
//               20
//             </option>

//             <option value="50">
//               50
//             </option>
//           </select>
//         </div>
//       </div>

//       {/* Products Table */}
//       <ProductsTable
//         products={products}
//         loading={loading}
//         pagination={pagination}
//         sortField={sortField}
//         sortOrder={sortOrder}
//         onSort={handleSort}
//         onView={handleView}
//         onEdit={handleEdit}
//         onDelete={handleDelete}
//         onManageSKU={
//           openSKUManager
//         }
//         onManageImages={
//           openImageManager
//         }
//       />

//       {/* Pagination */}
//       {pagination.pages > 1 && (
//         <Pagination
//           page={page}
//           pages={pagination.pages}
//           limit={limit}
//           total={pagination.total}
//           onPageChange={setPage}
//         />
//       )}

//       {/* Add/Edit Product Dialog */}
//       <ProductFormDialog
//         open={isAddEditDialogOpen}
//         onOpenChange={
//           setIsAddEditDialogOpen
//         }
//         editingProduct={
//           editingProduct
//         }
//         categories={categories}
//         subCategories={
//           subCategories
//         }
//         onSuccess={() =>
//           fetchProducts({
//             page,
//             limit,
//             sortField,
//             sortOrder,
//             search:
//               debouncedSearch,
//           })
//         }
//       />

//       {/* Product View Dialog */}
//       <ProductViewDialog
//         open={isViewDialogOpen}
//         onOpenChange={
//           setIsViewDialogOpen
//         }
//         product={viewingProduct}
//         onEdit={handleEdit}
//         onDelete={handleDelete}
//       />

//       {/* SKU Manager */}
//       <SKUManagerDialog
//         open={isSKUDialogOpen}
//         onOpenChange={
//           setIsSKUDialogOpen
//         }
//         product={selectedProduct}
//         colors={colors}
//         sizes={sizes}
//       />

//       {/* Color Image Manager */}
//       <ColorImageManagerDialog
//         open={isImageDialogOpen}
//         onOpenChange={
//           setIsImageDialogOpen
//         }
//         product={selectedProduct}
//         colors={colors}
//       />
//     </div>
//   );
// }
