"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;
  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: "",
    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: "",
      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('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');
      }

      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 || "",
      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-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        {/* <h2 className="text-2xl font-bold">Products Management</h2> */}
        
        <div className="flex items-center gap-3">
          {/* <div className="text-sm text-gray-500 bg-gray-100 px-3 py-1 rounded">
            Total Products: {pagination.total}
          </div> */}
          
          <Dialog open={isAddEditDialogOpen} onOpenChange={setIsAddEditDialogOpen}>
            <DialogTrigger asChild>
              <Button
                className="text-white"
                onClick={() => { resetForm(); setEditingProduct(null); setIsAddEditDialogOpen(true); }}
              >
                <Plus className="w-4 h-4" />
                Add Product
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-4xl">
              <div className="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-1 mx-auto">
                <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 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 p-1 text-white cursor-pointer"
                      onClick={() => {
                        setIsAddEditDialogOpen(false);
                      }}
                    />
                  </DialogHeader>

                  <form onSubmit={handleSubmit} className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-1">
                    <div className="max-h-[60vh] min-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2 pt-2 space-y-4 pb-4">
                      {/* Basic Information */}
                      <div className="grid md:grid-cols-3 gap-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="text-xs text-gray-500 mt-1">
                            Only letters, numbers, spaces, and basic punctuation (-_,.&())
                          </p>
                        </div>
                        <div>
                          <Label className="block mb-2" 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="w-full px-3 py-2.5 rounded-md border border-input text-sm bg-white dark:bg-[#3B3B3B] focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50"
                            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="block mb-2" htmlFor="category">Subcategory</Label>
                          <select
                            id="subcategory"
                            value={productForm.subcategory}
                            onChange={(e) => setProductForm(prev => ({ ...prev, subcategory: e.target.value }))}
                            className="w-full px-3 py-2.5 rounded-md border border-input text-sm bg-white dark:bg-[#3B3B3B] focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50"
                          >
                            <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="block mb-2" 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="block mb-2" 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 grid-cols-2 gap-3 flex-1" >
                        <div>
                          <Label className="block mb-2" 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="block mb-2" 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="block mb-2">Dimensions (cm) L × W × H <span className="text-red">*</span></Label>
                        <div className="grid grid-cols-3 gap-4 mt-2">
                          <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="text-xs text-gray-500 mt-1">Values must be positive numbers</p>
                      </div>

                      {/* Default Image */}
                      <div className="space-y-2">
                        <Label className="block mb-2" htmlFor="defaultImage">Default Product Image <span className="text-red">*</span></Label>
                        
                        {productForm.existingImage && !productForm.defaultImage && (
                          <div className="mb-3 p-3 border dark:bg-gray-800 border-gray-200 rounded-lg bg-gray-50">
                            <p className="text-xs text-gray-500 mb-2">Current Image:</p>

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

                              <button
                                type="button"
                                onClick={() => {
                                  setProductForm((prev) => ({
                                    ...prev,
                                    existingImage: "",
                                  }));
                                }}
                                className="absolute -top-2 -right-2 flex items-center justify-center w-6 h-6 rounded-full bg-red-500 text-white text-xs shadow-md hover:bg-red-600 transition"
                              >
                                ✕
                              </button>
                            </div>
                          </div>
                        )}
                        
                        {productForm.defaultImage && (
                        <div className="mb-3 p-3 border border-green-200 rounded-lg bg-green-50">
                          <p className="text-xs text-green-600 mb-2">New Image Preview:</p>

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

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

                          </div>
                        </div>
                        )}
                        
                        <div className="flex items-center gap-3">
                          <div className="flex-1">
                            <label className="flex items-center justify-center px-3 py-2 bg-gray-50 hover:bg-gray-100 border border-gray-200 rounded-md cursor-pointer transition-colors">
                              <Upload className="h-3.5 w-3.5 mr-1.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="text-xs text-gray-400 mt-1">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="flex justify-end space-x-3 px-4 pb-3 pt-3 border-t -mx-2">
                      <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>
      </div>

      {/* View Product Dialog */}
      <Dialog open={isViewDialogOpen} onOpenChange={setIsViewDialogOpen}>
        <DialogContent className="max-w-3xl">
          <div className="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-1 mx-auto">
            <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              <DialogHeader>
                <DialogTitle>Product Details</DialogTitle>
                <X className="h-6 w-6 p-1 text-white cursor-pointer"
                  onClick={() => {
                    setIsViewDialogOpen(false);
                  }}
                />
              </DialogHeader>
              
              {viewingProduct && (
                <div className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-grow">
                  <div className="max-h-[60vh] min-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2">
                    <div className="space-y-6 pb-4">
                      {viewingProduct.defaultImage && (
                        <div className="flex justify-center">
                          <img
                            src={viewingProduct.defaultImage}
                            alt={viewingProduct.name}
                            className="h-40 w-140 object-cover rounded-lg border-2 border-gray-200 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="text-sm font-mono">{viewingProduct.slug}</p>
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs text-gray-500">Price</Label>
                          <p className="text-sm font-mono">₹ {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="text-xs text-gray-500 mr-2">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="text-sm whitespace-pre-wrap bg-gray-100 dark:bg-gray-500 p-3 rounded-lg">
                            <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="text-sm bg-gray-100 dark:bg-gray-500 p-3 rounded-lg">
                            <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="pt-2 mt-2 border-t">
                        <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="flex justify-end space-x-3 px-4 pb-3 pt-3 border-t -mx-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        setIsViewDialogOpen(false);
                        handleEdit(viewingProduct);
                      }}
                    >
                      <Edit className="w-4 h-4" />
                      Edit Product
                    </Button>
                    <Button
                      variant="danger"
                      size="sm"
                      onClick={() => {
                        setIsViewDialogOpen(false);
                        handleDelete(viewingProduct._id);
                      }}
                    >
                      <Trash2 className="w-4 h-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 pt-0 py-1 sm:flex-row sm:items-center sm:justify-between">
        <div className="relative max-w-md w-full">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 h-4 w-4" />
          <Input
            placeholder="Search products..."
            value={search}
            onChange={(e) => handleSearch(e.target.value)}
            className="pl-10"
          />
          <X
            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 h-4 w-4 cursor-pointer"
            onClick={() => handleSearch('')}
          />
        </div>
        
        {/* PAGINATION LIMIT DROPDOWN */}
        <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="px-3 py-2.5 rounded-md border border-input text-sm bg-white dark:bg-[#3B3B3B] focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50"
          >
            <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 */}
      <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 dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800">
              <TableHead 
                className="text-center cursor-pointer 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="text-center cursor-pointer 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 dark:bg-gray-900 hover:bg-gray-50 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="text-center py-8">
                  No products found
                </TableCell>
              </TableRow>
            ) : (
              products.map((product, index) => (
                <TableRow key={product._id} className="bg-white dark:bg-gray-900 hover:bg-gray-50 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="h-12 w-12 object-cover rounded mx-auto cursor-pointer"
                        onClick={() => openPreview(index)}
                      />
                    ) : (
                      <div className="h-12 w-12 bg-gray-100 rounded mx-auto flex items-center justify-center">
                        <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="p-1 bg-blue-400 text-xs text-white rounded-md cursor-pointer" 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="w-4 h-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Image">
                        <Button size="sm" variant="outline" onClick={() => openImageManager(product)}>
                          <ImageIcon className="w-4 h-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="View">
                        <Button size="sm" variant="outline" onClick={() => handleView(product)}>
                          <Eye className="w-4 h-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Edit">
                        <Button size="sm" variant="outline" onClick={() => handleEdit(product)}>
                          <Edit className="w-4 h-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Delete">
                        <Button size="sm" variant="outline" onClick={() => handleDelete(product._id)}>
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </Tooltip>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* Pagination */}
      {pagination.pages > 1 && (
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between mt-6">
          <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="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-1 mx-auto">
            <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              {/* Header */}
              <DialogHeader>
                <div>
                  <p className="text-xs text-white uppercase tracking-wide mb-0.5">Product</p>
                  <DialogTitle className="text-base text-white font-medium">
                    {selectedProduct?.name} — SKU Manager
                  </DialogTitle>
                </div>
                <X className="h-6 w-6 p-1 text-white cursor-pointer"
                  onClick={() => {
                    setIsSKUDialogOpen(false);
                  }}
                />
              </DialogHeader>
              <div className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-grow">
                <div className="max-h-[60vh] min-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2">
                  {/* Collapsible Form */}
                  <div className="border-b">
                    <button
                      type="button"
                      onClick={() => {
                        setIsSKUFormOpen(!isSKUFormOpen);
                        if (!isSKUFormOpen) resetSKUForm();
                      }}
                      className="w-full px-3 py-2 flex items-center justify-between hover:bg-muted/40 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="w-4 h-4 text-muted-foreground" />
                      ) : (
                        <ChevronDown className="w-4 h-4 text-muted-foreground" />
                      )}
                    </button>
                    
                    {isSKUFormOpen  &&  (
                      <div className="px-0 py-5 bg-muted/40 border-t mt-2">
                        <form onSubmit={handleSKUSubmit} className="space-y-4">
                          <div className="grid grid-cols-4 gap-3">
                            <div>
                              <Label className="text-xs mb-1.5 block">Color <span className="text-red-500">*</span></Label>
                              <select
                                value={skuForm.color}
                                onChange={(e) => setSkuForm(prev => ({ ...prev, color: e.target.value }))}
                                required
                                className="w-full px-3 py-2.5 rounded-md border border-input bg-white dark:bg-[#3B3B3B] text-sm focus:outline-none focus:ring-1 focus:ring-ring"
                              >
                                <option value="">Select color</option>
                                {displayColors.map((color) => (
                                  <option key={color._id} value={color._id}>{color.name}</option>
                                ))}
                              </select>
                            </div>
                            <div>
                              <Label className="text-xs mb-1.5 block">Size <span className="text-red-500">*</span></Label>
                              <select
                                value={skuForm.size}
                                onChange={(e) => setSkuForm(prev => ({ ...prev, size: e.target.value }))}
                                required
                                className="w-full px-3 py-2.5 rounded-md border border-input bg-white dark:bg-[#3B3B3B] text-sm focus:outline-none focus:ring-1 focus:ring-ring"
                              >
                                <option value="">Select size</option>
                                {sizes.map((size) => (
                                  <option key={size._id} value={size._id}>{size.name}</option>
                                ))}
                              </select>
                            </div>
                            <div>
                              <Label className="text-xs mb-1.5 block">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="text-xs mb-1.5 block">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="px-6 py-5 border-b bg-primary dark:bg-[#1f2a37] rounded-t-lg flex items-center justify-between">
                      <p className="text-xs font-medium text-white uppercase tracking-wide">Existing SKUs</p>
                      <span className="text-xs bg-muted border rounded-full px-2.5 py-0.5 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={`text-xs cursor-pointer hover:bg-muted/40 select-none ${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="h-3 w-3 text-muted-foreground/40" />
                                }
                              </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-xs text-right">Qty</TableHead>
                          {/* <TableHead className="text-xs text-right">MRP</TableHead> */}
                          <TableHead className="text-xs text-center pr-6">Action</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody className="dark:bg-[#1f2a37]">
                        {sortedSkus.length === 0 ? (
                          <TableRow>
                            <TableCell colSpan={7} className="text-center text-muted-foreground py-10 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="w-2.5 h-2.5 rounded-full border flex-shrink-0"
                                    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="font-mono text-xs text-muted-foreground">{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="text-right pr-6">
                                <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="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-2 mx-auto">
            <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              {/* Header */}
              <DialogHeader>
                <div>
                  <p className="text-xs text-white uppercase tracking-wide mb-0.5">Product</p>
                  <DialogTitle className="text-base font-medium">
                    {selectedProduct?.name} — Color images
                  </DialogTitle>
                </div>
                <X className="h-6 w-6 p-1 text-white cursor-pointer"
                  onClick={() => {
                    setIsImageDialogOpen(false);
                  }}
                />
              </DialogHeader>
              <div className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-grow">
                <div className="max-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2">
                  { colors.length > 0 ? (
                    <div className="border-b">
                    
                    <button
                      type="button"
                      onClick={() => {
                        setIsImageUploadOpen(!isImageUploadOpen);
                        if (!isImageUploadOpen) {
                          setSelectedColor(undefined);
                          setImageFiles([]);
                        }
                      }}
                      className="w-full px-6 py-4 flex items-center justify-between hover:bg-muted/40 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="w-4 h-4 text-muted-foreground" />
                      ) : (
                        <ChevronDown className="w-4 h-4 text-muted-foreground" />
                      )}
                    </button>
                    
                    {isImageUploadOpen && (
                      <div className="px-6 py-5 bg-muted/40 border-t">
                        <div className="space-y-4">
                          {/* Color pills - radio style */}
                          <div>
                            <p className="text-xs text-muted-foreground mb-2">
                              Select color <span className="text-red-500">*</span>
                            </p>
                            <div className="flex gap-2 flex-wrap">
                              {colors.map((color) => {
                                const isSelected = selectedColor === color._id;
                                return (
                                  <label
                                    key={color._id}
                                    className={`flex items-center gap-2 px-3 py-1.5 rounded-full border cursor-pointer text-sm transition-all duration-150 ${
                                      isSelected
                                        ? "bg-background text-primary-foreground border-primary shadow-md scale-[1.03]"
                                        : "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="w-3 h-3 rounded-full flex-shrink-0 border"
                                      style={{ backgroundColor: color.hexCode }}
                                    />
                                    <span className="font-medium">{color.name}</span>
                                  </label>
                                );
                              })}
                            </div>
                          </div>

                          {/* File drop zone */}
                          <div>
                            <p className="text-xs text-muted-foreground mb-2">
                              Images <span className="text-red-500">*</span>
                              <span className="text-muted-foreground/60 ml-1">Max 2MB each</span>
                            </p>
                            <label className="flex flex-col items-center justify-center border border-dashed rounded-md px-4 py-5 cursor-pointer hover:bg-muted/40 transition-colors bg-background">
                              <Upload className="w-5 h-5 text-muted-foreground mb-2" />
                              <p className="text-sm text-muted-foreground">Click to select images</p>
                              <p className="text-xs text-muted-foreground/60 mt-0.5">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-xs text-muted-foreground mb-2">
                                {imageFiles.length} image{imageFiles.length > 1 ? 's' : ''} ready to upload
                              </p>
                              <div className="flex gap-2 flex-wrap">
                                {imageFiles.map((file, index) => (
                                  <div key={index} className="relative">
                                    <img
                                      src={URL.createObjectURL(file)}
                                      className="w-14 h-14 object-cover rounded-md border"
                                    />
                                    <button
                                      type="button"
                                      onClick={() => setImageFiles(prev => prev.filter((_, i) => i !== index))}
                                      className="absolute -top-1.5 -right-1.5 w-4 h-4 rounded-full bg-red-100 border border-red-200 flex items-center justify-center"
                                    >
                                      <X className="w-2.5 h-2.5 text-red-600" />
                                    </button>
                                    <div className="absolute bottom-0 left-0 right-0 bg-black/50 text-white text-center rounded-b-md py-px" 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="w-4 h-4 mr-2" />
                            {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="px-6 py-3 flex items-center justify-between border-b">
                      <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Uploaded by color</p>
                      <span className="text-xs text-muted-foreground border rounded-full px-2.5 py-0.5">
                        {colorImages.length} color{colorImages.length !== 1 ? 's' : ''}
                      </span>
                    </div>

                    <div className="p-6 flex flex-col gap-4">
                      {colorImages.length === 0 ? (
                        <div className="text-center py-8 text-sm text-muted-foreground border border-dashed rounded-lg">
                          No images uploaded yet. Select a color above and upload images to get started.
                        </div>
                      ) : (
                        colorImages.map((colorImage) => (
                          <div key={colorImage?._id} className="border rounded-lg overflow-hidden">
                            {/* Color row header */}
                            <div className="px-4 py-3 bg-muted/40 border-b flex items-center justify-between">
                              <div className="flex items-center gap-2">
                                <span
                                  className="w-3 h-3 rounded-full flex-shrink-0"
                                  style={{ backgroundColor: colorImage?.color?.hexCode }}
                                />
                                <span className="text-sm font-medium capitalize">{colorImage?.color?.name}</span>
                                <span className="text-xs text-muted-foreground border rounded-full px-2 py-0.5">
                                  {colorImage?.images?.length} image{colorImage?.images?.length !== 1 ? 's' : ''}
                                </span>
                              </div>
                              <label className="flex items-center gap-1.5 px-3 py-1.5 text-xs border rounded-md bg-background cursor-pointer hover:bg-muted/60 transition-colors text-muted-foreground">
                                <Plus className="w-3 h-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="p-4 flex gap-3 flex-wrap">
                              {colorImage?.images?.map((image, index) => (
                                <div key={index} className="relative group">
                                  <img
                                    src={image.url}
                                    alt={image.altText || `${colorImage?.color?.name} ${index + 1}`}
                                    className={`w-20 h-20 object-cover rounded-md border-2 ${
                                      image.isPrimary ? 'border-green-500' : 'border-transparent border border-border'
                                    }`}
                                  />
                                  {/* {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 bg-black/0 group-hover:bg-black/50 transition-all rounded-md flex flex-col items-center justify-center gap-1 opacity-0 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="px-2 py-1 bg-red-500/90 rounded text-xs font-medium text-white hover:bg-red-500"
                                    >
                                      Delete
                                    </button>
                                  </div>
                                </div>
                              ))}
                            </div>
                          </div>
                        ))
                      )}
                    </div>
                  </div>
                  </div>
                  
                ) : (
                    <div className="px-6 py-5 border-b bg-muted/40">
                      <p className="text-sm text-muted-foreground">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>
//   );
// }