"use client";

import React, { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Plus,
  Edit,
  Trash,
  Eye,
  ChevronLeft,
  ChevronRight,
  X,
  Check,
  CircleDashed,
} from "lucide-react";
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { listAllCategories } from "@/app/services/api/categories-api";
import { listAllProducts } from "@/app/services/api/product-api";
import { toast } from "@/components/ui/use-toast";
// import {
//   fetchCategories,
//   createCategory,
//   updateCategory,
//   deleteCategory,
// } from "@/redux/features/categoriesSlice";
// import { RootState, AppDispatch } from "@/redux/store";
// import { useDispatch, useSelector } from "react-redux";
import { useGetCategoriesQuery } from "@/redux/services/categories.api";
import {
  useCreateProductsMutation,
  useDeleteProductsMutation,
  useGetProductsQuery,
  useUpdateProductsMutation,
} from "@/redux/services/products.api";
import { useRouter } from "next/navigation";
import Image from "next/image";

type Category = {
  _id: string;
  name: string;
  icon: string; // URL or empty string
  status: string; // 'active' or other status
};

type Product = {
  _id?: string;
  name: string;
  // price: number | string;
  // description: string;
  categoryId: string;
  images: string[];
  categoryName?: string;
};

export default function Component() {
  // const router = useRouter();
  // useEffect(() => {
  //   const token = localStorage.getItem("token");
  //   if (!token) {
  //     router.push("/");
  //   }
  // });
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [ind, setInd] = useState<number[]>([]);
  const [erro, setErro] = useState<boolean>(false);
  const [nerro, setNerro] = useState<boolean>(false);
  const [cerro, setCerro] = useState<boolean>(false);
  const toggleIndex = (index: number) => {
    if (ind.includes(index)) {
      // If the index is already in the array, remove it
      setInd(ind.filter((i) => i !== index));
    } else {
      // Otherwise, add the index
      setInd([...ind, index]);
    }
  };
  const [searchTerm, setSearchTerm] = useState<string>(""); // Search term state
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  // const [categories, setCategories] = useState<Category[]>([]);
  // const [products, setProducts] = useState<Product[]>([]);
  const {
    data: categories,
    isLoading: isCategoryLoading,
    error: categoryError,
  } = useGetCategoriesQuery();
  const {
    data: products,
    isLoading: isProductsLoading,
    error: productsError,
  } = useGetProductsQuery();

  const [createProduct, { isLoading, error }] = useCreateProductsMutation({});
  const [updateProduct, { isLoading: updateLoading, error: updateError }] =
    useUpdateProductsMutation({});
  const [deleteProduct, { isLoading: deleteLoading, error: deleteError }] =
    useDeleteProductsMutation({});
  const [newProduct, setNewProduct] = useState<Omit<Product, "id">>({
    name: "",
    // price: 0,
    categoryId: "",
    // description: "",
    images: [],
  });
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [viewingProduct, setViewingProduct] = useState<Product | null>(null);
  const [selectedCategory, setSelectedCategory] = useState<string>("all");

  const handleAddProduct = () => {
    // setIsCreateDialogOpen(false);
    erro && setErro(false);
    const formData = new FormData();

    formData.append("name", newProduct.name);
    formData.append("categoryId", newProduct.categoryId);
    // formData.append("description", newProduct.description);
    formData.append("description", "default");
    // formData.append("price", newProduct.price.toString());
    newProduct.images.forEach((base64Image: string, index: number) => {
      // Convert Base64 to Blob
      const byteString = atob(base64Image.split(",")[1]); // Decode Base64 string
      const mimeString = base64Image.split(",")[0].split(":")[1].split(";")[0]; // Extract MIME type
      const byteArray = new Uint8Array(byteString.length);

      for (let i = 0; i < byteString.length; i++) {
        byteArray[i] = byteString.charCodeAt(i);
      }

      const blob = new Blob([byteArray], { type: mimeString });

      // Append the Blob to formData with a unique key for each image
      formData.append("images", blob, `image_${index}.png`);
    });

    createProduct(formData)
      .unwrap()
      .then((res) => {
        if (res.status) {
          return toast({
            title: res.message,
            variant: "success",
          });
        }

        return toast({
          title: res.message,
          variant: "destructive",
        });
      })
      .catch((err) =>
        toast({
          title: "Error creating Product",
          description: "All Fields Are Required To Create Product",
          variant: "destructive",
        })
      );
    setIsCreateDialogOpen(false);
    setNewProduct({
      name: "",
      // price: 0,
      categoryId: "",
      images: [],
      // description: "",
    });
  };
  const handleEditProduct = () => {
    setIsDialogOpen(false);
    const formData = new FormData();
    formData.append("name", editingProduct?.name || "");
    formData.append("productId", editingProduct?._id || "");
    // formData.append("description", editingProduct?.description || "");
    formData.append("description", "default");
    formData.append("categoryId", editingProduct?.categoryId || "");
    // editingProduct?.price &&
    //   formData.append("price", editingProduct?.price.toString());
    ind.map((i) => {
      formData.append("imageIndex[]", i.toString());
    });
    setInd([]);
    newProduct.images.forEach((base64Image: string, index: number) => {
      // Convert Base64 to Blob
      const byteString = atob(base64Image.split(",")[1]); // Decode Base64 string
      const mimeString = base64Image.split(",")[0].split(":")[1].split(";")[0]; // Extract MIME type
      const byteArray = new Uint8Array(byteString.length);

      for (let i = 0; i < byteString.length; i++) {
        byteArray[i] = byteString.charCodeAt(i);
      }

      const blob = new Blob([byteArray], { type: mimeString });

      // Append the Blob to formData with a unique key for each image
      formData.append("images", blob, `image_${index}.png`);
    });
    updateProduct(formData)
      .unwrap()
      .then((res) => {
        if (res.status) {
          return toast({
            title: res.message,
            variant: "success",
          });
        }

        return toast({
          title: res.message,
          variant: "destructive",
        });
      })
      .catch((err) =>
        toast({
          title: "Error Editing Product",
          // description: "All Fields Are Required To Edit Product",
          variant: "destructive",
        })
      );
    setNewProduct({
      name: "",
      // price: 0,
      categoryId: "",
      images: [],
      // description: "",
    });
  };

  const handleDeleteProduct = (id: string) => {
    deleteProduct(id)
      .unwrap()
      .then((res) => {
        if (res.status) {
          setIsCreateDialogOpen(false);
          return toast({
            title: res.message,
            variant: "destructive",
          });
        }
        return toast({
          title: res.message,
          variant: "destructive",
        });
      })
      .catch((err: any) =>
        toast({
          title: "Error Deleteing Product",
          variant: "destructive",
        })
      );

    //  dispatch(updateCategory(id))
    //    .unwrap()
    //    .then(() => {
    //      setSelectedCategory(null);
    //      toast({ title: "Category updated successfully", variant: "default" });
    //    })
    //    .catch(() => {
    //      toast({ title: "Error updating category", variant: "destructive" });
    //    });
  };

  const handleImageUpload = (
    e: React.ChangeEvent<HTMLInputElement>,
    isNewProduct: boolean
  ) => {
    const files = Array.from(e.target.files || []);
    const imagePromises = files.map((file) => {
      return new Promise<string>((resolve) => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result as string);
        reader.readAsDataURL(file);
      });
    });

    Promise.all(imagePromises).then((images) => {
      if (isNewProduct) {
        setNewProduct((prev) => ({
          ...prev,
          images: [...prev.images, ...images],
        }));
      } else if (editingProduct) {
        setEditingProduct((prev) =>
          prev ? { ...prev, images: [...prev.images, ...images] } : null
        );
      }
    });
  };

  useEffect(() => {
    setCurrentPage(1);
  }, [selectedCategory, searchTerm]);

  const [currentPage, setCurrentPage] = useState(1);
  const filteredProducts = products?.filter((p) => {
    return (
      (selectedCategory === "all" || p.categoryName === selectedCategory) &&
      p.name.toLowerCase().includes(searchTerm.toLowerCase())
    );
  });
  // Pagination state

  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [goToPage, setGoToPage] = useState("");
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = filteredProducts?.slice(
    indexOfFirstItem,
    indexOfLastItem
  );
  const totalPages = Math.ceil((filteredProducts?.length || 0) / itemsPerPage);

  const paginate = (pageNumber: number) => setCurrentPage(pageNumber);

  return (
    <div className="container mx-auto p-4 space-y-4">
      {/* Category Filter */}
      {/* <div className="flex"> */}
      <div className="space-y-6">
        <div className="flex flex-wrap items-end gap-4 sm:flex-nowrap">
          <div className="w-full sm:w-auto">
            <Label htmlFor="category-filter" className="mb-2 block">
              Filter by Category
            </Label>
            <Select
              value={selectedCategory}
              onValueChange={setSelectedCategory}
            >
              <SelectTrigger
                id="category-filter"
                className="w-full sm:w-[200px]"
              >
                <SelectValue placeholder="All Categories" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">
                  {isCategoryLoading ? (
                    <div>
                      <div className="flex justify-center items-center h-[50vh]">
                        <CircleDashed className="animate-spin text-[#be063f]" />
                      </div>
                    </div>
                  ) : (
                    "All Categories"
                  )}
                  {/* All Categories */}
                </SelectItem>
                {categories &&
                  categories.length > 0 &&
                  categories?.map((category) => (
                    <SelectItem key={category._id} value={category.name}>
                      <div className="flex items-center gap-4">
                        <Avatar>
                          {category.icon && category.icon.length > 0 ? (
                            <Image
                              src={category.icon}
                              height={200}
                              width={200}
                              alt="BI"
                            />
                          ) : (
                            <AvatarFallback>
                              {category.name.charAt(0)}
                            </AvatarFallback>
                          )}
                        </Avatar>
                        <span>{category.name}</span>
                      </div>
                    </SelectItem>
                  ))}
              </SelectContent>
            </Select>
          </div>

          <div className="w-full sm:w-auto sm:flex-1">
            <Label htmlFor="search" className="mb-2 block">
              Search by Name
            </Label>
            <Input
              id="search"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="Search products by name"
              className="w-full"
            />
          </div>

          <Dialog
            open={isCreateDialogOpen}
            onOpenChange={setIsCreateDialogOpen}
          >
            <DialogTrigger asChild>
              <Button
                variant="appVariant"
                className="w-full sm:w-auto"
                onClick={() => {
                  setErro(false);
                  setNerro(false);
                  setCerro(false);
                  setNewProduct({
                    name: "",
                    // price: 0,
                    categoryId: "",
                    images: [],
                    // description: "",
                  });
                }}
              >
                <Plus className="mr-2 h-4 w-4" /> Add Product
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Add New Product</DialogTitle>
              </DialogHeader>
              <div className="grid gap-4 py-4">
                <div className="grid grid-cols-4 items-center gap-4">
                  <Label htmlFor="product-name" className="text-right">
                    Name
                  </Label>
                  <Input
                    id="product-name"
                    value={newProduct.name}
                    onChange={(e) =>
                      setNewProduct({ ...newProduct, name: e.target.value })
                    }
                    className="col-span-3"
                  />
                </div>
                {newProduct.name.length <= 0 && nerro && (
                  <>
                    <div>
                      <p className="text-red-700 ml-10">Please Fill Name</p>
                      {/* <p className="text-red-700">Please selet Category</p> */}
                    </div>
                  </>
                )}
                <div className="grid grid-cols-4 items-center gap-4">
                  {/* <Label htmlFor="product-description" className="text-right">
                    Description
                  </Label>
                  <Input
                    id="product-description"
                    value={newProduct.description}
                    onChange={(e) =>
                      setNewProduct({
                        ...newProduct,
                        description: e.target.value,
                      })
                    }
                    className="col-span-3"
                  /> */}

                  {/* <div className="w-full"> */}

                  {/* </div> */}
                  {/* {newProduct.description } */}
                </div>
                {/* {newProduct.description.length <= 0 && cerro && (
                  <>
                    <div>
                      <p className="text-red-700 ml-10">
                        Please Fill Description
                      </p>
                    </div>
                  </>
                )} */}
                {/* <div className="grid grid-cols-4 items-center gap-4">
                  <Label htmlFor="product-price" className="text-right">
                    Price
                  </Label>
                  <Input
                    id="product-price"
                    type="number"
                    value={newProduct.price}
                    onChange={(e) =>
                      setNewProduct({
                        ...newProduct,
                        price: parseFloat(e.target.value),
                      })
                    }
                    className="col-span-3"
                  />
                </div> */}
                {categories && (
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="product-category" className="text-right">
                      Category
                    </Label>
                    <Select
                      value={newProduct.categoryId}
                      onValueChange={(value) =>
                        setNewProduct({ ...newProduct, categoryId: value })
                      }
                    >
                      <SelectTrigger
                        id="product-category"
                        className="col-span-3"
                      >
                        <SelectValue placeholder="Select a category" />
                      </SelectTrigger>
                      <SelectContent>
                        {categories &&
                          categories.length > 0 &&
                          categories?.map((category) => (
                            <SelectItem key={category._id} value={category._id}>
                              {category.name}
                            </SelectItem>
                          ))}
                      </SelectContent>
                    </Select>
                  </div>
                )}
                {/* <div></div> */}
                {!newProduct.categoryId && erro && (
                  <>
                    <div>
                      <p className="text-red-700 ml-10">
                        Please select Category
                      </p>
                      {/* <p className="text-red-700">Please selet Category</p> */}
                    </div>
                  </>
                )}
                <div className="grid grid-cols-4 items-center gap-4">
                  <Label htmlFor="product-images" className="text-right">
                    Images
                  </Label>
                  <Input
                    id="product-images"
                    type="file"
                    accept="image/*"
                    onChange={(e) => handleImageUpload(e, true)}
                    className="col-span-3"
                    multiple
                  />
                </div>
              </div>
              <Button
                onClick={() => {
                  if (
                    newProduct.categoryId &&
                    newProduct.name
                    // && newProduct.description
                  ) {
                    handleAddProduct();
                  } else {
                    newProduct.categoryId ? setErro(false) : setErro(true);
                    newProduct.name ? setNerro(false) : setNerro(true);
                    // newProduct.description ? setCerro(false) : setCerro(true);
                  }
                  // newProduct.categoryId ? handleAddProduct() : setErro(true);
                }}
                variant="appVariant"
              >
                Add Product
              </Button>
            </DialogContent>
          </Dialog>
        </div>
      </div>
      {/* </div> */}
      {/* Products Table */}

      {isProductsLoading || updateLoading ? (
        <div className="flex justify-center items-center h-[50vh]">
          <CircleDashed className="animate-spin text-[#be063f]" />
        </div>
      ) : (
        <>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Image</TableHead>
                <TableHead>Name</TableHead>
                {/* <TableHead>Price</TableHead> */}
                <TableHead>Category</TableHead>
                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {currentItems?.map((product) => (
                <TableRow key={product._id}>
                  <TableCell>
                    <Avatar>
                      {product.images &&
                      product.images.length > 0 &&
                      product.images[0].length > 0 ? (
                        <Image
                          src={product.images[0]}
                          height={200}
                          width={200}
                          alt="BI"
                        />
                      ) : (
                        <AvatarFallback>
                          {product.name.charAt(0).toUpperCase()}
                        </AvatarFallback>
                      )}
                    </Avatar>
                    {/* <Avatar>
                      <AvatarImage
                        src={
                          product.images.length > 0
                            ? product.images[0]
                            : product.name.charAt(0)
                        }
                      />
                      <AvatarFallback>{product.name.charAt(0)}</AvatarFallback>
                    </Avatar> */}
                  </TableCell>
                  <TableCell>{product.name}</TableCell>
                  {/* <TableCell>{product.description}</TableCell> */}
                  {/* <TableCell>
                    $
                    {typeof product.price === "string"
                      ? parseFloat(product.price).toFixed(2)
                      : product.price.toFixed(2)}
                  </TableCell> */}
                  <TableCell>{product.categoryName}</TableCell>
                  <TableCell>
                    {/* Edit Product */}
                    <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                      <DialogTrigger asChild>
                        <Button
                          variant="outline"
                          size="icon"
                          className="mr-2"
                          onClick={() => {
                            setEditingProduct(product);
                          }}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                      </DialogTrigger>
                      <DialogContent>
                        <DialogHeader>
                          <DialogTitle>Edit Product</DialogTitle>
                        </DialogHeader>
                        <div>
                          <Label htmlFor="edit-name" className="text-right">
                            Name
                          </Label>
                          <Input
                            id="edit-name"
                            defaultValue={editingProduct?.name || ""}
                            onChange={(e) =>
                              setEditingProduct(
                                editingProduct
                                  ? { ...editingProduct, name: e.target.value }
                                  : null
                              )
                            }
                            className="col-span-3"
                          />
                          {/* <Label htmlFor="edit-name" className="text-right">
                            Description
                          </Label>
                          <Input
                            id="edit-name"
                            defaultValue={editingProduct?.description || ""}
                            onChange={(e) =>
                              setEditingProduct(
                                editingProduct
                                  ? {
                                      ...editingProduct,
                                      description: e.target.value,
                                    }
                                  : null
                              )
                            }
                            className="col-span-3"
                          /> */}
                          {/* <Label htmlFor="edit-price" className="text-right">
                            Price
                          </Label>
                          <Input
                            id="edit-price"
                            type="number"
                            defaultValue={editingProduct?.price || 0}
                            onChange={(e) =>
                              setEditingProduct(
                                editingProduct
                                  ? {
                                      ...editingProduct,
                                      price: parseFloat(e.target.value),
                                    }
                                  : null
                              )
                            }
                            className="col-span-3"
                          /> */}
                          <div className="flex gap-4 mt-2 mb-2">
                            {editingProduct?.images &&
                              editingProduct.images.length > 0 &&
                              editingProduct.images.map((i, index) => (
                                <div key={index} className="relative group">
                                  <div className="absolute top-0.5 right-0.5 z-10">
                                    <Button
                                      size="icon"
                                      variant="outline"
                                      className="w-6 h-6 duration-200 rounded"
                                      onClick={() => toggleIndex(index)}
                                    >
                                      {ind.includes(index) ? (
                                        <Check className="h-4 w-4 text-green-700" />
                                      ) : (
                                        <X className="h-4 w-4 text-red-700" />
                                      )}
                                    </Button>
                                  </div>
                                  <div className="overflow-hidden rounded-lg shadow-md">
                                    <Image
                                      height={50}
                                      width={50}
                                      src={i}
                                      alt={`Product image ${index + 1}`}
                                      className={`w-24 h-24 object-contain transition-opacity duration-200 ${
                                        ind.includes(index)
                                          ? "opacity-50"
                                          : "opacity-100"
                                      }`}
                                    />
                                  </div>
                                </div>
                              ))}
                          </div>
                          <div className="">
                            <Label htmlFor="image" className="text-right">
                              Images
                            </Label>
                            <Input
                              id="image"
                              type="file"
                              accept="image/*"
                              onChange={(e) => handleImageUpload(e, true)}
                              className="col-span-3"
                              multiple
                            />
                          </div>
                        </div>
                        <Button
                          variant="appVariant"
                          onClick={handleEditProduct}
                        >
                          Edit Product
                        </Button>
                      </DialogContent>
                    </Dialog>

                    {/* View Product */}
                    <Button
                      variant="outline"
                      size="icon"
                      className="mr-2"
                      onClick={() => setViewingProduct(product)}
                    >
                      <Eye className="h-4 w-4" />
                    </Button>

                    <Dialog>
                      <DialogTrigger asChild>
                        <Button
                          variant="outline"
                          size="icon"
                          // onClick={() => handleDeleteProduct(product._id)}
                        >
                          <Trash className="h-4 w-4" />
                        </Button>
                      </DialogTrigger>
                      <DialogContent className="sm:max-w-[425px]">
                        <DialogTitle>Delete {product.name}</DialogTitle>
                        <DialogDescription>
                          Are you sure you want to delete Product {product.name}{" "}
                          of category {product.categoryName}
                        </DialogDescription>

                        <DialogFooter>
                          <Button
                            variant="appVariant"
                            size="icon"
                            onClick={() => handleDeleteProduct(product._id)}
                          >
                            <Trash className="h-4 w-4" />
                          </Button>
                        </DialogFooter>
                      </DialogContent>
                    </Dialog>
                    {/* Delete Product */}
                    {/* <Button
                  variant="outline"
                  size="icon"
                  onClick={() => handleDeleteProduct(product._id)}
                >

                  <Trash className="h-4 w-4" />
                </Button> */}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>

          <div className="flex justify-between items-center mt-4">
            <div>
              Showing {indexOfFirstItem + 1} to{" "}
              {Math.min(indexOfLastItem, filteredProducts?.length || 0)} of{" "}
              {filteredProducts?.length || 0} items
            </div>
            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => paginate(currentPage - 1)}
                disabled={currentPage === 1}
              >
                <ChevronLeft className="h-4 w-4 mr-2" />
                Previous
              </Button>
              <span className="mx-2">
                Page {currentPage} of {totalPages}
              </span>
              <Button
                variant="outline"
                size="sm"
                onClick={() => paginate(currentPage + 1)}
                disabled={currentPage === totalPages}
              >
                Next
                <ChevronRight className="h-4 w-4 ml-2" />
              </Button>
              <div className="flex items-center ml-4">
                <Input
                  type="number"
                  placeholder="Go to page"
                  value={goToPage}
                  onChange={(e) => setGoToPage(e.target.value)}
                  className="w-20 mr-2"
                />
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    const pageNumber = parseInt(goToPage);
                    if (pageNumber >= 1 && pageNumber <= totalPages) {
                      paginate(pageNumber);
                      setGoToPage("");
                    }
                  }}
                >
                  Go
                </Button>
              </div>
            </div>
          </div>
        </>
      )}

      {isLoading && (
        <div>
          <div className="flex justify-center items-center">
            <CircleDashed className="animate-spin text-[#be063f]" />
          </div>
        </div>
      )}
      {isProductsLoading && (
        <div>
          <div className="flex justify-center items-center h-[50vh]">
            <CircleDashed className="animate-spin text-[#be063f]" />
          </div>
        </div>
      )}
      {/* View Product Dialog */}
      {viewingProduct && (
        <Dialog
          open={!!viewingProduct}
          onOpenChange={() => setViewingProduct(null)}
        >
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Product Details</DialogTitle>
            </DialogHeader>

            <div className="grid gap-4 py-4">
              {viewingProduct.images && viewingProduct.images.length > 0 && (
                <Carousel className="mx-10">
                  <CarouselContent>
                    {viewingProduct.images.map((image, index) => (
                      <CarouselItem key={index} className="flex justify-center">
                        <Image
                          src={image}
                          alt={`${viewingProduct.name} ${index + 1}`}
                          width={200}
                          height={200}
                        />
                      </CarouselItem>
                    ))}
                  </CarouselContent>
                  <CarouselPrevious className="text-white bg-gray-700" />
                  <CarouselNext className="text-white bg-gray-700" />
                </Carousel>
              )}
              <div className="flex gap-2">
                <strong>Name: </strong>
                <p className="capitalize">{viewingProduct.name}</p>
              </div>
              <div className="flex gap-2">
                <strong>Category:</strong>{" "}
                <p className="capitalize">
                  {
                    categories?.find((c) => c._id === viewingProduct.categoryId)
                      ?.name
                  }
                </p>
              </div>
              {/* <p>
                <strong>Price:</strong> ${viewingProduct.price}
              </p> */}

              {/* <div className="flex gap-2">
                <strong>Description:</strong>
                <p className="capitalize">{viewingProduct.description}</p>
              </div> */}
            </div>
          </DialogContent>
        </Dialog>
      )}
    </div>
  );
}
