'use client';

import * as React from 'react';
import type { Metadata } from 'next';
import dynamic from 'next/dynamic';
import Button from '@mui/material/Button';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { Download as DownloadIcon } from '@phosphor-icons/react/dist/ssr/Download';
import { Plus as PlusIcon } from '@phosphor-icons/react/dist/ssr/Plus';
import { PlusCircle } from '@phosphor-icons/react/dist/ssr/PlusCircle';
import { Upload as UploadIcon } from '@phosphor-icons/react/dist/ssr/Upload';
import axios, { AxiosError } from 'axios';
import dayjs from 'dayjs';

import { config } from '@/config';
import type { Customer } from '@/components/dashboard/about/about-table';
import { MerchandiseFilters } from '@/components/dashboard/merchandise/merchandise-filters';
import { MerchandiseTable } from '@/components/dashboard/merchandise/merchandise-table';

import 'react-quill/dist/quill.snow.css';

import { useRouter } from 'next/navigation';
import {
  Checkbox,
  Chip,
  FormControl,
  FormControlLabel,
  Grid,
  IconButton,
  InputLabel,
  MenuItem,
  Modal,
  Pagination,
  Select,
  SelectChangeEvent,
  TablePagination,
  TextField,
  Tooltip,
  useTheme,
} from '@mui/material';
import { Box, height, width } from '@mui/system';
import { Palette, Upload } from '@phosphor-icons/react';
import { ColorPicker, useColor, type IColor } from 'react-color-palette';
import { toast, Toaster } from 'react-hot-toast';

import { Integration, IntegrationCard } from '@/components/dashboard/integrations/integrations-card';
import { MerchandiseCategoryCard } from '@/components/dashboard/merchandise/merchandiseCategory-card';
import { AppLoader } from '@/components/core/app-loader';
import { ProductsCard } from '@/components/dashboard/merchandise/products-card';
import { deleteMerchandiseCategory, deleteProduct, updateMerchandiseCategory, updateProduct } from '@/services/merchandise.service';
import { getProductColorCss, normalizeColorForApi, toPickerHex } from '@/utils/product-color';
import { getPrimaryProductImage, getProductImageDisplayUrl } from '@/utils/product-image';

import 'react-color-palette/css';

import { Close } from '@mui/icons-material';

const ReactQuill = dynamic(() => import('react-quill'), { ssr: false });

// export const metadata = { title: `About | Dashboard | ${config.site.name}` } satisfies Metadata;

const liveUrl = process.env.NEXT_PUBLIC_LIVE_API_URL;

const boxStyle = {
  position: 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)',
  width: '90%',
  maxWidth: 900,
  maxHeight: '95vh',
  bgcolor: 'background.paper',
  border: 'none',
  outline: 'none',
  boxShadow: 24,
  p: 4,
  borderRadius: '25px',
  overflowY: 'auto',
};

export interface MerchandiseCategory {
  _id: string;
  isDeleted: boolean;
  categoryName: string;
  image: string;
  createdAt: string;
  updatedAt: string;
  mediaData?: MediaData;
}

interface Data {
  data: MerchandiseCategory[];
  totalCount: number;
}

interface MediaData {
  _id: string;
  fileName: string;
  fileType: string;
  isDeleted: boolean;
  createdAt: string;
  updatedAt: string;
  fileUrl: string;
  thumbnail: string | null;
}

interface Product {
  _id: string;
  productName: string;
  productDescription: string;
  quantity: number;
  price: number;
  colors: string[];
  sizes: string[];
  createdAt: string;
  productImageData: MediaData[];
  categoryName: string;
  merchandiseCategory?: string;
}

interface ProductData {
  data: Product[];
  totalProducts: number;
}

