"use client";

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

interface Category {
  _id: string;
  name: string;
  slug: string;
  description?: string;
  image?: string;
  parent?: {
    _id: string;
    name: string;
    slug: string;
  };
  level: number;
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
}

export default function SubcategoriesManagement() {
  const [categories, setCategories] = useState<Category[]>([]);
  const [selectcategories, setSelectcategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [isAddEditDialogOpen, setIsAddEditDialogOpen] = useState(false);
  const [isViewDialogOpen, setIsViewDialogOpen] = useState(false);
  const [editingCategory, setEditingCategory] = useState<Category | null>(null);
  const [viewingCategory, setViewingCategory] = useState<Category | null>(null);
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [sortField, setSortField] = useState<"name" | "createdAt">("createdAt");
  const [sortOrder, setSortOrder] = useState<"desc" | "asc">("desc");
  const [pagination, setPagination] = useState({
    total: 0,
    pages: 0,
    page: 1,
    limit: 10,
  });
  const [open, setOpen] = useState(false);
  const [activeIndex, setActiveIndex] = useState(0);
  const openPreview = (index: number) => {
    setActiveIndex(index);
    setOpen(true);
  };
  const previewImages = useMemo(
    () =>
      categories
        .map((item: any) => ({
          src: item.image,
          name: item.name,
        }))
        .filter((i) => typeof i.src === "string" && i.src.trim()),
    [categories],
  );
  const [formData, setFormData] = useState({
    name: "",
    description: "",
    parent: "",
    image: "",
    isActive: true,
  });

  const debouncedSearch = useDebounce(search, 500);

  useEffect(() => {
    fetchCategories();
    fetchselectCategories();
  }, [debouncedSearch, page, limit, sortField, sortOrder]);

  // Cleanup object URLs
  useEffect(() => {
    return () => {
      if (formData.image && formData.image.startsWith("blob:")) {
        URL.revokeObjectURL(formData.image);
      }
    };
  }, [formData.image]);

  const fetchselectCategories = async () => {
    try {
      const params = new URLSearchParams({
        level: "1",
        limit: "100",
      });

      const response = await fetch(`/api/categories?${params}`);
      const result = await response.json();
      if (result.success) {
        setSelectcategories(result.data);
      } else {
        toast.error("Failed to fetch categories");
      }
    } catch (error) {
      toast.error("Error fetching categories");
    }
  };

  const fetchCategories = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        level: "2",
        page: page.toString(),
        limit: limit.toString(),
        sort: sortField,
        order: sortOrder,
        ...(debouncedSearch && { search: debouncedSearch }),
      });

      const response = await fetch(`/api/categories?${params}`);
      const result = await response.json();
      if (result.success) {
        setCategories(result.data);
        setPagination(result.pagination);
      } else {
        toast.error("Failed to fetch categories");
      }
    } catch (error) {
      toast.error("Error fetching categories");
    } finally {
      setLoading(false);
    }
  };

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

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

  // Validation function for subcategory name (only letters and spaces)
  const isValidSubcategoryName = (name: string) => {
    const regex = /^[A-Za-z\s]+$/;
    return regex.test(name);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!formData.name.trim()) {
      toast.error("Subcategory name is required");
      return;
    }

    if (!isValidSubcategoryName(formData.name)) {
      toast.error(
        "Subcategory name can only contain letters and spaces (no numbers or special characters)",
      );
      return;
    }

    try {
      const url = editingCategory
        ? `/api/categories/${editingCategory._id}`
        : "/api/categories";

      const method = editingCategory ? "PUT" : "POST";

      const form = new FormData();
      form.append("name", formData.name);
      form.append("description", formData.description);
      form.append("parent", formData.parent);
      form.append("isActive", String(formData.isActive));

      if (imageFile) {
        form.append("image", imageFile);
      }

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

      const result = await response.json();

      if (result.success) {
        toast.success(
          editingCategory
            ? "Subcategory updated successfully"
            : "Subcategory created successfully",
        );
        setIsAddEditDialogOpen(false);
        setEditingCategory(null);
        setImageFile(null);
        resetForm();
        fetchCategories();
        fetchselectCategories();
      } else {
        toast.error(result.error || "Failed to save subcategory");
      }
    } catch (error) {
      console.error("Error saving subcategory:", error);
      toast.error("Error saving subcategory");
    }
  };

  const handleEdit = (category: Category) => {
    setEditingCategory(category);
    setFormData({
      name: category.name,
      description: category.description || "",
      parent: category.parent?._id || "",
      image: category.image || "",
      isActive: category.isActive,
    });
    setImageFile(null);
    setIsAddEditDialogOpen(true);
  };

  const handleView = (category: Category) => {
    setViewingCategory(category);
    setIsViewDialogOpen(true);
  };

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

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

  //     const result = await response.json();

  //     if (result.success) {
  //       toast.success("Subcategory deleted successfully");
  //       fetchCategories();
  //       fetchselectCategories();
  //     } else {
  //       toast.error(result.error || "Failed to delete subcategory");
  //     }
  //   } catch (error) {
  //     toast.error("Error deleting subcategory");
  //   }
  // };
  const handleDelete = async (categoryId: string) => {
    if (!confirm("Are you sure you want to delete this subcategory?")) return;

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

      const result = await response.json();

      if (result.success) {
        toast.success("Subcategory deleted successfully");

        // If current page becomes empty after delete
        if (categories.length === 1 && page > 1) {
          setPage((prev) => prev - 1);
        } else {
          fetchCategories();
        }

        fetchselectCategories();
      } else {
        toast.error(result.error || "Failed to delete subcategory");
      }
    } catch (error) {
      toast.error("Error deleting subcategory");
    }
  };
  const resetForm = () => {
    setFormData({
      name: "",
      description: "",
      parent: "",
      image: "",
      isActive: true,
    });
    setImageFile(null);
  };

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

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

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

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

              {viewingCategory && (
                <div className="flex flex-1 flex-col p-4 pb-0 pl-2 pr-2">
                  <div className="max-h-[60vh] min-h-[60vh] flex-1 space-y-4 overflow-y-auto pb-4 pl-2 pr-2 pt-2">
                    {viewingCategory.image ? (
                      <div className="flex justify-center">
                        <img
                          src={viewingCategory.image}
                          alt={viewingCategory.name}
                          className="h-32 w-32 rounded-lg border-2 border-gray-200 object-cover"
                        />
                      </div>
                    ) : (
                      <DefaultImage />
                    )}

                    <div className="grid grid-cols-2 gap-3">
                      <div className="space-y-0.5">
                        <Label className="text-xs text-gray-500">
                          Subcategory Name
                        </Label>
                        <p className="text-sm font-medium">
                          {viewingCategory.name}
                        </p>
                      </div>

                      {/* <div className="space-y-0.5">
                        <Label className="text-xs text-gray-500">Slug</Label>
                        <p className="text-sm break-all">{viewingCategory.slug}</p>
                      </div> */}

                      <div className="space-y-0.5">
                        <Label className="text-xs text-gray-500">
                          Parent Category
                        </Label>
                        <p className="text-sm">
                          {viewingCategory.parent?.name || "-"}
                        </p>
                      </div>

                      <div className="space-y-0.5">
                        <Label className="mr-2 text-xs text-gray-500">
                          Status
                        </Label>
                        <Badge
                          variant={
                            viewingCategory.isActive ? "default" : "secondary"
                          }
                          className="mt-1"
                        >
                          {viewingCategory.isActive ? "Active" : "Inactive"}
                        </Badge>
                      </div>

                      {/* <div className="space-y-0.5">
                        <Label className="text-xs text-gray-500">Level</Label>
                        <p className="text-sm">{viewingCategory.level}</p>
                      </div> */}

                      {viewingCategory.description && (
                        <div className="col-span-2 space-y-0.5">
                          <Label className="text-xs text-gray-500">
                            Description
                          </Label>
                          <p className="max-h-24 overflow-y-auto whitespace-pre-wrap break-words rounded-md bg-gray-50 p-2 text-sm text-gray-800 dark:bg-[#324153] dark:text-white">
                            <Interweave content={viewingCategory.description} />
                          </p>
                        </div>
                      )}

                      <div className="col-span-2 pt-2">
                        <div className="grid grid-cols-2 gap-3 border-t pt-2">
                          <div className="space-y-0.5">
                            <Label className="text-xs text-gray-500">
                              Created At
                            </Label>
                            <p className="text-xs text-gray-500">
                              {formatDate(viewingCategory.createdAt)}
                            </p>
                          </div>

                          <div className="space-y-0.5">
                            <Label className="text-xs text-gray-500">
                              Last Updated
                            </Label>
                            <p className="text-xs text-gray-500">
                              {formatDate(viewingCategory.updatedAt)}
                            </p>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

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

      {/* Search with Pagination Limit Dropdown */}
      <div className="flex flex-col gap-4 py-1 pt-0 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex w-full flex-row gap-4 py-1 pt-0 sm:max-w-[500px] sm:items-center">
          <div className="relative max-w-sm flex-1">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-gray-400" />
            <Input
              placeholder="Search subcategories..."
              value={search}
              onChange={(e) => handleSearch(e.target.value)}
              className="pl-10"
            />
            <X
              className="absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 cursor-pointer text-gray-400"
              onClick={() => handleSearch("")}
            />
          </div>
          {open && (
            <ImagePreviewModal
              images={previewImages}
              activeIndex={activeIndex}
              setActiveIndex={setActiveIndex}
              onClose={() => setOpen(false)}
            />
          )}
          {/* PAGINATION LIMIT DROPDOWN */}
          <div className="flex items-center gap-2">
            <Label className="whitespace-nowrap text-sm">Show:</Label>
            <select
              value={limit.toString()}
              onChange={(e) => handleLimitChange(e.target.value)}
              className="border-input focus:ring-ring rounded-md border bg-white px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-[#3B3B3B]"
            >
              <option value="6">6</option>
              <option value="10">10</option>
              <option value="20">20</option>
              <option value="50">50</option>
            </select>
          </div>
        </div>
        <div className="flex items-center justify-between">
          {/* <h2 className="text-2xl font-bold">Subcategories Management</h2> */}
          <div className="flex items-center gap-3">
            {/* <div className="text-sm text-gray-500 bg-gray-100 px-3 py-1 rounded">
              Total Subcategories: {pagination.total}
            </div> */}
            <Dialog
              open={isAddEditDialogOpen}
              onOpenChange={setIsAddEditDialogOpen}
            >
              <DialogTrigger asChild>
                <Button
                  onClick={() => {
                    resetForm();
                    setIsAddEditDialogOpen(true);
                  }}
                >
                  <Plus className="h-4 w-4" />
                  Add Subcategory
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-2xl">
                <div className="mx-auto my-1 flex min-h-[calc(100%-0.5rem)] max-w-lg items-center">
                  <div className="relative flex w-full flex-col gap-0 rounded-lg border-0 border-stroke bg-white p-0 text-dark-5 shadow-lg dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
                    <DialogHeader>
                      <DialogTitle>
                        {editingCategory
                          ? "Edit Subcategory"
                          : "Add New Subcategory"}
                      </DialogTitle>
                      <X
                        className="h-6 w-6 cursor-pointer p-1 text-white"
                        onClick={() => {
                          setIsAddEditDialogOpen(false);
                        }}
                      />
                    </DialogHeader>
                    <form
                      onSubmit={handleSubmit}
                      className="flex flex-1 flex-col p-4 pb-0 pl-2 pr-2"
                    >
                      <div className="max-h-[60vh] min-h-[60vh] flex-1 space-y-4 overflow-y-auto pb-4 pl-2 pr-2 pt-2">
                        <div>
                          <Label className="mb-2 block" htmlFor="name">
                            Subcategory Name <span className="text-red">*</span>
                          </Label>
                          <Input
                            id="name"
                            value={formData.name}
                            onChange={(e) => {
                              const value = e.target.value;
                              if (/^[A-Za-z\s]*$/.test(value) || value === "") {
                                setFormData((prev) => ({
                                  ...prev,
                                  name: value,
                                }));
                              }
                            }}
                            onBlur={(e) => {
                              const trimmed = e.target.value.trim();
                              if (trimmed !== e.target.value) {
                                setFormData((prev) => ({
                                  ...prev,
                                  name: trimmed,
                                }));
                              }
                              if (trimmed && !isValidSubcategoryName(trimmed)) {
                                toast.error(
                                  "Subcategory name can only contain letters and spaces",
                                );
                              }
                            }}
                            placeholder="e.g., Mobile Phones, Laptops, Headphones"
                            required
                          />
                          <p className="mt-1 text-xs text-gray-500">
                            Only letters (A-Z, a-z) and spaces are allowed. No
                            numbers or special characters.
                          </p>
                        </div>
                        <div>
                          <Label className="mb-2 block" htmlFor="parent">
                            Parent Category <span className="text-red">*</span>
                          </Label>
                          <select
                            id="parent"
                            value={formData.parent}
                            onChange={(e) =>
                              setFormData((prev) => ({
                                ...prev,
                                parent:
                                  e.target.value === "none"
                                    ? ""
                                    : e.target.value,
                              }))
                            }
                            required
                            className="border-input focus:ring-ring w-full rounded-md border bg-white px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-[#3B3B3B]"
                          >
                            <option value="" disabled>
                              Select Parent Category
                            </option>
                            {selectcategories
                              .filter((item: any) => item.isActive)
                              ?.map((category) => (
                                <option key={category._id} value={category._id}>
                                  {category.name}
                                </option>
                              ))}
                          </select>
                        </div>
                        <div>
                          <Label className="mb-2 block" htmlFor="description">
                            Description
                          </Label>
                          <Editor
                            value={formData.description}
                            onChange={(value: any) =>
                              setFormData((prev) => ({
                                ...prev,
                                description: value,
                              }))
                            }
                            rows={3}
                          />
                        </div>

                        <div className="flex items-center gap-2">
                          <Switch
                            checked={formData.isActive}
                            onCheckedChange={(checked) =>
                              setFormData((prev) => ({
                                ...prev,
                                isActive: checked,
                              }))
                            }
                            className="peer data-[state=checked]:border-purple-300 data-[state=unchecked]:border-gray-400 data-[state=unchecked]:bg-gray-100"
                          />
                          <Label>
                            {formData.isActive ? "Active" : "Inactive"}
                          </Label>
                        </div>

                        <div className="space-y-2">
                          <Label htmlFor="image"> Subcategory Image</Label>
                          <div className="flex items-center gap-3">
                            {formData.image ? (
                              <div className="group relative flex-shrink-0">
                                <img
                                  src={formData.image}
                                  alt="Preview"
                                  className="h-12 w-12 rounded-md border border-gray-200 object-cover"
                                />
                                <button
                                  type="button"
                                  onClick={() => {
                                    setFormData((prev) => ({
                                      ...prev,
                                      image: "",
                                    }));
                                    setImageFile(null);
                                  }}
                                  className="absolute -right-1.5 -top-1.5 rounded-full bg-red-500 p-0.5 text-white opacity-0 transition-opacity group-hover:opacity-100"
                                >
                                  <X className="h-2.5 w-2.5" />
                                </button>
                              </div>
                            ) : (
                              <div className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-md border border-gray-200 bg-gray-100">
                                <Image className="h-5 w-5 text-gray-400" />
                              </div>
                            )}

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

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

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

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

              {/* <TableHead className="text-center">Slug</TableHead> */}
              <TableHead className="text-center">Category</TableHead>
              <TableHead className="text-center">Image</TableHead>
              <TableHead className="text-center">Status</TableHead>
              <TableHead className="text-center">Action</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow className="bg-white hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800">
                <TableCell colSpan={6} className="px-4 py-8 text-center">
                  <div className="flex items-center justify-center">
                    <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
                    <span className="ml-2">Loading...</span>
                  </div>
                </TableCell>
              </TableRow>
            ) : categories.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="py-8 text-center">
                  No subcategories found
                </TableCell>
              </TableRow>
            ) : (
              categories.map((category, index) => (
                <TableRow
                  key={category._id}
                  className="bg-white hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800"
                >
                  <TableCell className="text-center">
                    {
                      sortField === "createdAt" && sortOrder === "asc"
                        ? pagination.total -
                          (pagination.page - 1) * pagination.limit -
                          index // desc
                        : (pagination.page - 1) * pagination.limit + index + 1 // asc
                    }
                  </TableCell>
                  <TableCell className="text-center font-medium">
                    {category.name}
                  </TableCell>
                  {/* <TableCell className="text-center">{category.slug}</TableCell> */}
                  <TableCell className="text-center">
                    {category.parent?.name || "-"}
                  </TableCell>
                  <TableCell className="text-center">
                    {category.image ? (
                      <img
                        src={category.image}
                        alt={category.name}
                        onClick={() => openPreview(index)}
                        className="mx-auto h-10 w-10 cursor-pointer rounded object-cover"
                      />
                    ) : (
                      <div className="justify-center">
                        <DefaultImage />
                      </div>
                    )}
                  </TableCell>
                  <TableCell className="d-flex text-center">
                    <Badge
                      variant={category.isActive ? "default" : "secondary"}
                    >
                      {category.isActive ? "Active" : "Inactive"}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-center">
                    <div className="flex justify-center gap-1">
                      <Tooltip text="View">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleView(category)}
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Edit">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleEdit(category)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Delete">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleDelete(category._id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

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