"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useCallback, useMemo, useRef } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { cn } from "../../lib/utils/index.js";
import { Button } from "../ui/button.js";
import { Input } from "../ui/input.js";
import { Card, CardContent } from "../ui/card.js";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from "../ui/dropdown-menu.js";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle
} from "../ui/alert-dialog.js";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "../ui/select.js";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from "../ui/table.js";
import {
  MoreHorizontal,
  ChevronLeft,
  ChevronRight,
  ChevronsLeft,
  ChevronsRight,
  Plus,
  Search,
  Eye,
  Edit,
  Copy,
  Trash2,
  ExternalLink,
  Loader2
} from "lucide-react";
import { SkeletonEntityList } from "../ui/skeleton-list.js";
import { EntityFieldRenderer } from "./EntityFieldRenderer.js";
import { sel } from "../../lib/test/index.js";
import { usePermission } from "../../lib/permissions/hooks.js";
function EntityTable({
  entityConfig,
  data,
  columns: customColumns,
  selectable = false,
  selectedIds: controlledSelectedIds,
  onSelectionChange,
  onRowClick,
  basePath,
  quickActions: customQuickActions,
  dropdownActions: customDropdownActions,
  useDefaultActions = true,
  pagination,
  currentSort,
  onSort,
  searchQuery = "",
  onSearch,
  enableSearch = true,
  getItemName,
  emptyState,
  loading = false,
  onDelete,
  onDuplicate,
  getPublicUrl,
  className,
  teamId,
  headerActions,
  showHeader = true
}) {
  var _a, _b, _c, _d, _e, _f;
  const router = useRouter();
  const slug = entityConfig.slug;
  const [internalSelectedIds, setInternalSelectedIds] = useState(/* @__PURE__ */ new Set());
  const [internalPage, setInternalPage] = useState(1);
  const [internalPageSize, setInternalPageSize] = useState((pagination == null ? void 0 : pagination.pageSize) ?? 10);
  const [localSearchQuery, setLocalSearchQuery] = useState(searchQuery);
  const [confirmDialog, setConfirmDialog] = useState({
    open: false,
    item: null,
    action: null
  });
  const [isDeleting, setIsDeleting] = useState(false);
  const lastClickedIndexRef = useRef(null);
  const canCreate = usePermission(`${slug}.create`);
  const canUpdate = usePermission(`${slug}.update`);
  const canDelete = usePermission(`${slug}.delete`);
  const selectedIds = controlledSelectedIds ?? internalSelectedIds;
  const setSelectedIds = useCallback(
    (ids) => {
      if (onSelectionChange) {
        onSelectionChange(ids);
      } else {
        setInternalSelectedIds(ids);
      }
    },
    [onSelectionChange]
  );
  const isPublicEntity = ((_a = entityConfig.access) == null ? void 0 : _a.public) === true;
  const columns = useMemo(() => {
    if (customColumns) return customColumns;
    return entityConfig.fields.filter((field) => field.display.showInList).filter((field) => field.name !== "slug" || isPublicEntity).sort((a, b) => a.display.order - b.display.order).map((field) => ({
      key: field.name,
      header: field.display.label,
      sortable: field.api.sortable,
      className: field.display.className
    }));
  }, [customColumns, entityConfig.fields, isPublicEntity]);
  const publicBasePath = ((_b = entityConfig.access) == null ? void 0 : _b.basePath) ?? ((_d = (_c = entityConfig.builder) == null ? void 0 : _c.public) == null ? void 0 : _d.basePath);
  const getPublicUrlForItem = useCallback((item) => {
    if (getPublicUrl) return getPublicUrl(item);
    if (!publicBasePath) return null;
    const itemSlug = item.slug;
    if (!itemSlug) return null;
    return publicBasePath === "/" ? `/${itemSlug}` : `${publicBasePath}/${itemSlug}`;
  }, [getPublicUrl, publicBasePath]);
  const isPublished = useCallback((item) => {
    const status = item.status;
    return status === "published";
  }, []);
  const defaultQuickActions = useMemo(() => {
    if (!useDefaultActions) return [];
    const actions = [];
    if (canUpdate) {
      actions.push({
        id: "edit",
        label: "Edit",
        icon: /* @__PURE__ */ jsx(Edit, { className: "h-3 w-3" }),
        onClick: (item) => {
          router.push(`${basePath || `/dashboard/${slug}`}/${item.id}/edit`);
        },
        dataCySuffix: "edit"
      });
    }
    if (publicBasePath) {
      actions.push({
        id: "view-public",
        label: "View",
        icon: /* @__PURE__ */ jsx(ExternalLink, { className: "h-3 w-3" }),
        onClick: (item) => {
          const url = getPublicUrlForItem(item);
          if (url) window.open(url, "_blank");
        },
        visible: (item) => isPublished(item) && !!getPublicUrlForItem(item),
        dataCySuffix: "view-public"
      });
    }
    return actions;
  }, [useDefaultActions, canUpdate, basePath, slug, router, publicBasePath, getPublicUrlForItem, isPublished]);
  const defaultDropdownActions = useMemo(() => {
    if (!useDefaultActions) return [];
    const actions = [];
    actions.push({
      id: "view",
      label: "View",
      icon: /* @__PURE__ */ jsx(Eye, { className: "h-4 w-4" }),
      onClick: (item) => {
        router.push(`${basePath || `/dashboard/${slug}`}/${item.id}`);
      },
      dataCySuffix: "view"
    });
    if (canUpdate) {
      actions.push({
        id: "edit",
        label: "Edit",
        icon: /* @__PURE__ */ jsx(Edit, { className: "h-4 w-4" }),
        onClick: (item) => {
          router.push(`${basePath || `/dashboard/${slug}`}/${item.id}/edit`);
        },
        dataCySuffix: "edit"
      });
    }
    if (canUpdate && onDuplicate) {
      actions.push({
        id: "duplicate",
        label: "Duplicate",
        icon: /* @__PURE__ */ jsx(Copy, { className: "h-4 w-4" }),
        onClick: (item) => {
          onDuplicate(item.id);
        },
        dataCySuffix: "duplicate"
      });
    }
    if (publicBasePath) {
      actions.push({
        id: "view-public",
        label: "View Public",
        icon: /* @__PURE__ */ jsx(ExternalLink, { className: "h-4 w-4" }),
        onClick: (item) => {
          const url = getPublicUrlForItem(item);
          if (url) window.open(url, "_blank");
        },
        // Only show in dropdown for non-published items (published shows as quick action)
        visible: (item) => !isPublished(item) && !!getPublicUrlForItem(item),
        dataCySuffix: "view-public"
      });
    }
    if (canDelete && onDelete) {
      actions.push({
        id: "delete",
        label: "Delete",
        icon: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" }),
        onClick: () => {
        },
        // Handled by confirmation
        variant: "destructive",
        separator: true,
        requiresConfirmation: true,
        confirmationTitle: (item) => `Delete ${entityConfig.names.singular}?`,
        confirmationDescription: (item) => {
          const name = (getItemName == null ? void 0 : getItemName(item)) || item.name || item.title || item.id;
          return `This will permanently delete "${name}". This action cannot be undone.`;
        },
        dataCySuffix: "delete"
      });
    }
    return actions;
  }, [useDefaultActions, canUpdate, canDelete, onDelete, onDuplicate, basePath, slug, router, entityConfig.names.singular, getItemName, publicBasePath, getPublicUrlForItem, isPublished]);
  const quickActions = useMemo(() => {
    return [...defaultQuickActions, ...customQuickActions || []];
  }, [defaultQuickActions, customQuickActions]);
  const dropdownActions = useMemo(() => {
    return [...defaultDropdownActions, ...customDropdownActions || []];
  }, [defaultDropdownActions, customDropdownActions]);
  const isPaginated = !!pagination;
  const currentPage = (pagination == null ? void 0 : pagination.currentPage) ?? internalPage;
  const pageSize = (pagination == null ? void 0 : pagination.onPageSizeChange) ? pagination.pageSize : internalPageSize;
  const totalItems = (pagination == null ? void 0 : pagination.totalItems) ?? data.length;
  const totalPages = Math.ceil(totalItems / pageSize);
  const paginatedData = useMemo(() => {
    if (!isPaginated) return data;
    if ((pagination == null ? void 0 : pagination.totalItems) !== void 0 && pagination.totalItems !== data.length) {
      return data;
    }
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    return data.slice(startIndex, endIndex);
  }, [data, isPaginated, pagination == null ? void 0 : pagination.totalItems, currentPage, pageSize]);
  const displayData = isPaginated ? paginatedData : data;
  const allSelected = displayData.length > 0 && displayData.every((item) => selectedIds.has(item.id));
  const someSelected = selectedIds.size > 0 && !allSelected && displayData.some((item) => selectedIds.has(item.id));
  const handlePageChange = useCallback(
    (page) => {
      if (page < 1 || page > totalPages) return;
      if (pagination == null ? void 0 : pagination.onPageChange) {
        pagination.onPageChange(page);
      } else {
        setInternalPage(page);
      }
    },
    [pagination, totalPages]
  );
  const handlePageSizeChange = useCallback(
    (newPageSize) => {
      if (pagination == null ? void 0 : pagination.onPageSizeChange) {
        pagination.onPageSizeChange(newPageSize);
      } else {
        setInternalPageSize(newPageSize);
        setInternalPage(1);
      }
    },
    [pagination]
  );
  const toggleAll = useCallback(() => {
    if (allSelected) {
      const newSet = new Set(selectedIds);
      displayData.forEach((item) => newSet.delete(item.id));
      setSelectedIds(newSet);
    } else {
      const newSet = new Set(selectedIds);
      displayData.forEach((item) => newSet.add(item.id));
      setSelectedIds(newSet);
    }
  }, [allSelected, displayData, selectedIds, setSelectedIds]);
  const toggleOne = useCallback(
    (id, index, shiftKey) => {
      const newSet = new Set(selectedIds);
      if (shiftKey && lastClickedIndexRef.current !== null) {
        const start = Math.min(lastClickedIndexRef.current, index);
        const end = Math.max(lastClickedIndexRef.current, index);
        for (let i = start; i <= end; i++) {
          if (displayData[i]) {
            newSet.add(displayData[i].id);
          }
        }
      } else {
        if (newSet.has(id)) {
          newSet.delete(id);
        } else {
          newSet.add(id);
        }
      }
      lastClickedIndexRef.current = index;
      setSelectedIds(newSet);
    },
    [selectedIds, setSelectedIds, displayData]
  );
  const handleSearch = useCallback(
    (query) => {
      setLocalSearchQuery(query);
      onSearch == null ? void 0 : onSearch(query);
    },
    [onSearch]
  );
  const handleRowClick = useCallback(
    (item) => {
      if (onRowClick) {
        onRowClick(item);
      } else {
        router.push(`${basePath || `/dashboard/${slug}`}/${item.id}`);
      }
    },
    [onRowClick, router, basePath, slug]
  );
  const handleDropdownAction = useCallback(
    (action, item) => {
      if (action.requiresConfirmation) {
        setConfirmDialog({ open: true, item, action });
      } else {
        action.onClick(item);
      }
    },
    []
  );
  const confirmAction = useCallback(async () => {
    if (confirmDialog.action && confirmDialog.item) {
      if (confirmDialog.action.id === "delete" && onDelete) {
        setIsDeleting(true);
        try {
          await onDelete(confirmDialog.item.id);
        } finally {
          setIsDeleting(false);
        }
      } else {
        confirmDialog.action.onClick(confirmDialog.item);
      }
    }
    setConfirmDialog({ open: false, item: null, action: null });
  }, [confirmDialog, onDelete]);
  const getConfirmationTitle = useCallback(() => {
    const { action, item } = confirmDialog;
    if (!action || !item) return "Are you sure?";
    if (typeof action.confirmationTitle === "function") {
      return action.confirmationTitle(item);
    }
    return action.confirmationTitle || "Are you sure?";
  }, [confirmDialog]);
  const getConfirmationDescription = useCallback(() => {
    const { action, item } = confirmDialog;
    if (!action || !item) return "This action cannot be undone.";
    if (typeof action.confirmationDescription === "function") {
      return action.confirmationDescription(item);
    }
    return action.confirmationDescription || "This action cannot be undone.";
  }, [confirmDialog]);
  if (loading) {
    return /* @__PURE__ */ jsx(SkeletonEntityList, { rowCount: pageSize, columnCount: columns.length });
  }
  const hasActions = dropdownActions.length > 0;
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: cn(showHeader && "p-6", "space-y-4", className),
      "data-cy": sel("entities.list.table.container", { slug }),
      children: [
        showHeader && /* @__PURE__ */ jsxs("div", { className: "flex flex-col sm:flex-row gap-4 justify-between items-start sm:items-center", children: [
          /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
            /* @__PURE__ */ jsx("h2", { className: "text-2xl font-bold tracking-tight", children: entityConfig.names.plural }),
            /* @__PURE__ */ jsxs("p", { className: "text-muted-foreground", children: [
              "Manage your ",
              entityConfig.names.plural.toLowerCase()
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col sm:flex-row gap-2", children: [
            enableSearch && /* @__PURE__ */ jsxs("div", { className: "relative", children: [
              /* @__PURE__ */ jsx(Search, { className: "absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  placeholder: `Search ${entityConfig.names.plural.toLowerCase()}...`,
                  value: localSearchQuery,
                  onChange: (e) => handleSearch(e.target.value),
                  className: "pl-8 w-full sm:w-[300px]",
                  "data-cy": sel("entities.list.search.input", { slug })
                }
              )
            ] }),
            headerActions,
            canCreate && /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsxs(
              Link,
              {
                href: `${basePath || `/dashboard/${slug}`}/create`,
                "data-cy": sel("entities.list.addButton", { slug }),
                children: [
                  /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }),
                  "Add ",
                  entityConfig.names.singular
                ]
              }
            ) })
          ] })
        ] }),
        selectable && selectedIds.size > 0 && /* @__PURE__ */ jsxs(
          "div",
          {
            className: "text-sm text-muted-foreground",
            "data-cy": sel("entities.list.selectionCount", { slug }),
            children: [
              selectedIds.size,
              " of ",
              totalItems,
              " selected"
            ]
          }
        ),
        displayData.length === 0 ? /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "flex flex-col items-center justify-center py-12", children: [
          entityConfig.icon && typeof entityConfig.icon === "function" && entityConfig.icon({
            className: "h-16 w-16 text-muted-foreground/50 mb-4"
          }),
          /* @__PURE__ */ jsxs("h3", { className: "text-lg font-medium mb-2", children: [
            "No ",
            entityConfig.names.plural.toLowerCase(),
            " found"
          ] }),
          /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground text-center max-w-sm", children: localSearchQuery ? `No ${entityConfig.names.plural.toLowerCase()} match your search criteria.` : `Get started by creating your first ${entityConfig.names.singular.toLowerCase()}.` }),
          !localSearchQuery && canCreate && /* @__PURE__ */ jsx(Button, { className: "mt-4", asChild: true, children: /* @__PURE__ */ jsxs(Link, { href: `${basePath || `/dashboard/${slug}`}/create`, children: [
            /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }),
            "Add ",
            entityConfig.names.singular
          ] }) }),
          emptyState
        ] }) }) : /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsx(
            "div",
            {
              className: "overflow-hidden shadow-sm ring-1 ring-black/5 dark:ring-white/10 rounded-lg",
              "data-cy": sel("entities.list.table.container", { slug }),
              children: /* @__PURE__ */ jsxs(Table, { "data-cy": sel("entities.list.table.element", { slug }), children: [
                /* @__PURE__ */ jsx(TableHeader, { className: "bg-muted/50 dark:bg-muted/30", children: /* @__PURE__ */ jsxs(TableRow, { children: [
                  selectable && /* @__PURE__ */ jsx(TableHead, { className: "w-12", children: /* @__PURE__ */ jsx(
                    "input",
                    {
                      type: "checkbox",
                      className: "h-4 w-4 rounded border-border text-primary focus:ring-primary cursor-pointer",
                      checked: allSelected,
                      ref: (el) => {
                        if (el) el.indeterminate = someSelected;
                      },
                      onChange: toggleAll,
                      "aria-label": "Select all",
                      "data-cy": sel("entities.list.table.selectAll", { slug })
                    }
                  ) }),
                  columns.map((column) => /* @__PURE__ */ jsx(
                    TableHead,
                    {
                      className: cn("min-w-[100px]", column.headerClassName),
                      style: column.width ? { width: column.width } : void 0,
                      children: column.sortable && onSort ? /* @__PURE__ */ jsx(
                        Button,
                        {
                          variant: "ghost",
                          onClick: () => {
                            const direction = (currentSort == null ? void 0 : currentSort.field) === column.key && currentSort.direction === "asc" ? "desc" : "asc";
                            onSort(column.key, direction);
                          },
                          className: "-ml-3 h-8 font-medium",
                          children: column.header
                        }
                      ) : /* @__PURE__ */ jsx("span", { className: "font-medium", children: column.header })
                    },
                    column.key
                  )),
                  hasActions && /* @__PURE__ */ jsx(TableHead, { className: "w-12", children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Actions" }) })
                ] }) }),
                /* @__PURE__ */ jsx(TableBody, { className: "divide-y divide-border bg-card", children: displayData.map((item, rowIndex) => /* @__PURE__ */ jsxs(
                  TableRow,
                  {
                    className: cn(
                      "group transition-colors cursor-pointer",
                      selectedIds.has(item.id) ? "bg-primary/5" : "hover:bg-muted/30"
                    ),
                    onClick: () => handleRowClick(item),
                    "data-cy": sel("entities.list.table.row.element", { slug, id: item.id }),
                    children: [
                      selectable && /* @__PURE__ */ jsx(
                        TableCell,
                        {
                          className: "w-12",
                          onClick: (e) => e.stopPropagation(),
                          children: /* @__PURE__ */ jsx(
                            "input",
                            {
                              type: "checkbox",
                              className: "h-4 w-4 rounded border-border text-primary focus:ring-primary cursor-pointer",
                              checked: selectedIds.has(item.id),
                              onChange: () => {
                              },
                              onClick: (e) => {
                                e.stopPropagation();
                                toggleOne(item.id, rowIndex, e.shiftKey);
                              },
                              "aria-label": `Select row ${rowIndex + 1}`,
                              "data-cy": sel("entities.list.table.row.checkbox", { slug, id: item.id })
                            }
                          )
                        }
                      ),
                      columns.map((column, colIndex) => {
                        const field = entityConfig.fields.find((f) => f.name === column.key);
                        const cellValue = item[column.key];
                        const renderCellContent = () => {
                          if (column.render) {
                            return column.render(item);
                          }
                          if (!field) {
                            return /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: String(cellValue ?? "-") });
                          }
                          return /* @__PURE__ */ jsx(
                            EntityFieldRenderer,
                            {
                              field,
                              value: cellValue,
                              mode: "list",
                              context: {
                                entityType: slug,
                                formData: item,
                                teamId
                              }
                            }
                          );
                        };
                        return /* @__PURE__ */ jsx(TableCell, { className: cn(column.className), children: colIndex === 0 && quickActions.length > 0 ? /* @__PURE__ */ jsxs("div", { children: [
                          /* @__PURE__ */ jsx("div", { className: "font-medium", children: renderCellContent() }),
                          /* @__PURE__ */ jsx(
                            "div",
                            {
                              className: "flex items-center gap-1 mt-0.5 opacity-0 group-hover:opacity-100 transition-opacity",
                              onClick: (e) => e.stopPropagation(),
                              children: quickActions.filter((action) => !action.visible || action.visible(item)).map((action) => /* @__PURE__ */ jsxs(
                                "button",
                                {
                                  onClick: () => action.onClick(item),
                                  className: cn(
                                    "inline-flex items-center gap-1 px-1.5 py-0.5 text-[11px] font-medium rounded transition-colors cursor-pointer",
                                    action.variant === "destructive" ? "text-destructive hover:bg-destructive/10" : "text-muted-foreground hover:bg-muted hover:text-foreground"
                                  ),
                                  "data-cy": sel("entities.list.table.row.quickAction", {
                                    slug,
                                    action: action.dataCySuffix || action.id,
                                    id: item.id
                                  }),
                                  children: [
                                    action.icon,
                                    action.label
                                  ]
                                },
                                action.id
                              ))
                            }
                          )
                        ] }) : renderCellContent() }, column.key);
                      }),
                      hasActions && /* @__PURE__ */ jsx(
                        TableCell,
                        {
                          className: "w-12 text-right",
                          onClick: (e) => e.stopPropagation(),
                          children: /* @__PURE__ */ jsxs(DropdownMenu, { children: [
                            /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
                              Button,
                              {
                                variant: "ghost",
                                size: "icon",
                                className: "h-8 w-8",
                                "data-cy": sel("entities.list.table.row.menu", { slug, id: item.id }),
                                children: [
                                  /* @__PURE__ */ jsx(MoreHorizontal, { className: "h-4 w-4" }),
                                  /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Open menu" })
                                ]
                              }
                            ) }),
                            /* @__PURE__ */ jsx(DropdownMenuContent, { align: "end", className: "w-48", children: dropdownActions.filter((action) => !action.visible || action.visible(item)).map((action, actionIndex) => /* @__PURE__ */ jsxs("div", { children: [
                              action.separator && actionIndex > 0 && /* @__PURE__ */ jsx(DropdownMenuSeparator, {}),
                              /* @__PURE__ */ jsxs(
                                DropdownMenuItem,
                                {
                                  onClick: () => handleDropdownAction(action, item),
                                  className: cn(
                                    action.variant === "destructive" && "text-destructive focus:text-destructive"
                                  ),
                                  "data-cy": sel("entities.list.table.row.action", {
                                    slug,
                                    action: action.dataCySuffix || action.id,
                                    id: item.id
                                  }),
                                  children: [
                                    /* @__PURE__ */ jsx("span", { className: "mr-2 h-4 w-4", children: action.icon }),
                                    action.label
                                  ]
                                }
                              )
                            ] }, action.id)) })
                          ] })
                        }
                      )
                    ]
                  },
                  item.id
                )) })
              ] })
            }
          ),
          isPaginated && totalPages > 1 && /* @__PURE__ */ jsxs(
            "div",
            {
              className: "flex items-center justify-between px-4 py-3 border rounded-lg bg-card",
              "data-cy": sel("entities.list.pagination.container", { slug }),
              children: [
                /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2", children: (pagination == null ? void 0 : pagination.showPageSizeSelector) && /* @__PURE__ */ jsxs(Fragment, { children: [
                  /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: "Rows per page:" }),
                  /* @__PURE__ */ jsxs(
                    Select,
                    {
                      value: String(pageSize),
                      onValueChange: (value) => handlePageSizeChange(Number(value)),
                      children: [
                        /* @__PURE__ */ jsx(
                          SelectTrigger,
                          {
                            className: "h-8 w-[70px]",
                            "data-cy": sel("entities.list.pagination.pageSize", { slug }),
                            children: /* @__PURE__ */ jsx(SelectValue, { placeholder: String(pageSize) })
                          }
                        ),
                        /* @__PURE__ */ jsx(SelectContent, { children: ((pagination == null ? void 0 : pagination.pageSizeOptions) ?? [10, 20, 50, 100]).map((size) => /* @__PURE__ */ jsx(
                          SelectItem,
                          {
                            value: String(size),
                            "data-cy": sel("entities.list.pagination.pageSizeOption", { slug, size }),
                            children: size
                          },
                          size
                        )) })
                      ]
                    }
                  )
                ] }) }),
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
                  /* @__PURE__ */ jsxs(
                    "span",
                    {
                      className: "text-sm text-muted-foreground",
                      "data-cy": sel("entities.list.pagination.info", { slug }),
                      children: [
                        "Page ",
                        currentPage,
                        " of ",
                        totalPages,
                        /* @__PURE__ */ jsxs("span", { className: "ml-2 text-xs", children: [
                          "(",
                          (currentPage - 1) * pageSize + 1,
                          "-",
                          Math.min(currentPage * pageSize, totalItems),
                          " of ",
                          totalItems,
                          ")"
                        ] })
                      ]
                    }
                  ),
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
                    /* @__PURE__ */ jsxs(
                      Button,
                      {
                        variant: "outline",
                        size: "icon",
                        className: "h-8 w-8",
                        onClick: () => handlePageChange(1),
                        disabled: currentPage === 1,
                        "data-cy": sel("entities.list.pagination.first", { slug }),
                        children: [
                          /* @__PURE__ */ jsx(ChevronsLeft, { className: "h-4 w-4" }),
                          /* @__PURE__ */ jsx("span", { className: "sr-only", children: "First page" })
                        ]
                      }
                    ),
                    /* @__PURE__ */ jsxs(
                      Button,
                      {
                        variant: "outline",
                        size: "icon",
                        className: "h-8 w-8",
                        onClick: () => handlePageChange(currentPage - 1),
                        disabled: currentPage === 1,
                        "data-cy": sel("entities.list.pagination.prev", { slug }),
                        children: [
                          /* @__PURE__ */ jsx(ChevronLeft, { className: "h-4 w-4" }),
                          /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Previous page" })
                        ]
                      }
                    ),
                    /* @__PURE__ */ jsxs(
                      Button,
                      {
                        variant: "outline",
                        size: "icon",
                        className: "h-8 w-8",
                        onClick: () => handlePageChange(currentPage + 1),
                        disabled: currentPage === totalPages,
                        "data-cy": sel("entities.list.pagination.next", { slug }),
                        children: [
                          /* @__PURE__ */ jsx(ChevronRight, { className: "h-4 w-4" }),
                          /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Next page" })
                        ]
                      }
                    ),
                    /* @__PURE__ */ jsxs(
                      Button,
                      {
                        variant: "outline",
                        size: "icon",
                        className: "h-8 w-8",
                        onClick: () => handlePageChange(totalPages),
                        disabled: currentPage === totalPages,
                        "data-cy": sel("entities.list.pagination.last", { slug }),
                        children: [
                          /* @__PURE__ */ jsx(ChevronsRight, { className: "h-4 w-4" }),
                          /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Last page" })
                        ]
                      }
                    )
                  ] })
                ] })
              ]
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          AlertDialog,
          {
            open: confirmDialog.open,
            onOpenChange: (open) => !open && setConfirmDialog({ open: false, item: null, action: null }),
            children: /* @__PURE__ */ jsxs(AlertDialogContent, { "data-cy": sel("entities.list.confirm.dialog", { slug }), children: [
              /* @__PURE__ */ jsxs(AlertDialogHeader, { children: [
                /* @__PURE__ */ jsx(AlertDialogTitle, { children: getConfirmationTitle() }),
                /* @__PURE__ */ jsx(AlertDialogDescription, { children: getConfirmationDescription() })
              ] }),
              /* @__PURE__ */ jsxs(AlertDialogFooter, { children: [
                /* @__PURE__ */ jsx(AlertDialogCancel, { "data-cy": sel("entities.list.confirm.cancel", { slug }), children: "Cancel" }),
                /* @__PURE__ */ jsx(
                  AlertDialogAction,
                  {
                    onClick: confirmAction,
                    disabled: isDeleting,
                    className: cn(
                      ((_e = confirmDialog.action) == null ? void 0 : _e.variant) === "destructive" && "bg-destructive text-destructive-foreground hover:bg-destructive/90"
                    ),
                    "data-cy": sel("entities.list.confirm.action", { slug }),
                    children: isDeleting ? /* @__PURE__ */ jsxs(Fragment, { children: [
                      /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }),
                      "Deleting..."
                    ] }) : ((_f = confirmDialog.action) == null ? void 0 : _f.label) || "Confirm"
                  }
                )
              ] })
            ] })
          }
        )
      ]
    }
  );
}
export {
  EntityTable
};