export default function Page(): React.JSX.Element {
  const router = useRouter();
  const theme = useTheme();
  const [open, setOpen] = React.useState(false);
  const handleOpen = () => setOpen(true);
  const handleClose = () => {
    setOpen(false);
    setCategoryName('');
    setFile(null);
    setImagePreview(null);
  };
  const [open1, setOpen1] = React.useState(false);
  const handleOpen1 = () => {
    setExistingProductMediaIds([]);
    setRemovedProductMediaIds([]);
    setProductImageInputKey((currentKey) => currentKey + 1);
    setOpen1(true);
  };
  const handleClose1 = () => setOpen1(false);
  const [categoryName, setCategoryName] = React.useState('');
  const [file, setFile] = React.useState<File | null>(null);
  const [productName, setProductName] = React.useState('');
  const [productDescription, setProductDescription] = React.useState('');
  const [quantity, setQuantity] = React.useState('');
  const [price, setPrice] = React.useState('');
  const [colors, setColors] = React.useState<string[]>([]);
  const [sizes, setSizes] = React.useState<string[]>([]);
  const [size, setSize] = React.useState<string>('');
  const [productFile, setProductFile] = React.useState<File | null>(null);
  const [data, setData] = React.useState<Data | null>(null);
  const [products, setProducts] = React.useState<ProductData | null>(null);
  const [selectedCategoryId, setSelectedCategoryId] = React.useState('');
  const [selectedTab, setSelectedTab] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [page, setPage] = React.useState(0);
  const [searchQuery, setSearchQuery] = React.useState('');
  const [categoryRowsPerPage, setCategoryRowsPerPage] = React.useState(10);
  const [categoryPage, setCategoryPage] = React.useState(0);
  const [categorySearchQuery, setCategorySearchQuery] = React.useState('');
  const [imagePreview, setImagePreview] = React.useState<string | null>(null);
  const [productImagePreview, setProductImagePreview] = React.useState<string | null>(null);
  const [existingProductMediaIds, setExistingProductMediaIds] = React.useState<string[]>([]);
  const [removedProductMediaIds, setRemovedProductMediaIds] = React.useState<string[]>([]);
  const [productImageInputKey, setProductImageInputKey] = React.useState(0);
  const [isLoading, setIsLoading] = React.useState<boolean>(false);
  const [categoriesLoading, setCategoriesLoading] = React.useState(false);
  const [productsLoading, setProductsLoading] = React.useState(false);
  const [color, setColor] = useColor('#000000');
  const [selectedCategory, setSelectedCategory] = React.useState<MerchandiseCategory | null>(null);
  const [editModalOpen, setEditModalOpen] = React.useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = React.useState(false);
  const [detailModalOpen, setDetailModalOpen] = React.useState(false);
  const [selectedProduct, setSelectedProduct] = React.useState<Product | null>(null);
  const [editProductModalOpen, setEditProductModalOpen] = React.useState(false);
  const [deleteProductDialogOpen, setDeleteProductDialogOpen] = React.useState(false);
  const [detailProductModalOpen, setDetailProductModalOpen] = React.useState(false);
  const [refreshTrigger, setRefreshTrigger] = React.useState(0);
  const [productsSectionKey, setProductsSectionKey] = React.useState(0);
  const [productImageOverrides, setProductImageOverrides] = React.useState<Record<string, string>>({});
  const [productImageVersionKeys, setProductImageVersionKeys] = React.useState<Record<string, number>>({});
  const [updatingProductId, setUpdatingProductId] = React.useState<string | null>(null);

  // const colorsSet = ["Blue", "Green", "Black", "Yellow", "White", "Grey", "Purple", "Pink"];
  // const firstRowColors = colorsSet.slice(0, 4);
  // const secondRowColors = colorsSet.slice(4, 8);

  const getDisplayProductImageUrl = React.useCallback(
    (product: Product) => {
      const primaryImage = getPrimaryProductImage(product.productImageData);

      return getProductImageDisplayUrl(primaryImage?.fileUrl, {
        overrideUrl: productImageOverrides[product._id],
        cacheKey:
          productImageVersionKeys[product._id] ??
          `${productsSectionKey}-${primaryImage?.updatedAt ?? primaryImage?._id ?? product._id}`,
      });
    },
    [productImageOverrides, productImageVersionKeys, productsSectionKey]
  );

  const clearProductImageOverride = React.useCallback((productId: string) => {
    setProductImageOverrides((prev) => {
      const overrideUrl = prev[productId];
      if (overrideUrl?.startsWith('blob:')) {
        URL.revokeObjectURL(overrideUrl);
      }

      if (!overrideUrl) {
        return prev;
      }

      const next = { ...prev };
      delete next[productId];
      return next;
    });
  }, []);

  const sizeSet = ['small', 'medium', 'large', 'extralarge'];

  const handleTabChange = (_event: React.SyntheticEvent, newValue: number) => {
    setSelectedTab(newValue);
  };

  const handleSearchQueryChange = React.useCallback((query: string) => {
    setSearchQuery(query);
    setPage(0);
  }, []);

  const handleCategorySearchQueryChange = React.useCallback((query: string) => {
    setCategorySearchQuery(query);
    setCategoryPage(0);
  }, []);

  React.useEffect(() => {
    if (typeof window === 'undefined') return;

    const token = localStorage.getItem('token');
    let cancelled = false;

    const fetchMerchandiseCategoryData = async () => {
      try {
        setCategoriesLoading(true);
        const response = await axios.get(`${liveUrl}/api/v1/admin/fetchAllMerchandiseCategory`, {
          headers: {
            authorization: `${token}`,
          },
          params: {
            skip: categoryPage,
            limit: categoryRowsPerPage,
            categoryName: categorySearchQuery || undefined,
          },
        });

        if (!cancelled && response.data.data) {
          setData(response.data.data);
        }
      } catch (error: unknown) {
        if (!cancelled) {
          const message =
            error instanceof AxiosError && error.response?.data?.message
              ? error.response.data.message
              : error instanceof Error
                ? error.message
                : 'Something went wrong...';
          console.log(message);
        }
      } finally {
        if (!cancelled) {
          setCategoriesLoading(false);
        }
      }
    };

    void fetchMerchandiseCategoryData();

    return () => {
      cancelled = true;
    };
  }, [categoryPage, categoryRowsPerPage, categorySearchQuery, refreshTrigger]);

  const refetchProducts = React.useCallback(async (options?: { silent?: boolean }): Promise<ProductData | null> => {
    if (typeof window === 'undefined') return null;

    const token = localStorage.getItem('token');
    const silent = options?.silent ?? false;

    try {
      if (!silent) {
        setProductsLoading(true);
      }
      const response = await axios.get(`${liveUrl}/api/v1/admin/fetchAllProducts`, {
        headers: {
          authorization: `${token}`,
        },
        params: {
          skip: page,
          limit: rowsPerPage,
          productName: searchQuery || undefined,
        },
      });

      if (response.data.data) {
        setProducts(response.data.data);
        return response.data.data;
      }

      return null;
    } catch (error: unknown) {
      const message =
        error instanceof AxiosError && error.response?.data?.message
          ? error.response.data.message
          : error instanceof Error
            ? error.message
            : 'Something went wrong...';
      console.log(message);
      return null;
    } finally {
      if (!silent) {
        setProductsLoading(false);
      }
    }
  }, [page, rowsPerPage, searchQuery]);

  const refreshProductsList = React.useCallback(async () => {
    const refreshedProducts = await refetchProducts({ silent: true });
    setProductsSectionKey((currentKey) => currentKey + 1);
    return refreshedProducts;
  }, [refetchProducts]);

  React.useEffect(() => {
    if (typeof window === 'undefined' || selectedTab !== 1) return;

    void refetchProducts();
  }, [selectedTab, refreshTrigger, refetchProducts]);

  React.useEffect(() => {
    if (typeof window === 'undefined' || products || selectedTab === 1) return;

    const token = localStorage.getItem('token');
    let cancelled = false;

    const prefetchProducts = async () => {
      try {
        const response = await axios.get(`${liveUrl}/api/v1/admin/fetchAllProducts`, {
          headers: {
            authorization: `${token}`,
          },
          params: {
            skip: 0,
            limit: rowsPerPage,
          },
        });

        if (!cancelled && response.data.data) {
          setProducts(response.data.data);
        }
      } catch {
        // Prefetch silently; active tab fetch handles visible errors.
      }
    };

    void prefetchProducts();

    return () => {
      cancelled = true;
    };
  }, [products, selectedTab, rowsPerPage]);

  const tabLoading = selectedTab === 0 ? categoriesLoading : productsLoading;

  const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newRowsPerPage = parseInt(event.target.value, 10);
    setRowsPerPage(newRowsPerPage);
    setPage(0); // Reset to the first page
  };

  const handleChangePage = (event: React.MouseEvent<HTMLButtonElement> | null, newPage: number) => {
    console.log(newPage);

    setPage(newPage);
  };

  const handleCategoryChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newRowsPerPage = parseInt(event.target.value, 10);
    setCategoryRowsPerPage(newRowsPerPage);
    setCategoryPage(0); // Reset to the first page
  };

  const handleCategoryChangePage = (event: React.MouseEvent<HTMLButtonElement> | null, newPage: number) => {
    console.log(newPage);

    setCategoryPage(newPage);
  };

  const handleCategoryName: React.ChangeEventHandler<HTMLInputElement> = (event) => {
    setCategoryName(event.target.value);
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    console.log('event.target.files', event.target.files);
    if (event.target.files && event.target.files[0]) {
      setFile(event.target.files[0]);

      const previewUrl = URL.createObjectURL(event.target.files[0]);
      setImagePreview(previewUrl);
      console.log('Image Preview: ', previewUrl);
      event.target.value = '';
    }
  };

  const handleRemoveImage = () => {
    setFile(null);
    setImagePreview(null);
  };

  const handleProductName = (event: React.ChangeEvent<HTMLInputElement>) => {
    setProductName(event.target.value);
  };

  const handleDescription = (event: React.ChangeEvent<HTMLInputElement>) => {
    setProductDescription(event.target.value);
  };

  const handleQuantity = (event: React.ChangeEvent<HTMLInputElement>) => {
    setQuantity(event.target.value);
  };

  const handlePrice = (event: React.ChangeEvent<HTMLInputElement>) => {
    setPrice(event.target.value);
  };

  const handleFileChange1 = (event: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = event.target.files?.[0];
    if (!selectedFile) return;

    if (productImagePreview?.startsWith('blob:')) {
      URL.revokeObjectURL(productImagePreview);
    }

    if (existingProductMediaIds.length > 0) {
      setRemovedProductMediaIds(existingProductMediaIds);
    }

    setProductFile(selectedFile);
    setProductImagePreview(URL.createObjectURL(selectedFile));
    event.target.value = '';
  };

  const handleRemoveProductImage = () => {
    if (productImagePreview?.startsWith('blob:')) {
      URL.revokeObjectURL(productImagePreview);
    }

    if (existingProductMediaIds.length > 0) {
      setRemovedProductMediaIds(existingProductMediaIds);
    }

    setProductFile(null);
    setProductImagePreview(null);
  };

  // to be continued
  // const handleColorChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  //   const selectedColor = event.target.name;
  //   setColors((prevColors) => {
  //     if (event.target.checked) {
  //       // Add color to array if checked and not already present
  //       return [...prevColors, selectedColor];
  //     } else {
  //       // Remove color from array if unchecked
  //       return prevColors.filter((color) => color !== selectedColor);
  //     }
  //   });
  // };

  const handleAddColor = () => {
    if (!colors.includes(color.hex)) {
      setColors([...colors, color.hex]);
    }
  };

  const handleColorChange = (newColor: IColor) => {
    setColor(newColor);
    setColors([normalizeColorForApi(newColor.hex)]);
  };

  const resetColorPicker = () => {
    setColor((prev) => ({ ...prev, hex: '#000000' }));
    setColors([]);
  };

  // const handleSizeChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  //   const selectedSize = event.target.name;
  //   setSizes((prevSize) => {
  //     if (event.target.checked) {
  //       // Add color to array if checked and not already present
  //       return [...prevSize, selectedSize];
  //     } else {
  //       // Remove color from array if unchecked
  //       return prevSize.filter((size) => size !== selectedSize);
  //     }
  //   });
  // };

  const handleError = (msg: string) => {
    toast.error(msg);
  };

  const handleCategoryChange = (event: SelectChangeEvent<string>) => {
    const selectedCategory = (data as unknown as Data)?.data.find((item) => item._id === event.target.value);

    if (selectedCategory) {
      setSelectedCategoryId(selectedCategory._id);
      console.log(selectedCategory._id);
    } else {
      console.error('Selected category not found');
    }
  };
  // const handleSizeChange = (event: SelectChangeEvent<string>) => {
  //   const selectedCategory = (data as unknown as Data)?.data.find((item) => item._id === event.target.value);

  //   if (selectedCategory) {
  //     setSelectedCategoryId(selectedCategory._id);
  //     console.log(selectedCategory._id);
  //   } else {
  //     console.error('Selected category not found');
  //   }
  // };

  const handleSuccess = (msg: string) => {
    toast.success(msg);
    if (msg !== 'Product added successfully!') {
      setRefreshTrigger((prev) => prev + 1);
    }
    if (msg === 'Category added successfully!') {
      setCategoryName('');
      setFile(null);
      setImagePreview(null);
      handleClose();
    }
    if (msg === 'Product added successfully!') {
      setProductName('');
      setProductDescription('');
      setQuantity('');
      setPrice('');
      setColors([]);
      setSizes([]);
      setProductFile(null);
      setProductImagePreview(null);
      setExistingProductMediaIds([]);
      setRemovedProductMediaIds([]);
      setProductImageInputKey((currentKey) => currentKey + 1);
      setSelectedCategoryId('');
      setSize('');
      resetColorPicker();
      handleClose1();
    }
  };

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    try {
      const token = localStorage.getItem('token');

      const formData = new FormData();
      formData.append('categoryName', categoryName);
      if (file) {
        formData.append('media', file);
      }

      const response = await axios.post(`${liveUrl}/api/v1/admin/createMerchandiseCategory`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          authorization: token,
        },
      });

      return handleSuccess('Category added successfully!');
    } catch (e: unknown) {
      if (e instanceof AxiosError && e.response) {
        return handleError(e.response.data.message);
      } else if (e instanceof Error) {
        return handleError(e.message);
      } else {
        return handleError('Something went wrong...');
      }
    }
  };

  const handleSubmit1 = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    try {
      const token = localStorage.getItem('token');
      const formData = new FormData();
      formData.append('merchandiseCategory', selectedCategoryId);
      formData.append('productName', productName);
      formData.append('productDescription', productDescription);
      if (productFile) {
        formData.append('media', productFile);
      }
      formData.append('quantity', quantity);
      formData.append('price', price);
      formData.append('colors[]', normalizeColorForApi(color.hex));
      formData.append('sizes[]', size);
      // colors.forEach((color) => formData.append('colors[]', color));
      // formData.append("colors", colors);
      // sizes.forEach((size) => );
      // formData.append("sizes", sizes);

      await axios.post(`${liveUrl}/api/v1/admin/addProduct`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          authorization: token,
        },
      });

      await refreshProductsList();
      return handleSuccess('Product added successfully!');
    } catch (e: unknown) {
      if (e instanceof AxiosError && e.response) {
        return handleError(e.response.data.message);
      } else if (e instanceof Error) {
        return handleError(e.message);
      } else {
        return handleError('Something went wrong...');
      }
    }
  };

  const handleRemoveColor = (index: number) => {
    const updatedColors = colors.filter((_, i) => i !== index);

    setColors(updatedColors);
  };

  // Handlers for card actions
  const handleEditCategory = (category: MerchandiseCategory) => {
    setSelectedCategory(category);
    setCategoryName(category.categoryName);
    setFile(null);
    setImagePreview(
      category.mediaData?.fileUrl ||
        (category.mediaData?.fileName ? `${liveUrl}/${category.mediaData.fileName}` : null)
    );
    setEditModalOpen(true);
  };
  const handleDeleteCategory = (category: MerchandiseCategory) => {
    setSelectedCategory(category);
    setDeleteDialogOpen(true);
  };
  const handleDetailCategory = (category: MerchandiseCategory) => {
    setSelectedCategory(category);
    setDetailModalOpen(true);
  };
  const handleCloseEditModal = () => {
    setEditModalOpen(false);
    setSelectedCategory(null);
    setCategoryName('');
    setImagePreview(null);
    setFile(null);
  };
  const handleCloseDeleteDialog = () => {
    setDeleteDialogOpen(false);
    setSelectedCategory(null);
  };
  const handleCloseDetailModal = () => {
    setDetailModalOpen(false);
    setSelectedCategory(null);
  };

  const handleEditSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!selectedCategory) return;

    try {
      setIsLoading(true);

      const response = await updateMerchandiseCategory(selectedCategory._id, {
        categoryName,
        media: file ?? undefined,
      });

      toast.success(response.message || 'Merchandise category updated successfully');
      handleCloseEditModal();
      setRefreshTrigger((prev) => prev + 1);
      setIsLoading(false);
    } catch (e: unknown) {
      setIsLoading(false);
      if (e instanceof AxiosError && e.response?.data?.message) {
        toast.error(e.response.data.message);
      } else if (e instanceof Error) {
        toast.error(e.message);
      } else {
        toast.error('Failed to update category');
      }
    }
  };
  const handleDeleteConfirm = async () => {
    if (!selectedCategory) return;

    try {
      setIsLoading(true);

      const response = await deleteMerchandiseCategory(selectedCategory._id);

      toast.success(response.message || 'Merchandise category deleted successfully');
      setDeleteDialogOpen(false);
      setSelectedCategory(null);
      setRefreshTrigger((prev) => prev + 1);
      setIsLoading(false);
    } catch (e: unknown) {
      setIsLoading(false);
      if (e instanceof AxiosError && e.response?.data?.message) {
        toast.error(e.response.data.message);
      } else if (e instanceof Error) {
        toast.error(e.message);
      } else {
        toast.error('Failed to delete category');
      }
    }
  };

  // Handlers for product card actions
  const handleEditProduct = (product: Product) => {
    setSelectedProduct(product);
    setProductName(product.productName);
    setProductDescription(product.productDescription);
    setQuantity(product.quantity.toString());
    setPrice(product.price.toString());
    setColors(product.colors.map(normalizeColorForApi));
    setSizes(product.sizes);
    setSize(product.sizes[0] ?? '');
    setColor((prev) => ({ ...prev, hex: toPickerHex(product.colors[0]) }));
    setProductImagePreview(getPrimaryProductImage(product.productImageData)?.fileUrl ?? null);
    setProductFile(null);
    setExistingProductMediaIds(product.productImageData.map((media) => media._id).filter(Boolean));
    setRemovedProductMediaIds([]);
    setProductImageInputKey((currentKey) => currentKey + 1);

    if (product.merchandiseCategory) {
      setSelectedCategoryId(product.merchandiseCategory);
    } else {
      const matchedCategory = data?.data.find((category) => category.categoryName === product.categoryName);
      setSelectedCategoryId(matchedCategory?._id ?? '');
    }

    setEditProductModalOpen(true);
  };
  const handleDeleteProduct = (product: Product) => {
    setSelectedProduct(product);
    setDeleteProductDialogOpen(true);
  };
  const handleDetailProduct = (product: Product) => {
    setSelectedProduct(product);
    setDetailProductModalOpen(true);
  };
  const handleCloseEditProductModal = () => {
    setEditProductModalOpen(false);
    setSelectedProduct(null);
    setProductName('');
    setProductDescription('');
    setQuantity('');
    setPrice('');
    setColors([]);
    setSizes([]);
    setSize('');
    setSelectedCategoryId('');
    if (productImagePreview?.startsWith('blob:')) {
      URL.revokeObjectURL(productImagePreview);
    }
    setProductImagePreview(null);
    setProductFile(null);
    setExistingProductMediaIds([]);
    setRemovedProductMediaIds([]);
    resetColorPicker();
  };
  const handleCloseDeleteProductDialog = () => {
    setDeleteProductDialogOpen(false);
    setSelectedProduct(null);
  };
  const handleCloseDetailProductModal = () => {
    setDetailProductModalOpen(false);
    setSelectedProduct(null);
  };

  const handleEditProductSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!selectedProduct) return;

    const productId = selectedProduct._id;
    const uploadedProductFile = productFile;
    let temporaryImageUrl: string | null = null;

    if (uploadedProductFile) {
      temporaryImageUrl = URL.createObjectURL(uploadedProductFile);

      setProductImageOverrides((prev) => {
        const existingOverride = prev[productId];
        if (existingOverride?.startsWith('blob:')) {
          URL.revokeObjectURL(existingOverride);
        }

        return { ...prev, [productId]: temporaryImageUrl! };
      });
    }

    const colorsToSend = color.hex ? [normalizeColorForApi(color.hex)] : colors.map(normalizeColorForApi);
    const sizesToSend = size ? [size] : sizes;
    const categoryName =
      data?.data.find((category) => category._id === selectedCategoryId)?.categoryName ??
      selectedProduct.categoryName;

    setProducts((prev) => {
      if (!prev) return prev;

      return {
        ...prev,
        data: prev.data.map((product) =>
          product._id === productId
            ? {
                ...product,
                productName,
                productDescription,
                quantity: Number(quantity),
                price: Number(price),
                colors: colorsToSend,
                sizes: sizesToSend,
                categoryName,
                merchandiseCategory: selectedCategoryId,
              }
            : product
        ),
      };
    });

    setProductsSectionKey((currentKey) => currentKey + 1);
    handleCloseEditProductModal();

    try {
      setIsLoading(true);
      setUpdatingProductId(productId);

      const response = await updateProduct(productId, {
        merchandiseCategory: selectedCategoryId || undefined,
        productName,
        productDescription,
        quantity,
        price,
        colors: colorsToSend,
        sizes: sizesToSend,
        media: uploadedProductFile ?? undefined,
      });

      await refreshProductsList();

      if (uploadedProductFile) {
        setProductImageVersionKeys((prev) => ({ ...prev, [productId]: Date.now() }));
      }

      clearProductImageOverride(productId);

      toast.success(response.message || 'Product updated successfully');
    } catch (e: unknown) {
      if (temporaryImageUrl) {
        clearProductImageOverride(productId);
      }

      await refreshProductsList();

      if (e instanceof AxiosError && e.response?.data?.message) {
        toast.error(e.response.data.message);
      } else if (e instanceof Error) {
        toast.error(e.message);
      } else {
        toast.error('Failed to update product');
      }
    } finally {
      setIsLoading(false);
      setUpdatingProductId(null);
    }
  };
  const handleDeleteProductConfirm = async () => {
    if (!selectedProduct) return;

    try {
      setIsLoading(true);

      const response = await deleteProduct(selectedProduct._id);

      await refreshProductsList();
      toast.success(response.message || 'Product deleted successfully');
      setDeleteProductDialogOpen(false);
      setSelectedProduct(null);
    } catch (e: unknown) {
      if (e instanceof AxiosError && e.response?.data?.message) {
        toast.error(e.response.data.message);
      } else if (e instanceof Error) {
        toast.error(e.message);
      } else {
        toast.error('Failed to delete product');
      }
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Box sx={{ 
      bgcolor: theme.palette.mode === 'dark' ? '#0f172a' : '#fafbfc', 
      minHeight: '100vh', 
      p: 3 
    }}>
      <Toaster />
      {/* Modern Header Section */}
      <Stack
        direction="row"
        justifyContent="space-between"
        alignItems="center"
        sx={{
          mb: 4,
          p: 3,
          borderRadius: 4,
          background: '#FFDD31',
          color: '#0B0504',
        }}
      >
        <Box>
          <Typography variant="h4" fontWeight={700} gutterBottom>
            Merchandise Management
          </Typography>
          <Typography variant="body1" sx={{ opacity: 0.9 }}>
            Manage product categories and inventory for your store
          </Typography>
        </Box>
        <Stack direction="row" spacing={2}>
          <Button
            variant="contained"
            startIcon={<PlusIcon size={20} />}
            onClick={handleOpen}
            sx={{
              bgcolor: 'rgba(11, 5, 4, 0.8)',
              color: '#FFDD31',
              borderRadius: 3,
              px: 3,
              py: 1.5,
              fontWeight: 600,
              border: '1px solid rgba(11, 5, 4, 0.9)',
              '&:hover': {
                bgcolor: 'rgba(11, 5, 4, 0.9)',
                transform: 'translateY(-2px)',
              },
              transition: 'all 0.3s ease',
            }}
          >
            Create Category
          </Button>
          <Button
            variant="contained"
            startIcon={<PlusIcon size={20} />}
            onClick={handleOpen1}
            sx={{
              bgcolor: 'rgba(11, 5, 4, 0.8)',
              color: '#FFDD31',
              borderRadius: 3,
              px: 3,
              py: 1.5,
              fontWeight: 600,
              border: '1px solid rgba(11, 5, 4, 0.9)',
              '&:hover': {
                bgcolor: 'rgba(11, 5, 4, 0.9)',
                transform: 'translateY(-2px)',
              },
              transition: 'all 0.3s ease',
            }}
          >
            Create Product
          </Button>
        </Stack>
      </Stack>
      <MerchandiseFilters
        value={selectedTab}
        onChange={handleTabChange}
        onCategorySearch={handleCategorySearchQueryChange}
        onSearchChange={handleSearchQueryChange}
      />
      <Box 
        sx={{ 
          position: 'relative', 
          p: 3, 
          borderRadius: 4,
          background: theme.palette.mode === 'dark' 
            ? 'linear-gradient(145deg, #1e293b 0%, #334155 100%)' 
            : 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
          border: theme.palette.mode === 'dark' 
            ? '1px solid #475569' 
            : '1px solid rgba(255, 255, 255, 0.2)',
          boxShadow: theme.palette.mode === 'dark' 
            ? '0 8px 32px rgba(0, 0, 0, 0.3)' 
            : '0 8px 32px rgba(0, 0, 0, 0.08)',
          minHeight: '400px',
          overflow: 'hidden',
        }}
      >
        {tabLoading && <AppLoader fill size="lg" label={`Loading ${selectedTab === 0 ? 'categories' : 'products'}...`} />}
      <Box key={productsSectionKey} sx={{ display: selectedTab === 1 ? 'block' : 'none', minHeight: 320 }}>
          <Grid container spacing={3} sx={{ mt: '5px' }}>
            {products?.data.map((product) => (
              <Grid key={`${product._id}-${productsSectionKey}`} md={4} lg={4} sm={6} xs={12} p={1.5}>
                <Box sx={{ 
                  borderRadius: 3, 
                  boxShadow: 2, 
                  bgcolor: theme.palette.mode === 'dark' ? '#334155' : '#fff', 
                  height: '100%', 
                  position: 'relative', 
                  zIndex: 1,
                  opacity: updatingProductId === product._id ? 0.72 : 1,
                  transition: 'opacity 0.2s ease',
                }}>
                  <ProductsCard
                    product={product}
                    displayImageUrl={getDisplayProductImageUrl(product)}
                    onEdit={handleEditProduct}
                    onDelete={handleDeleteProduct}
                    onDetail={handleDetailProduct}
                  />
                </Box>
              </Grid>
            ))}
          </Grid>
          <Box sx={{ display: 'flex', justifyContent: 'center', mt:3 }}>
            {products && (
              <TablePagination
                sx={{ mt: '-25px' }}
                rowsPerPageOptions={[10, 8, 5]}
                component="div"
                count={products.totalProducts}
                rowsPerPage={rowsPerPage}
                page={page}
                onPageChange={handleChangePage}
                onRowsPerPageChange={handleChangeRowsPerPage}
              />
            )}
          </Box>
      </Box>
      <Box sx={{ display: selectedTab === 0 ? 'block' : 'none' }}>
          <Grid container spacing={3} sx={{ mt: '5px' }}>
            {data?.data.map((category) => (
              <Grid key={category._id} md={4} lg={4} sm={6} xs={12} p={1.5}>
                <Box sx={{ 
                  borderRadius: 3, 
                  boxShadow: 2, 
                  bgcolor: theme.palette.mode === 'dark' ? '#334155' : '#fff', 
                  height: '100%', 
                  position: 'relative', 
                  zIndex: 1 
                }}>
                  <MerchandiseCategoryCard
                    merchandise={category}
                    onEdit={handleEditCategory}
                    onDelete={handleDeleteCategory}
                    onDetail={handleDetailCategory}
                  />
                </Box>
              </Grid>
            ))}
          </Grid>
          <Box sx={{ display: 'flex', justifyContent: 'center', mt:3 }}>
            {data && (
              <TablePagination
                sx={{ mt: '-25px' }}
                rowsPerPageOptions={[10, 8, 5]}
                component="div"
                count={data.totalCount}
                rowsPerPage={categoryRowsPerPage}
                page={categoryPage}
                onPageChange={handleCategoryChangePage}
                onRowsPerPageChange={handleCategoryChangeRowsPerPage}
              />
            )}
          </Box>
      </Box>
      </Box>
      {/* Create Category Modal */}
      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="create-category-modal"
        style={{ backdropFilter: 'blur(5px)' }}
      >
        <Box sx={boxStyle}>
          <IconButton
            onClick={handleClose}
            sx={{ position: 'absolute', top: 12, right: 12 }}
          >
            <Close />
          </IconButton>
          <Typography id="create-category-modal" variant="h6" component="h1" sx={{ fontWeight: 'bold', mb: 2 }}>
            Create Category
          </Typography>
          <form onSubmit={handleSubmit}>
            <TextField
              required
              fullWidth
              margin="normal"
              label="Category Name"
              variant="outlined"
              value={categoryName}
              onChange={handleCategoryName}
              sx={{
                '& .MuiOutlinedInput-root': { borderRadius: '10px' },
              }}
            />
            <Box sx={{ display: 'flex', justifyContent: 'center', mt: 2, gap: 1 }}>
              <Button
                variant="contained"
                component="label"
                sx={{
                  backgroundColor: 'black',
                  color: '#FFDD31',
                  fontWeight: 'bold',
                  borderRadius: '25px',
                  '&:hover': { backgroundColor: '#FFDD31', color: 'black' },
                }}
                startIcon={<Upload size={32} weight="fill" />}
                size="large"
              >
                Upload Image
                <input type="file" hidden accept="image/*" onChange={handleFileChange} />
              </Button>
            </Box>
            {imagePreview && (
              <Box sx={{ position: 'relative', mt: 2, display: 'flex', justifyContent: 'center' }}>
                <img
                  src={imagePreview}
                  alt="Category preview"
                  style={{ maxWidth: 120, height: 120, borderRadius: 10, objectFit: 'cover' }}
                />
                <Button
                  onClick={handleRemoveImage}
                  sx={{
                    position: 'absolute',
                    top: 0,
                    right: 'calc(50% - 72px)',
                    minWidth: 'unset',
                    borderRadius: '50%',
                    width: 24,
                    height: 24,
                    p: 0,
                  }}
                >
                  &times;
                </Button>
              </Box>
            )}
            <Button
              type="submit"
              fullWidth
              variant="contained"
              disabled={!categoryName.trim()}
              sx={{
                mt: 3,
                backgroundColor: '#000000',
                color: '#FFDD31',
                fontWeight: 'bold',
                borderRadius: '25px',
                '&:hover': { backgroundColor: '#FFDD31', color: '#000000' },
              }}
              size="large"
            >
              Create Category
            </Button>
          </form>
        </Box>
      </Modal>
      <Modal
        open={open1}
        onClose={handleClose1}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
        style={{ 
          backdropFilter: 'blur(12px)',
          backgroundColor: theme.palette.mode === 'dark' 
            ? 'rgba(0, 0, 0, 0.7)' 
            : 'rgba(0, 0, 0, 0.5)',
        }}
      >
        <Box sx={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          width: '95%',
          maxWidth: 800,
          maxHeight: '95vh',
          bgcolor: 'background.paper',
          outline: 'none',
          boxShadow: theme.palette.mode === 'dark' 
            ? '0 24px 48px rgba(0, 0, 0, 0.4), 0 8px 16px rgba(0, 0, 0, 0.2)' 
            : '0 24px 48px rgba(0, 0, 0, 0.15), 0 8px 16px rgba(0, 0, 0, 0.1)',
          borderRadius: 4,
          overflowY: 'auto',
          border: theme.palette.mode === 'dark' 
            ? '1px solid rgba(255, 255, 255, 0.12)' 
            : '1px solid rgba(0, 0, 0, 0.12)',
          background: theme.palette.mode === 'dark' 
            ? 'linear-gradient(145deg, #1a202c 0%, #2d3748 100%)' 
            : 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
          backdropFilter: 'blur(20px)',
          '&::-webkit-scrollbar': {
            width: '8px',
          },
          '&::-webkit-scrollbar-track': {
            background: theme.palette.mode === 'dark' ? '#2d3748' : '#f1f5f9',
            borderRadius: '4px',
          },
          '&::-webkit-scrollbar-thumb': {
            background: theme.palette.mode === 'dark' ? '#4a5568' : '#cbd5e0',
            borderRadius: '4px',
            '&:hover': {
              background: theme.palette.mode === 'dark' ? '#718096' : '#a0aec0',
            },
          },
        }}>
          {/* Header with gradient */}
          <Box sx={{
            position: 'relative',
            p: 4,
            pb: 2,
            background: theme.palette.mode === 'dark' 
              ? 'linear-gradient(135deg, #ffd700 0%, #ffed4a 100%)' 
              : 'linear-gradient(135deg, #1a202c 0%, #2d3748 100%)',
            color: theme.palette.mode === 'dark' ? '#1a202c' : '#ffffff',
            borderTopLeftRadius: 16,
            borderTopRightRadius: 16,
          }}>
            <IconButton
              onClick={handleClose1}
              sx={{
                position: 'absolute',
                top: 16,
                right: 16,
                backgroundColor: theme.palette.mode === 'dark' 
                  ? 'rgba(26, 32, 44, 0.2)' 
                  : 'rgba(255, 255, 255, 0.2)',
                color: theme.palette.mode === 'dark' ? '#1a202c' : '#ffffff',
                width: 40,
                height: 40,
                '&:hover': {
                  backgroundColor: theme.palette.mode === 'dark' 
                    ? 'rgba(239, 68, 68, 0.2)' 
                    : 'rgba(239, 68, 68, 0.2)',
                  color: '#dc2626',
                  transform: 'scale(1.05)',
                },
                transition: 'all 0.2s ease-in-out',
                backdropFilter: 'blur(8px)',
              }}
            >
              <Close />
            </IconButton>
            <Typography 
              id="modal-modal-title" 
              variant="h4" 
              component="h1" 
              fontWeight={700} 
              textAlign="center"
              sx={{
                fontSize: '2rem',
                letterSpacing: '-0.025em',
              }}
            >
              🛍️ Create New Product
            </Typography>
            <Typography variant="body1" textAlign="center" sx={{ opacity: 0.9, mt: 1, fontSize: '1.1rem' }}>
              Add a new product to your merchandise catalog
            </Typography>
          </Box>
          
          {/* Form Content */}
          <Box sx={{ p: 4 }}>
            <form onSubmit={handleSubmit1}>
            <TextField
              required
              fullWidth
              margin="normal"
              label="Product Name"
              variant="outlined"
              value={productName}
              placeholder="Enter product name (e.g., Warrior T-Shirt)"
              onChange={handleProductName}
              sx={{
                mt: 2,
                '& .MuiOutlinedInput-root': {
                  borderRadius: 3,
                  backgroundColor: theme.palette.mode === 'dark' 
                    ? 'rgba(51, 65, 85, 0.3)' 
                    : 'rgba(248, 250, 252, 0.8)',
                },
                '& .MuiOutlinedInput-root.Mui-focused': {
                  '& fieldset': {
                    borderColor: theme.palette.mode === 'dark' ? '#3b82f6' : '#1d4ed8',
                    borderWidth: 2,
                  },
                },
                '& .MuiInputLabel-root.Mui-focused': {
                  color: theme.palette.mode === 'dark' ? '#3b82f6' : '#1d4ed8',
                  fontWeight: 600,
                },
              }}
            />
            <Stack gap={2} direction={'row'}>
              <FormControl fullWidth>
                <InputLabel id="demo-simple-select-label">Choose Category</InputLabel>
                <Select
                  labelId="demo-simple-select-label"
                  id="demo-simple-select"
                  value={selectedCategoryId}
                  label="Choose Category"
                  onChange={handleCategoryChange}
                >
                  {data?.data.map((item) => (
                    <MenuItem value={item._id} key={item._id}>
                      {item.categoryName}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
              <FormControl fullWidth>
                <InputLabel id="demo-simple-select-label-1">Select Size</InputLabel>
                <Select
                  labelId="demo-simple-select-label-1"
                  id="demo-simple-select-1"
                  value={size}
                  label="Select Size"
                  onChange={(e) => {
                    setSize(e.target.value);
                    setSizes([e.target.value]);
                  }}
                >
                  {sizeSet.map((el, i) => {
                    return (
                      <MenuItem value={el} key={i}>
                        {el === 'small'
                          ? 'Small'
                          : el === 'medium'
                            ? 'Medium'
                            : el === 'large'
                              ? 'Large'
                              : el === 'extralarge'
                                ? 'Extra Large'
                                : el}
                      </MenuItem>
                    );
                  })}
                </Select>
              </FormControl>
            </Stack>
            <Grid container spacing={2} sx={{ mt: 1 }}>
              <Grid item xs={12} sm={6}>
                <TextField
                  required
                  fullWidth
                  label="Quantity"
                  variant="outlined"
                  value={quantity}
                  onChange={handleQuantity}
                  type="number"
                  inputProps={{ min: 1 }}
                  placeholder="e.g., 100"
                  sx={{
                    '& .MuiOutlinedInput-root': {
                      borderRadius: 3,
                      backgroundColor: theme.palette.mode === 'dark' 
                        ? 'rgba(51, 65, 85, 0.3)' 
                        : 'rgba(248, 250, 252, 0.8)',
                    },
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  required
                  fullWidth
                  label="Price ($)"
                  variant="outlined"
                  value={price}
                  onChange={handlePrice}
                  type="number"
                  inputProps={{ min: 0, step: "0.01" }}
                  placeholder="e.g., 29.99"
                  sx={{
                    '& .MuiOutlinedInput-root': {
                      borderRadius: 3,
                      backgroundColor: theme.palette.mode === 'dark' 
                        ? 'rgba(51, 65, 85, 0.3)' 
                        : 'rgba(248, 250, 252, 0.8)',
                    },
                  }}
                />
              </Grid>
            </Grid>
            <Stack>
              <TextField
                required
                fullWidth
                margin="normal"
                label="Product Description"
                variant="outlined"
                value={productDescription}
                onChange={handleDescription}
                minRows={5}
                multiline={true}
              />
            </Stack>

            <Stack direction="row" gap={2} mt={2}>
              <Stack>
                <Stack direction="row" alignItems="center" gap={1} mb={1}>
                  <Typography variant="subtitle1">Select Color</Typography>
                  <Box
                    sx={{
                      width: 24,
                      height: 24,
                      borderRadius: '50%',
                      bgcolor: color.hex,
                      border: '1px solid',
                      borderColor: 'divider',
                    }}
                  />
                  <Typography variant="body2" color="text.secondary">
                    {color.hex}
                  </Typography>
                </Stack>
                <ColorPicker color={color} onChange={handleColorChange} />
              </Stack>
              <Stack sx={{ width: '100%' }}>
                <Box sx={{ display: 'flex', mt: '10px', gap: '5px' }}>
                  <Button
                    variant="contained"
                    component="label"
                    sx={{
                      backgroundColor: 'black',
                      color: '#FFDD31',
                      fontWeight: 'bold',
                      borderRadius: '25px',
                      '&:hover': {
                        backgroundColor: '#FFDD31',
                        borderColor: '#FFDD31',
                        color: 'black',
                      },
                    }}
                    startIcon={<Upload size={32} weight="fill" />}
                    size="large"
                  >
                    Upload Image
                    <input
                      key={`create-product-image-${productImageInputKey}`}
                      type="file"
                      hidden
                      accept="image/*"
                      onChange={handleFileChange1}
                    />
                  </Button>
                </Box>
                {productImagePreview && (
                  <Box
                    sx={{
                      position: 'relative',
                      width: '80px',
                      height: '80px',
                      mt: 2,
                      display: 'flex',
                      justifyContent: 'center',
                      alignItems: 'center',
                    }}
                  >
                    <img
                      key={productImagePreview}
                      src={productImagePreview}
                      alt="Product preview"
                      style={{
                        maxWidth: '100%',
                        height: '100%',
                        borderRadius: '10px',
                        objectFit: 'cover',
                      }}
                    />
                    <Button
                      onClick={handleRemoveProductImage}
                      sx={{
                        position: 'absolute',
                        top: '3px',
                        right: '3px',
                        minWidth: 'unset',
                        color: 'black',
                        backgroundColor: 'rgba(255, 255, 255, 0.6)',
                        backdropFilter: 'blur(2px)',
                        '&:hover': {
                          color: '#FFDD31',
                          backgroundColor: 'black',
                        },
                        borderRadius: '50%',
                        padding: '0',
                        fontSize: '20px',
                        width: '24px',
                        height: '24px',
                      }}
                    >
                      &times;
                    </Button>
                  </Box>
                )}
              </Stack>
            </Stack>

            <Button
              type="submit"
              fullWidth
              variant="contained"
              disabled={!productName.trim() || !selectedCategoryId || !quantity || !price}
              sx={{
                mt: 4,
                py: 2,
                background: theme.palette.mode === 'dark' 
                  ? 'linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%)' 
                  : 'linear-gradient(135deg, #60a5fa 0%, #3b82f6 100%)',
                color: 'white',
                fontWeight: 700,
                fontSize: '1.1rem',
                borderRadius: 3,
                boxShadow: '0 4px 15px rgba(59, 130, 246, 0.3)',
                border: 'none',
                '&:hover': {
                  transform: 'translateY(-2px)',
                  boxShadow: '0 6px 20px rgba(59, 130, 246, 0.4)',
                },
                '&:disabled': {
                  background: theme.palette.mode === 'dark' ? '#374151' : '#d1d5db',
                  color: theme.palette.mode === 'dark' ? '#6b7280' : '#9ca3af',
                  boxShadow: 'none',
                  transform: 'none',
                },
                transition: 'all 0.3s ease',
              }}
            >
              Create Product
            </Button>
            </form>
          </Box>
        </Box>
      </Modal>
      {/* Edit Category Modal */}
      <Modal open={editModalOpen} onClose={handleCloseEditModal} aria-labelledby="edit-category-modal" style={{ backdropFilter: 'blur(5px)' }}>
        <Box sx={boxStyle}>
          <Typography id="edit-category-modal" variant="h6" component="h1" sx={{ fontWeight: 'bold' }}>
            Edit Category
          </Typography>
          <form onSubmit={handleEditSubmit}>
            <TextField
              required
              fullWidth
              margin="normal"
              label="Category Name"
              variant="outlined"
              value={categoryName}
              sx={{
                '& .MuiOutlinedInput-root': { borderRadius: '10px' },
                '& .MuiOutlinedInput-root.Mui-focused': { '& fieldset': { borderColor: '#FFDD31' } },
                '& .MuiInputLabel-root.Mui-focused': { color: '#000000' },
              }}
              onChange={handleCategoryName}
            />
            <Box sx={{ display: 'flex', justifyContent: 'center', mt: '10px', gap: '5px' }}>
              <Button
                variant="contained"
                component="label"
                sx={{
                  backgroundColor: 'black',
                  color: '#FFDD31',
                  fontWeight: 'bold',
                  borderRadius: '25px',
                  '&:hover': { backgroundColor: '#FFDD31', borderColor: '#FFDD31', color: 'black' },
                }}
                startIcon={<Upload size={32} weight="fill" />}
                size="large"
              >
                Upload Profile Image
                <input type="file" hidden accept="image/*" onChange={handleFileChange} />
              </Button>
            </Box>
            {imagePreview && (
              <Box sx={{ position: 'relative', mt: 2, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                <img
                  src={imagePreview}
                  alt="Uploaded Preview"
                  style={{ maxWidth: '100px', height: '100px', borderRadius: '10px', objectFit: 'cover' }}
                />
                <Button
                  onClick={handleRemoveImage}
                  sx={{ position: 'absolute', top: '3px', right: '270px', minWidth: 'unset', color: 'black', backgroundColor: 'rgba(255, 255, 255, 0.6)', backdropFilter: 'blur(2px)', '&:hover': { color: '#FFDD31', backgroundColor: 'black' }, borderRadius: '50%', padding: '0', fontSize: '20px', width: '24px', height: '24px' }}
                >
                  &times;
                </Button>
              </Box>
            )}
            <Button
              type="submit"
              fullWidth
              variant="contained"
              disabled={isLoading || !categoryName.trim()}
              sx={{ marginTop: '16px', backgroundColor: '#000000', color: '#FFDD31', fontWeight: 'bold', borderRadius: '25px', '&:hover': { backgroundColor: '#FFDD31', borderColor: '#000000', color: '#000000' } }}
              size="large"
            >
              {isLoading ? 'Saving...' : 'Save Changes'}
            </Button>
          </form>
        </Box>
      </Modal>
      {/* Delete Confirmation Dialog */}
      <Modal open={deleteDialogOpen} onClose={handleCloseDeleteDialog} aria-labelledby="delete-category-modal" style={{ backdropFilter: 'blur(5px)' }}>
        <Box sx={{ ...boxStyle, maxWidth: 400 }}>
          <Typography id="delete-category-modal" variant="h6" component="h1" sx={{ fontWeight: 'bold', mb: 2 }}>
            Delete Category
          </Typography>
          <Typography>Are you sure you want to delete this category?</Typography>
          <Stack direction="row" spacing={2} sx={{ mt: 3, justifyContent: 'flex-end' }}>
            <Button onClick={handleCloseDeleteDialog} variant="outlined" disabled={isLoading}>
              Cancel
            </Button>
            <Button onClick={handleDeleteConfirm} variant="contained" color="error" disabled={isLoading}>
              {isLoading ? 'Deleting...' : 'Delete'}
            </Button>
          </Stack>
        </Box>
      </Modal>
      {/* Category Detail Modal - Enhanced */}
      <Modal open={detailModalOpen} onClose={handleCloseDetailModal} aria-labelledby="detail-category-modal" style={{ backdropFilter: 'blur(8px)' }}>
        <Box sx={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          width: '90%',
          maxWidth: 650,
          maxHeight: '90vh',
          bgcolor: 'background.paper',
          borderRadius: 4,
          boxShadow: theme.palette.mode === 'dark' 
            ? '0 20px 60px rgba(0, 0, 0, 0.6)' 
            : '0 20px 60px rgba(0, 0, 0, 0.15)',
          overflow: 'hidden',
          border: theme.palette.mode === 'dark' 
            ? '1px solid #475569' 
            : '1px solid rgba(255, 255, 255, 0.8)',
        }}>
          {selectedCategory && (
            <>
              {/* Header with gradient background */}
              <Box sx={{
                position: 'relative',
                p: 4,
                pb: 2,
                background: theme.palette.mode === 'dark' 
                  ? 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 50%, #d946ef 100%)' 
                  : 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                color: 'white',
              }}>
                <IconButton
                  onClick={handleCloseDetailModal}
                  sx={{
                    position: 'absolute',
                    top: 16,
                    right: 16,
                    color: 'white',
                    bgcolor: 'rgba(255, 255, 255, 0.1)',
                    '&:hover': {
                      bgcolor: 'rgba(255, 255, 255, 0.2)',
                      transform: 'scale(1.1)',
                    },
                    transition: 'all 0.2s ease',
                  }}
                >
                  <Close />
                </IconButton>
                <Typography variant="h4" fontWeight={700} mb={1} align="center">
                  {selectedCategory.categoryName}
                </Typography>
                <Typography variant="body1" align="center" sx={{ opacity: 0.9 }}>
                  Category Details
                </Typography>
              </Box>

              {/* Content Section */}
              <Box sx={{ p: 4 }}>
                {/* Image Section */}
                <Box sx={{
                  position: 'relative',
                  mb: 4,
                  borderRadius: 3,
                  overflow: 'hidden',
                  boxShadow: theme.palette.mode === 'dark' 
                    ? '0 8px 32px rgba(0, 0, 0, 0.3)' 
                    : '0 8px 32px rgba(0, 0, 0, 0.08)',
                }}>
                  <img
                    src={
                      selectedCategory.mediaData?.fileUrl ||
                      (selectedCategory.mediaData?.fileName
                        ? `${liveUrl}/${selectedCategory.mediaData.fileName}`
                        : '')
                    }
                    alt={selectedCategory.categoryName}
                    style={{
                      width: '100%',
                      height: '300px',
                      objectFit: 'cover',
                      borderRadius: '12px',
                    }}
                  />
                  <Box sx={{
                    position: 'absolute',
                    bottom: 0,
                    left: 0,
                    right: 0,
                    background: 'linear-gradient(transparent, rgba(0,0,0,0.7))',
                    p: 2,
                    color: 'white',
                  }}>
                    <Typography variant="h6" fontWeight={600}>
                      {selectedCategory.categoryName}
                    </Typography>
                  </Box>
                </Box>

                {/* Info Cards */}
                <Grid container spacing={2}>
                  <Grid item xs={6}>
                    <Box sx={{
                      p: 3,
                      borderRadius: 3,
                      background: theme.palette.mode === 'dark' 
                        ? 'linear-gradient(145deg, #1e293b 0%, #334155 100%)' 
                        : 'linear-gradient(145deg, #f8fafc 0%, #e2e8f0 100%)',
                      border: theme.palette.mode === 'dark' 
                        ? '1px solid #475569' 
                        : '1px solid #e2e8f0',
                      textAlign: 'center',
                    }}>
                      <Typography variant="body2" color="text.secondary" mb={1}>
                        Created On
                      </Typography>
                      <Typography variant="h6" color="primary.main" fontWeight={600}>
                        {dayjs(selectedCategory.createdAt).format('MMM D, YYYY')}
                      </Typography>
                    </Box>
                  </Grid>
                  <Grid item xs={6}>
                    <Box sx={{
                      p: 3,
                      borderRadius: 3,
                      background: theme.palette.mode === 'dark' 
                        ? 'linear-gradient(145deg, #1e293b 0%, #334155 100%)' 
                        : 'linear-gradient(145deg, #f8fafc 0%, #e2e8f0 100%)',
                      border: theme.palette.mode === 'dark' 
                        ? '1px solid #475569' 
                        : '1px solid #e2e8f0',
                      textAlign: 'center',
                    }}>
                      <Typography variant="body2" color="text.secondary" mb={1}>
                        Last Updated
                      </Typography>
                      <Typography variant="h6" color="secondary.main" fontWeight={600}>
                        {dayjs(selectedCategory.updatedAt).format('MMM D, YYYY')}
                      </Typography>
                    </Box>
                  </Grid>
                </Grid>

                {/* Status Badge */}
                <Box sx={{ mt: 3, textAlign: 'center' }}>
                  <Chip
                    label="Active Category"
                    color="success"
                    variant="outlined"
                    sx={{
                      fontWeight: 600,
                      px: 2,
                      py: 1,
                      borderRadius: 2,
                    }}
                  />
                </Box>

                <Stack direction="row" spacing={2} justifyContent="center" sx={{ mt: 3 }}>
                  <Button
                    variant="outlined"
                    onClick={() => {
                      handleCloseDetailModal();
                      if (selectedCategory) handleEditCategory(selectedCategory);
                    }}
                  >
                    Edit
                  </Button>
                  <Button
                    variant="contained"
                    color="error"
                    onClick={() => {
                      handleCloseDetailModal();
                      if (selectedCategory) handleDeleteCategory(selectedCategory);
                    }}
                  >
                    Delete
                  </Button>
                </Stack>
              </Box>
            </>
          )}
        </Box>
      </Modal>
      {/* Edit Product Modal */}
      <Modal open={editProductModalOpen} onClose={handleCloseEditProductModal} aria-labelledby="edit-product-modal" style={{ backdropFilter: 'blur(5px)' }}>
        <Box sx={boxStyle}>
          <Typography id="edit-product-modal" variant="h6" component="h1" sx={{ fontWeight: 'bold' }}>
            Edit Product
          </Typography>
          <form onSubmit={handleEditProductSubmit}>
            <TextField
              required
              fullWidth
              margin="normal"
              label="Product Name"
              variant="outlined"
              value={productName}
              sx={{
                '& .MuiOutlinedInput-root': { borderRadius: '10px' },
                '& .MuiOutlinedInput-root.Mui-focused': { '& fieldset': { borderColor: '#FFDD31' } },
                '& .MuiInputLabel-root.Mui-focused': { color: '#000000' },
              }}
              onChange={handleProductName}
            />
            <TextField
              required
              fullWidth
              margin="normal"
              label="Product Description"
              variant="outlined"
              value={productDescription}
              onChange={handleDescription}
              minRows={5}
              multiline={true}
            />
            <Stack direction={'row'} gap={2}>
              <TextField
                required
                fullWidth
                margin="normal"
                label="Product Quantity"
                variant="outlined"
                value={quantity}
                onChange={handleQuantity}
                type="number"
              />
              <TextField
                required
                fullWidth
                margin="normal"
                label="Product Price"
                variant="outlined"
                value={price}
                onChange={handlePrice}
                type="number"
              />
            </Stack>
            <Stack gap={2} direction={'row'} sx={{ mt: 1 }}>
              <FormControl fullWidth margin="normal">
                <InputLabel id="edit-product-category-label">Choose Category</InputLabel>
                <Select
                  labelId="edit-product-category-label"
                  value={selectedCategoryId}
                  label="Choose Category"
                  onChange={handleCategoryChange}
                >
                  {data?.data.map((item) => (
                    <MenuItem value={item._id} key={item._id}>
                      {item.categoryName}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
              <FormControl fullWidth margin="normal">
                <InputLabel id="edit-product-size-label">Select Size</InputLabel>
                <Select
                  labelId="edit-product-size-label"
                  value={size}
                  label="Select Size"
                  onChange={(e) => {
                    setSize(e.target.value);
                    setSizes([e.target.value]);
                  }}
                >
                  {sizeSet.map((el, i) => (
                    <MenuItem value={el} key={i}>
                      {el === 'small'
                        ? 'Small'
                        : el === 'medium'
                          ? 'Medium'
                          : el === 'large'
                            ? 'Large'
                            : el === 'extralarge'
                              ? 'Extra Large'
                              : el}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Stack>
            <Stack direction="row" gap={2} mt={2}>
              <Stack>
                <Stack direction="row" alignItems="center" gap={1} mb={1}>
                  <Typography variant="subtitle1">Select Color</Typography>
                  <Box
                    sx={{
                      width: 24,
                      height: 24,
                      borderRadius: '50%',
                      bgcolor: color.hex,
                      border: '1px solid',
                      borderColor: 'divider',
                    }}
                  />
                  <Typography variant="body2" color="text.secondary">
                    {color.hex}
                  </Typography>
                </Stack>
                <ColorPicker color={color} onChange={handleColorChange} />
              </Stack>
            </Stack>
            <Box sx={{ display: 'flex', justifyContent: 'center', mt: '10px', gap: '5px' }}>
              <Button
                variant="contained"
                component="label"
                sx={{
                  backgroundColor: 'black',
                  color: '#FFDD31',
                  fontWeight: 'bold',
                  borderRadius: '25px',
                  '&:hover': { backgroundColor: '#FFDD31', borderColor: '#FFDD31', color: 'black' },
                }}
                startIcon={<Upload size={32} weight="fill" />}
                size="large"
              >
                {productImagePreview ? 'Replace Image' : 'Upload Image'}
                <input
                  key={`edit-product-image-${productImageInputKey}`}
                  type="file"
                  hidden
                  accept="image/*"
                  onChange={handleFileChange1}
                />
              </Button>
            </Box>
            {productImagePreview && (
              <Box
                sx={{
                  position: 'relative',
                  width: '80px',
                  height: '80px',
                  mt: 2,
                  mx: 'auto',
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                }}
              >
                <img
                  key={productImagePreview}
                  src={productImagePreview}
                  alt="Product preview"
                  style={{ maxWidth: '100%', height: '100%', borderRadius: '10px', objectFit: 'cover' }}
                />
                <Button
                  onClick={handleRemoveProductImage}
                  sx={{
                    position: 'absolute',
                    top: '3px',
                    right: '3px',
                    minWidth: 'unset',
                    color: 'black',
                    backgroundColor: 'rgba(255, 255, 255, 0.6)',
                    backdropFilter: 'blur(2px)',
                    '&:hover': { color: '#FFDD31', backgroundColor: 'black' },
                    borderRadius: '50%',
                    padding: '0',
                    fontSize: '20px',
                    width: '24px',
                    height: '24px',
                  }}
                >
                  &times;
                </Button>
              </Box>
            )}
            <Button
              type="submit"
              fullWidth
              variant="contained"
              disabled={isLoading || !productName.trim() || !selectedCategoryId || !quantity || !price}
              sx={{ marginTop: '16px', backgroundColor: '#000000', color: '#FFDD31', fontWeight: 'bold', borderRadius: '25px', '&:hover': { backgroundColor: '#FFDD31', borderColor: '#000000', color: '#000000' } }}
              size="large"
            >
              {isLoading ? 'Saving...' : 'Save Changes'}
            </Button>
          </form>
        </Box>
      </Modal>
      {/* Delete Product Confirmation Dialog */}
      <Modal open={deleteProductDialogOpen} onClose={handleCloseDeleteProductDialog} aria-labelledby="delete-product-modal" style={{ backdropFilter: 'blur(5px)' }}>
        <Box sx={{ ...boxStyle, maxWidth: 400 }}>
          <Typography id="delete-product-modal" variant="h6" component="h1" sx={{ fontWeight: 'bold', mb: 2 }}>
            Delete Product
          </Typography>
          <Typography>Are you sure you want to delete this product?</Typography>
          <Stack direction="row" spacing={2} sx={{ mt: 3, justifyContent: 'flex-end' }}>
            <Button onClick={handleCloseDeleteProductDialog} variant="outlined" disabled={isLoading}>
              Cancel
            </Button>
            <Button onClick={handleDeleteProductConfirm} variant="contained" color="error" disabled={isLoading}>
              {isLoading ? 'Deleting...' : 'Delete'}
            </Button>
          </Stack>
        </Box>
      </Modal>
      {/* Product Detail Modal - Enhanced */}
      <Modal open={detailProductModalOpen} onClose={handleCloseDetailProductModal} aria-labelledby="detail-product-modal" style={{ backdropFilter: 'blur(8px)' }}>
        <Box sx={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          width: '95%',
          maxWidth: 1000,
          maxHeight: '95vh',
          bgcolor: 'background.paper',
          borderRadius: 4,
          boxShadow: theme.palette.mode === 'dark' 
            ? '0 25px 80px rgba(0, 0, 0, 0.6)' 
            : '0 25px 80px rgba(0, 0, 0, 0.15)',
          overflow: 'hidden',
          border: theme.palette.mode === 'dark' 
            ? '1px solid #475569' 
            : '1px solid rgba(255, 255, 255, 0.8)',
        }}>
          {selectedProduct && (
            <>
              {/* Header */}
              <Box sx={{
                position: 'relative',
                p: 3,
                background: theme.palette.mode === 'dark' 
                  ? 'linear-gradient(135deg, #0f172a 0%, #1e293b 100%)' 
                  : 'linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%)',
                borderBottom: theme.palette.mode === 'dark' 
                  ? '1px solid #475569' 
                  : '1px solid #e2e8f0',
              }}>
                <IconButton
                  onClick={handleCloseDetailProductModal}
                  sx={{
                    position: 'absolute',
                    top: 16,
                    right: 16,
                    color: theme.palette.mode === 'dark' ? '#f87171' : '#dc2626',
                    bgcolor: theme.palette.mode === 'dark' 
                      ? 'rgba(248, 113, 113, 0.1)' 
                      : 'rgba(220, 38, 38, 0.1)',
                    '&:hover': {
                      bgcolor: theme.palette.mode === 'dark' 
                        ? 'rgba(248, 113, 113, 0.2)' 
                        : 'rgba(220, 38, 38, 0.2)',
                      transform: 'scale(1.1)',
                    },
                    transition: 'all 0.2s ease',
                  }}
                >
                  <Close />
                </IconButton>
                <Typography variant="h4" fontWeight={700} color="text.primary" textAlign="center">
                  {selectedProduct.productName}
                </Typography>
                <Typography variant="h5" color="success.main" textAlign="center" mt={1} fontWeight={600}>
                  ${selectedProduct.price}
                </Typography>
              </Box>

              {/* Content */}
              <Box sx={{ overflowY: 'auto', maxHeight: 'calc(95vh - 120px)' }}>
                <Grid container>
                  {/* Image Section */}
                  <Grid item xs={12} md={6} sx={{ p: 3 }}>
                    <Box sx={{
                      position: 'relative',
                      borderRadius: 3,
                      overflow: 'hidden',
                      boxShadow: theme.palette.mode === 'dark' 
                        ? '0 12px 40px rgba(0, 0, 0, 0.4)' 
                        : '0 12px 40px rgba(0, 0, 0, 0.1)',
                      mb: 2,
                    }}>
                      <img
                        key={
                          selectedProduct
                            ? getDisplayProductImageUrl(selectedProduct)
                            : 'product-detail'
                        }
                        src={
                          selectedProduct
                            ? getDisplayProductImageUrl(selectedProduct)
                            : ''
                        }
                        alt={selectedProduct.productName}
                        style={{
                          width: '100%',
                          height: '350px',
                          objectFit: 'cover',
                        }}
                      />
                      <Box sx={{
                        position: 'absolute',
                        top: 12,
                        left: 12,
                        bgcolor: 'success.main',
                        color: 'white',
                        px: 2,
                        py: 0.5,
                        borderRadius: 2,
                        fontWeight: 600,
                        fontSize: '0.875rem',
                      }}>
                        In Stock
                      </Box>
                    </Box>
                  </Grid>

                  {/* Details Section */}
                  <Grid item xs={12} md={6} sx={{ p: 3 }}>
                    {/* Product Info Cards */}
                    <Stack spacing={2}>
                      <Box sx={{
                        p: 2,
                        borderRadius: 2,
                        background: theme.palette.mode === 'dark' 
                          ? 'linear-gradient(145deg, #1e293b 0%, #334155 100%)' 
                          : 'linear-gradient(145deg, #f8fafc 0%, #e2e8f0 100%)',
                        border: theme.palette.mode === 'dark' 
                          ? '1px solid #475569' 
                          : '1px solid #e2e8f0',
                      }}>
                        <Typography variant="body2" color="text.secondary" mb={1}>
                          Category
                        </Typography>
                        <Typography variant="h6" color="primary.main" fontWeight={600}>
                          {selectedProduct.categoryName}
                        </Typography>
                      </Box>

                      <Grid container spacing={2}>
                        <Grid item xs={6}>
                          <Box sx={{
                            p: 2,
                            borderRadius: 2,
                            background: theme.palette.mode === 'dark' 
                              ? 'linear-gradient(145deg, #1e293b 0%, #334155 100%)' 
                              : 'linear-gradient(145deg, #f8fafc 0%, #e2e8f0 100%)',
                            border: theme.palette.mode === 'dark' 
                              ? '1px solid #475569' 
                              : '1px solid #e2e8f0',
                            textAlign: 'center',
                          }}>
                            <Typography variant="body2" color="text.secondary" mb={1}>
                              Quantity
                            </Typography>
                            <Typography variant="h6" color="success.main" fontWeight={600}>
                              {selectedProduct.quantity}
                            </Typography>
                          </Box>
                        </Grid>
                        <Grid item xs={6}>
                          <Box sx={{
                            p: 2,
                            borderRadius: 2,
                            background: theme.palette.mode === 'dark' 
                              ? 'linear-gradient(145deg, #1e293b 0%, #334155 100%)' 
                              : 'linear-gradient(145deg, #f8fafc 0%, #e2e8f0 100%)',
                            border: theme.palette.mode === 'dark' 
                              ? '1px solid #475569' 
                              : '1px solid #e2e8f0',
                            textAlign: 'center',
                          }}>
                            <Typography variant="body2" color="text.secondary" mb={1}>
                              Created
                            </Typography>
                            <Typography variant="body1" color="text.primary" fontWeight={600}>
                              {dayjs(selectedProduct.createdAt).format('MMM D, YYYY')}
                            </Typography>
                          </Box>
                        </Grid>
                      </Grid>

                      {/* Size and Color */}
                      <Box sx={{
                        p: 2,
                        borderRadius: 2,
                        background: theme.palette.mode === 'dark' 
                          ? 'linear-gradient(145deg, #1e293b 0%, #334155 100%)' 
                          : 'linear-gradient(145deg, #f8fafc 0%, #e2e8f0 100%)',
                        border: theme.palette.mode === 'dark' 
                          ? '1px solid #475569' 
                          : '1px solid #e2e8f0',
                      }}>
                        <Grid container spacing={2}>
                          <Grid item xs={6}>
                            <Typography variant="body2" color="text.secondary" mb={1}>
                              Available Sizes
                            </Typography>
                            <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
                              {selectedProduct.sizes.map((size, index) => (
                                <Chip
                                  key={index}
                                  label={
                                    size === 'small' ? 'S' :
                                    size === 'medium' ? 'M' :
                                    size === 'large' ? 'L' :
                                    size === 'extralarge' ? 'XL' : size
                                  }
                                  size="small"
                                  variant="outlined"
                                  color="primary"
                                />
                              ))}
                            </Box>
                          </Grid>
                          <Grid item xs={6}>
                            <Typography variant="body2" color="text.secondary" mb={1}>
                              Available Colors
                            </Typography>
                            <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
                              {selectedProduct.colors.map((color, index) => (
                                <Box
                                  key={index}
                                  sx={{
                                    width: 24,
                                    height: 24,
                                    borderRadius: '50%',
                                    backgroundColor: getProductColorCss(color),
                                    border: theme.palette.mode === 'dark' 
                                      ? '2px solid #475569' 
                                      : '2px solid #e2e8f0',
                                    boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                                  }}
                                />
                              ))}
                            </Box>
                          </Grid>
                        </Grid>
                      </Box>

                      {/* Description */}
                      <Box sx={{
                        p: 3,
                        borderRadius: 2,
                        background: theme.palette.mode === 'dark' 
                          ? 'linear-gradient(145deg, #1e293b 0%, #334155 100%)' 
                          : 'linear-gradient(145deg, #f8fafc 0%, #e2e8f0 100%)',
                        border: theme.palette.mode === 'dark' 
                          ? '1px solid #475569' 
                          : '1px solid #e2e8f0',
                      }}>
                        <Typography variant="h6" color="text.primary" fontWeight={600} mb={2}>
                          Product Description
                        </Typography>
                        <Typography
                          variant="body1"
                          color="text.secondary"
                          sx={{
                            lineHeight: 1.6,
                            whiteSpace: 'pre-wrap',
                            wordBreak: 'break-word',
                          }}
                        >
                          {selectedProduct.productDescription}
                        </Typography>
                      </Box>

                      <Stack direction="row" spacing={2} justifyContent="flex-end" sx={{ mt: 1 }}>
                        <Button
                          variant="outlined"
                          onClick={() => {
                            handleCloseDetailProductModal();
                            handleEditProduct(selectedProduct);
                          }}
                        >
                          Edit
                        </Button>
                        <Button
                          variant="contained"
                          color="error"
                          onClick={() => {
                            handleCloseDetailProductModal();
                            handleDeleteProduct(selectedProduct);
                          }}
                        >
                          Delete
                        </Button>
                      </Stack>
                    </Stack>
                  </Grid>
                </Grid>
              </Box>
            </>
          )}
        </Box>
      </Modal>
    </Box>
  );
}
