"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 { 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, ArrowUp, ArrowDown, ArrowUpDown } from "lucide-react";
import { toast } from "sonner";
import { Tooltip } from "../../../../../src/components/ui/tooltip";
import { useDebounce } from "../../../../../src/hooks/useDebounce";

interface Size {
  _id: string;
  name: string;
  sortOrder: number;
  isActive: boolean;
  chest?: number;
  shoulder?: number;
  frontLength?: number;
  neck?: number;
  waist?: number;
  hip?: number;
  sleeveLength?: number;
  createdAt: string;
  updatedAt: string;
}

export default function SizesManagement() {
  const [sizes, setSizes] = useState<Size[]>([]);
  const [loading, setLoading] = useState(true);
  const [isAddEditDialogOpen, setIsAddEditDialogOpen] = useState(false);
  const [isViewDialogOpen, setIsViewDialogOpen] = useState(false);
  const [editingSize, setEditingSize] = useState<Size | null>(null);
  const [viewingSize, setViewingSize] = useState<Size | null>(null);
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [sortField, setSortField] = useState<"name" | "sortOrder" | "createdAt">("createdAt");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
  const [pagination, setPagination] = useState({
    total: 0,
    pages: 0,
    page: 1,
    limit: 10
  });

  const [formData, setFormData] = useState({
    name: "",
    sortOrder: "0",
    isActive: "true",
    chest: "",
    shoulder: "",
    frontLength: "",
    neck: "",
    waist: "",
    hip: "",
    sleeveLength: ""
  });

  const debouncedSearch = useDebounce(search, 500)

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

  const fetchSizes = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        page: page.toString(),
        limit: limit.toString(),
        sort: sortField,
        order: sortOrder,
        ...(debouncedSearch && { search: debouncedSearch })
      });
      
      const res = await fetch(`/api/sizes?${params}`);
      const result = await res.json();
      if (result.success) {
        setSizes(result.data);
        setPagination(result.pagination);
      } else {
        toast.error("Failed to fetch sizes");
      }
    } catch {
      toast.error("Error fetching sizes");
    } finally {
      setLoading(false);
    }
  };

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

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

  // Validation function for size name (only letters, numbers, and spaces allowed)
  const isValidSizeName = (name: string) => {
    const regex = /^[A-Za-z0-9\s]+$/;
    return regex.test(name);
  };

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

    if (isSubmitting) return;

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

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

    const sortOrderValue = parseInt(formData.sortOrder) || 0;
    if (sortOrderValue < 0) {
      toast.error("Sort order cannot be negative");
      return;
    }

    setIsSubmitting(true);

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

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

      const res = await fetch(url, {
        method,
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          ...formData,
          sortOrder: sortOrderValue,
          isActive: formData.isActive === "true",
          chest: formData.chest ? parseFloat(formData.chest) : undefined,
          shoulder: formData.shoulder ? parseFloat(formData.shoulder) : undefined,
          frontLength: formData.frontLength ? parseFloat(formData.frontLength) : undefined,
          neck: formData.neck ? parseFloat(formData.neck) : undefined,
          waist: formData.waist ? parseFloat(formData.waist) : undefined,
          hip: formData.hip ? parseFloat(formData.hip) : undefined,
          sleeveLength: formData.sleeveLength ? parseFloat(formData.sleeveLength) : undefined,
        }),
      });

      const result = await res.json();

      if (result.success) {
        toast.success(editingSize ? "Size updated successfully" : "Size created successfully");
        setIsAddEditDialogOpen(false);
        setEditingSize(null);
        resetForm();
        fetchSizes();
      } else {
        toast.error(result.error || "Failed to save size");
      }
    } catch {
      toast.error("Error saving size");
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleEdit = (size: Size) => {
    setEditingSize(size);
    setFormData({
      name: size.name,
      sortOrder: size.sortOrder.toString(),
      isActive: size.isActive.toString(),
      chest: size.chest?.toString() || "",
      shoulder: size.shoulder?.toString() || "",
      frontLength: size.frontLength?.toString() || "",
      neck: size.neck?.toString() || "",
      waist: size.waist?.toString() || "",
      hip: size.hip?.toString() || "",
      sleeveLength: size.sleeveLength?.toString() || ""
    });
    setIsAddEditDialogOpen(true);
  };

  const handleView = (size: Size) => {
    setViewingSize(size);
    setIsViewDialogOpen(true);
  };

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

    try {
      const res = await fetch(`/api/sizes/${sizeId}`, {
        method: "DELETE",
      });

      const result = await res.json();

      if (result.success) {
        toast.success("Size deleted successfully");
        fetchSizes();
      } else {
        toast.error(result.error || "Failed to delete size");
      }
    } catch {
      toast.error("Error deleting size");
    }
  };

  const resetForm = () => {
    setFormData({
      name: "",
      sortOrder: "0",
      isActive: "true",
      chest: "",
      shoulder: "",
      frontLength: "",
      neck: "",
      waist: "",
      hip: "",
      sleeveLength: ""
    });
  };

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

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

  const renderMeasurements = useMemo(() => {
    const measurements = [
      { label: 'Chest', value: viewingSize?.chest },
      { label: 'Shoulder', value: viewingSize?.shoulder },
      { label: 'Front Length', value: viewingSize?.frontLength },
      { label: 'Neck', value: viewingSize?.neck },
      { label: 'Waist', value: viewingSize?.waist },
      { label: 'Hip', value: viewingSize?.hip },
      { label: 'Sleeve Length', value: viewingSize?.sleeveLength },
    ];

    const hasMeasurements = measurements.some(m => m.value !== null && m.value !== undefined);

    if (!hasMeasurements) return null;

    return (
      <div className="space-y-3">
        <Label className="text-sm font-medium text-gray-700 dark:text-white">Measurements (in inches)</Label>
        <div className="grid grid-cols-2 gap-3 bg-gray-50 p-4 rounded-lg dark:bg-[#324153] dark:text-white">
          {measurements.map(({ label, value }) =>
            // value !== null && value !== undefined ? (
              <div key={label} className="space-y-0.5">
                <Label className="text-xs text-gray-500">{label}</Label>
                <p className="text-sm font-medium">{value}"</p>
              </div>
            )
          }
        </div>
      </div>
    );
  }, [viewingSize])

  return (
    <div className="rounded-sm">
      {/* Header */}      

      {/* View Dialog */}
      <Dialog open={isViewDialogOpen} onOpenChange={setIsViewDialogOpen}>
        <DialogContent className="max-w-2xl">
          <div className="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-1 mx-auto">
            <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              <DialogHeader className="flex-shrink-0">
                <DialogTitle>Size Details</DialogTitle>
                <X className="h-6 w-6 p-1 text-white cursor-pointer"
                  onClick={() => {
                    setIsViewDialogOpen(false);
                  }}
                />
              </DialogHeader>
              
              {viewingSize && (
                <div className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-1">
                    <div className="max-h-[60vh] min-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2 pt-2 space-y-4 pb-4">
                      <div className="grid grid-cols-2 gap-4">
                        <div className="space-y-1">
                          <Label className="text-xs text-gray-500">Size Name</Label>
                          <p className="text-base font-medium">{viewingSize.name}</p>
                        </div>

                        <div className="space-y-1">
                          <Label className="text-xs text-gray-500">Sort Order</Label>
                          <p className="text-base">{viewingSize.sortOrder}</p>
                        </div>

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

                      {(viewingSize.chest || viewingSize.shoulder || viewingSize.frontLength || 
                        viewingSize.neck || viewingSize.waist || viewingSize.hip || viewingSize.sleeveLength) && (
                        // <div className="space-y-3">
                        //   <Label className="text-sm font-medium text-gray-700">Measurements (in inches)</Label>
                        //   <div className="grid grid-cols-2 gap-3 bg-gray-50 p-4 rounded-lg dark:bg-[#3B3B3B]">
                        //     {viewingSize.chest && (
                        //       <div className="space-y-0.5">
                        //         <Label className="text-xs text-gray-500">Chest</Label>
                        //         <p className="text-sm font-medium">{viewingSize.chest}"</p>
                        //       </div>
                        //     )}
                        //     {viewingSize.shoulder && (
                        //       <div className="space-y-0.5">
                        //         <Label className="text-xs text-gray-500">Shoulder</Label>
                        //         <p className="text-sm font-medium">{viewingSize.shoulder}"</p>
                        //       </div>
                        //     )}
                        //     {viewingSize.frontLength && (
                        //       <div className="space-y-0.5">
                        //         <Label className="text-xs text-gray-500">Front Length</Label>
                        //         <p className="text-sm font-medium">{viewingSize.frontLength}"</p>
                        //       </div>
                        //     )}
                        //     {viewingSize.neck && (
                        //       <div className="space-y-0.5">
                        //         <Label className="text-xs text-gray-500">Neck</Label>
                        //         <p className="text-sm font-medium">{viewingSize.neck}"</p>
                        //       </div>
                        //     )}
                        //     {viewingSize.waist && (
                        //       <div className="space-y-0.5">
                        //         <Label className="text-xs text-gray-500">Waist</Label>
                        //         <p className="text-sm font-medium">{viewingSize.waist}"</p>
                        //       </div>
                        //     )}
                        //     {viewingSize.hip && (
                        //       <div className="space-y-0.5">
                        //         <Label className="text-xs text-gray-500">Hip</Label>
                        //         <p className="text-sm font-medium">{viewingSize.hip}"</p>
                        //       </div>
                        //     )}
                        //     {viewingSize.sleeveLength && (
                        //       <div className="space-y-0.5">
                        //         <Label className="text-xs text-gray-500">Sleeve Length</Label>
                        //         <p className="text-sm font-medium">{viewingSize.sleeveLength}"</p>
                        //       </div>
                        //     )}
                        //   </div>
                        // </div>
                        renderMeasurements
                      )}

                      <div className="pt-2 mt-2 border-t">
                        <div className="grid grid-cols-2 gap-4">
                          <div className="space-y-0.5">
                            <Label className="text-xs text-gray-500">Created At</Label>
                            <p className="text-xs text-gray-500">{formatDate(viewingSize.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(viewingSize.updatedAt)}</p>
                          </div>
                        </div>
                      </div>
                    </div>

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

      {/* Search and Pagination Limit Dropdown */}
      <div className="flex flex-col gap-4 pt-0 py-1 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex gap-4 pt-0 py-1 flex-row sm:items-center w-full sm:max-w-[500px]">
          <div className="relative flex-1 max-w-sm">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
            <Input
              placeholder="Search sizes..."
              value={search}
              onChange={(e) => handleSearch(e.target.value)}
              className="pl-10"
            />
              <X
              className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 h-4 w-4 cursor-pointer"
              onClick={() => handleSearch('')}
            />
          </div>
          
          {/* PAGINATION LIMIT DROPDOWN */}
          <div className="flex items-center gap-2">
            <Label className="text-sm whitespace-nowrap">Show:</Label>
            <select
              value={limit.toString()}
              onChange={(e) => handleLimitChange(e.target.value)}
              className="px-3 py-2.5 rounded-md border border-input text-sm bg-white dark:bg-[#3B3B3B] focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50"
            >
              <option value="6">6</option>
              <option value="10">10</option>
              <option value="20">20</option>
              <option value="50">50</option>
            </select>
          </div>
        </div>
        <div className="pb-1 flex justify-between items-center">
          <div className="flex items-center gap-3">
            {/* <div className="text-sm text-gray-500 bg-gray-100 px-3 py-1 rounded">
              Total Sizes: {pagination.total}
            </div> */}
            
            <Dialog open={isAddEditDialogOpen} onOpenChange={setIsAddEditDialogOpen}>
              <DialogTrigger asChild>
                <Button
                  onClick={() => {
                    setEditingSize(null);
                    resetForm();
                  }}
                  className="flex items-center gap-2"
                >
                  <Plus className="h-4 w-4" />
                  Add Size
                </Button>
              </DialogTrigger>

              <DialogContent className="max-w-2xl">
                <div className="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-1 mx-auto">
                  <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
                    <DialogHeader className="flex-shrink-0">
                      <DialogTitle>
                        {editingSize ? "Edit Size" : "Add New Size"}
                      </DialogTitle>
                      <X className="h-6 w-6 p-1 text-white cursor-pointer"
                        onClick={() => {
                          setIsAddEditDialogOpen(false);
                        }}
                      />
                    </DialogHeader>
                    <form onSubmit={handleSubmit} className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-1">
                      <div className="max-h-[60vh] min-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2 pt-2 space-y-4 pb-4">
                        {/* Basic Info */}
                        <div className="grid grid-cols-1 gap-4">
                          <div>
                            <Label className="block mb-2">Name <span className="text-red">*</span></Label>
                            <Input
                              value={formData.name}
                              onChange={(e) => {
                                const value = e.target.value;
                                if (/^[A-Za-z0-9\s]*$/.test(value) || value === '') {
                                  setFormData({ ...formData, name: value });
                                }
                              }}
                              onBlur={(e) => {
                                const trimmed = e.target.value.trim();
                                if (trimmed !== e.target.value) {
                                  setFormData({ ...formData, name: trimmed });
                                }
                                if (trimmed && !isValidSizeName(trimmed)) {
                                  toast.error("Size name can only contain letters, numbers, and spaces");
                                }
                              }}
                              placeholder="e.g., S, M, L, XL, 2XL"
                              required
                            />
                            <p className="text-xs text-gray-500 mt-1">
                              Only letters, numbers, and spaces allowed. No special characters.
                            </p>
                          </div>
                          <div>
                            <Label className="block mb-2">Sort Order</Label>
                            <Input
                              type="number"
                              min="1"
                              value={formData.sortOrder}
                              onChange={(e) => {
                                  const value = e.target.value === '' ? '' : Math.max(0, Number(e.target.value)).toString();
                                  setFormData({ ...formData, sortOrder: value === '' ? '0' : value });
                                }}
                              onKeyDown={(e) => {
                                if (e.key === '-') {
                                  e.preventDefault();
                                }
                              }}
                              placeholder="1"
                            />
                            <p className="text-xs text-gray-500 mt-1">Must be 1 or greater</p>
                          </div>
                          <div>
                            <Label className="block mb-2">Status</Label>
                            <select
                              value={formData.isActive}
                              onChange={(e) =>
                                setFormData({ ...formData, isActive: e.target.value })
                              }
                              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2"
                            >
                              <option value="true">Active</option>
                              <option value="false">Inactive</option>
                            </select>
                          </div>
                        </div>

                        {/* Measurements */}
                        {/* <div>
                          <Label className="text-base font-medium">Measurements (optional)</Label>
                          <div className="grid grid-cols-4 gap-4 mt-2">
                            <div>
                              <Label className="text-sm">Chest (inches)</Label>
                              <Input
                                type="number"
                                step="0.1"
                                min={0}
                                value={formData.chest}
                                onChange={(e) => {
                                  const value = e.target.value === '' ? '' : Math.max(0, Number(e.target.value)).toString();
                                  setFormData({ ...formData, chest: value === '' ? '' : value });
                                }}
                                onKeyDown={(e) => {
                                  if (e.key === '-') e.preventDefault();
                                }}
                                placeholder="36.0"
                              />
                            </div>
                            <div>
                              <Label className="text-sm">Shoulder (inches)</Label>
                              <Input
                                type="number"
                                step="0.1"
                                min={0}
                                value={formData.shoulder}
                                onChange={(e) => {
                                  const value = e.target.value === '' ? '' : Math.max(0, Number(e.target.value)).toString();
                                  setFormData({ ...formData, shoulder: value === '' ? '' : value });
                                }}
                                onKeyDown={(e) => {
                                  if (e.key === '-') e.preventDefault();
                                }}
                                placeholder="17.0"
                              />
                            </div>
                            <div>
                              <Label className="text-sm">Front Length (inches)</Label>
                              <Input
                                type="number"
                                step="0.1"
                                min={0}
                                value={formData.frontLength}
                                onChange={(e) => {
                                  const value = e.target.value === '' ? '' : Math.max(0, Number(e.target.value)).toString();
                                  setFormData({ ...formData, frontLength: value === '' ? '' : value });
                                }}
                                onKeyDown={(e) => {
                                  if (e.key === '-') e.preventDefault();
                                }}
                                placeholder="41.0"
                              />
                            </div>
                            <div>
                              <Label className="text-sm">Neck (inches)</Label>
                              <Input
                                type="number"
                                step="0.1"
                                min={0}
                                value={formData.neck}
                                onChange={(e) => {
                                  const value = e.target.value === '' ? '' : Math.max(0, Number(e.target.value)).toString();
                                  setFormData({ ...formData, neck: value === '' ? '' : value });
                                }}
                                onKeyDown={(e) => {
                                  if (e.key === '-') e.preventDefault();
                                }}
                                placeholder="15.0"
                              />
                            </div>
                            <div>
                              <Label className="text-sm">Waist (inches)</Label>
                              <Input
                                type="number"
                                step="0.1"
                                min={0}
                                value={formData.waist}
                                onChange={(e) => {
                                  const value = e.target.value === '' ? '' : Math.max(0, Number(e.target.value)).toString();
                                  setFormData({ ...formData, waist: value === '' ? '' : value });
                                }}
                                onKeyDown={(e) => {
                                  if (e.key === '-') e.preventDefault();
                                }}
                                placeholder="33.0"
                              />
                            </div>
                            <div>
                              <Label className="text-sm">Hip (inches)</Label>
                              <Input
                                type="number"
                                step="0.1"
                                min={0}
                                value={formData.hip}
                                onChange={(e) => {
                                  const value = e.target.value === '' ? '' : Math.max(0, Number(e.target.value)).toString();
                                  setFormData({ ...formData, hip: value === '' ? '' : value });
                                }}
                                onKeyDown={(e) => {
                                  if (e.key === '-') e.preventDefault();
                                }}
                                placeholder="37.0"
                              />
                            </div>
                            <div>
                              <Label className="text-sm">Sleeve Length (inches)</Label>
                              <Input
                                type="number"
                                step="0.1"
                                min={0}
                                value={formData.sleeveLength}
                                onChange={(e) => {
                                  const value = e.target.value === '' ? '' : Math.max(0, Number(e.target.value)).toString();
                                  setFormData({ ...formData, sleeveLength: value === '' ? '' : value });
                                }}
                                onKeyDown={(e) => {
                                  if (e.key === '-') e.preventDefault();
                                }}
                                placeholder="24.0"
                              />
                            </div>
                          </div>
                          <p className="text-xs text-gray-500 mt-2">All measurement values must be 0 or greater</p>
                        </div> */}
                      </div>
                      {/* Actions */}
                      <div className="flex justify-end space-x-3 px-4 pb-3 pt-3 border-t -mx-2">
                        <Button
                          type="button"
                          variant="outline"
                          onClick={() => setIsAddEditDialogOpen(false)}
                        >
                          Cancel
                        </Button>
                        <Button type="submit" disabled={isSubmitting}>
                          {isSubmitting ? "Saving..." : (editingSize ? "Update" : "Create")}
                        </Button>
                      </div>
                    </form>

                  </div>
                </div>
              </DialogContent>
            </Dialog>
          </div>
        </div>
      </div>

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

          <TableBody>
            {loading ? (
                          <TableRow className='bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800'>
                            <TableCell colSpan={6} className="px-4 py-8 text-center">
                              <div className="flex items-center justify-center">
                                <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
                                <span className="ml-2">Loading...</span>
                              </div>
                            </TableCell>
                          </TableRow>
                        ) : sizes.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} className="text-center py-8">
                      No sizes found
                    </TableCell>
                  </TableRow>
                ) : (
                sizes.map((size, index) => (
                <TableRow key={size._id} className="bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800">
                  <TableCell className="text-center">
                    {sortField === "createdAt" && sortOrder === "asc"
                      ? pagination.total - ((pagination.page - 1) * pagination.limit) - index  // desc
                      : ((pagination.page - 1) * pagination.limit) + index + 1                 // asc
                    }
                  </TableCell>
                  <TableCell className="text-center font-medium">
                    {size.name}
                  </TableCell>
                  <TableCell className="text-center">{size.sortOrder}</TableCell>
                  {/* <TableCell className="text-center">
                    <div className="text-sm text-gray-600">
                      {size.chest && `Chest: ${size.chest}" `}
                      {size.shoulder && `Shoulder: ${size.shoulder}" `}
                      {size.waist && `Waist: ${size.waist}"`}
                    </div>
                  </TableCell> */}
                  <TableCell className="text-center">
                    <Badge variant={size.isActive ? "default" : "secondary"}>
                      {size.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(size)}
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Edit">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleEdit(size)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                      <Tooltip text="Delete">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleDelete(size._id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </Tooltip>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>

        {/* Pagination */}
        {pagination.pages > 1 && (
          <div className="flex items-center justify-between mt-4 p-4">
            <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="outline"
                size="sm"
                onClick={() => setPage(page - 1)}
                disabled={page === 1}
              >
                <ChevronLeft className="h-4 w-4" />
                Previous
              </Button>
              <span className="text-sm">
                Page {page} of {pagination.pages}
              </span>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPage(page + 1)}
                disabled={page === pagination.pages}
              >
                Next
                <ChevronRightIcon className="h-4 w-4" />
              </Button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}