"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import React, { useState, useMemo, useCallback } from "react";
import Link from "next/link";
import { Card, CardContent } from "../ui/card";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Badge } from "../ui/badge";
import { Checkbox } from "../ui/checkbox";
import { Alert, AlertDescription } from "../ui/alert";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from "../ui/table";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from "../ui/dropdown-menu";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle
} from "../ui/alert-dialog";
import {
  Loader2,
  Plus,
  Search,
  ArrowUpDown,
  ArrowUp,
  ArrowDown,
  Trash2,
  AlertCircle,
  MoreVertical,
  Edit,
  ExternalLink
} from "lucide-react";
import { SkeletonEntityList } from "../ui/skeleton-list";
import { EntityFieldRenderer } from "./EntityFieldRenderer";
import { createTestId, sel } from "../../lib/test";
import { usePermission } from "../../lib/permissions/hooks";
function generateTestIds(entityName) {
  return {
    container: createTestId(entityName, "list"),
    search: createTestId(entityName, "search"),
    table: createTestId(entityName, "table"),
    row: (id) => createTestId(entityName, "row", id),
    actions: (id) => createTestId(entityName, "actions", id),
    bulkSelect: createTestId(entityName, "bulk", "select"),
    addButton: createTestId(entityName, "add", "button")
  };
}
function EntityList({
  entityConfig,
  data,
  isLoading = false,
  error = null,
  onSearch,
  onSort,
  onSelect,
  onBulkDelete,
  onDelete,
  enableBulkOperations = false,
  enableSearch = true,
  enableRowActions = true,
  getPublicUrl,
  currentSort,
  searchQuery = "",
  selectedIds = [],
  pageSize = 10,
  currentPage = 1,
  totalPages = 1,
  onPageChange,
  headerActions,
  className,
  teamId
}) {
  var _a, _b;
  const [localSearchQuery, setLocalSearchQuery] = useState(searchQuery);
  const [isDeleting, setIsDeleting] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [itemToDelete, setItemToDelete] = useState(null);
  const [isRowDeleting, setIsRowDeleting] = useState(false);
  const canCreate = usePermission(`${entityConfig.slug}.create`);
  const canUpdate = usePermission(`${entityConfig.slug}.update`);
  const canDelete = usePermission(`${entityConfig.slug}.delete`);
  const testIds = generateTestIds(entityConfig.slug);
  const listFields = useMemo(() => {
    return entityConfig.fields.filter((field) => field.display.showInList).sort((a, b) => a.display.order - b.display.order);
  }, [entityConfig.fields]);
  const handleSearch = useCallback((query) => {
    setLocalSearchQuery(query);
    onSearch == null ? void 0 : onSearch(query);
  }, [onSearch]);
  const handleSort = useCallback((fieldName) => {
    if (!onSort) return;
    let direction = "asc";
    if ((currentSort == null ? void 0 : currentSort.field) === fieldName && currentSort.direction === "asc") {
      direction = "desc";
    }
    onSort(fieldName, direction);
  }, [onSort, currentSort]);
  const handleRowSelect = useCallback((id, checked) => {
    if (!onSelect) return;
    let newSelectedIds;
    if (checked) {
      newSelectedIds = [...selectedIds, id];
    } else {
      newSelectedIds = selectedIds.filter((selectedId) => selectedId !== id);
    }
    onSelect(newSelectedIds);
  }, [onSelect, selectedIds]);
  const handleSelectAll = useCallback((checked) => {
    if (!onSelect) return;
    if (checked) {
      const allIds = data.map((item) => String(item.id));
      onSelect(allIds);
    } else {
      onSelect([]);
    }
  }, [onSelect, data]);
  const handleBulkDelete = useCallback(async () => {
    if (!onBulkDelete || selectedIds.length === 0) return;
    setIsDeleting(true);
    try {
      await onBulkDelete(selectedIds);
      onSelect == null ? void 0 : onSelect([]);
    } catch (error2) {
      console.error("Bulk delete failed:", error2);
    } finally {
      setIsDeleting(false);
    }
  }, [onBulkDelete, selectedIds, onSelect]);
  const handleRowDeleteClick = useCallback((id, name) => {
    setItemToDelete({ id, name });
    setDeleteDialogOpen(true);
  }, []);
  const handleRowDeleteConfirm = useCallback(async () => {
    if (!onDelete || !itemToDelete) return;
    setIsRowDeleting(true);
    try {
      await onDelete(itemToDelete.id);
      setDeleteDialogOpen(false);
      setItemToDelete(null);
    } catch (error2) {
      console.error("Row delete failed:", error2);
    } finally {
      setIsRowDeleting(false);
    }
  }, [onDelete, itemToDelete]);
  const handleRowDeleteCancel = useCallback(() => {
    setDeleteDialogOpen(false);
    setItemToDelete(null);
  }, []);
  const getSortIcon = (fieldName) => {
    if ((currentSort == null ? void 0 : currentSort.field) !== fieldName) {
      return /* @__PURE__ */ jsx(ArrowUpDown, { className: "ml-2 h-4 w-4" });
    }
    return currentSort.direction === "asc" ? /* @__PURE__ */ jsx(ArrowUp, { className: "ml-2 h-4 w-4" }) : /* @__PURE__ */ jsx(ArrowDown, { className: "ml-2 h-4 w-4" });
  };
  if (isLoading) {
    const columnCount = ((_b = (_a = entityConfig == null ? void 0 : entityConfig.fields) == null ? void 0 : _a.filter((field) => field.display.showInList)) == null ? void 0 : _b.length) || 6;
    const hasSelected = selectedIds.length > 0;
    return /* @__PURE__ */ jsx(
      SkeletonEntityList,
      {
        rowCount: pageSize || 10,
        columnCount,
        showBulkActions: hasSelected
      }
    );
  }
  return /* @__PURE__ */ jsx("div", { className: "min-h-screen bg-gradient-to-b from-background to-muted/20 py-12 px-4 sm:px-6 lg:px-8", children: /* @__PURE__ */ jsxs(
    "div",
    {
      className: `max-w-7xl mx-auto space-y-4 ${className || ""}`,
      "data-testid": testIds.container,
      "data-cy": sel("entities.list.container", { slug: entityConfig.slug }),
      children: [
        /* @__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-testid": testIds.search,
                  "data-cy": sel("entities.table.search", { slug: entityConfig.slug })
                }
              )
            ] }),
            headerActions,
            canCreate && /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsxs(
              Link,
              {
                href: `/dashboard/${entityConfig.slug}/create`,
                "data-testid": testIds.addButton,
                "data-cy": sel("entities.table.addButton", { slug: entityConfig.slug }),
                children: [
                  /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }),
                  "Add ",
                  entityConfig.names.singular
                ]
              }
            ) })
          ] })
        ] }),
        enableBulkOperations && selectedIds.length > 0 && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 p-3 bg-muted rounded-lg", children: [
          /* @__PURE__ */ jsxs(Badge, { variant: "outline", children: [
            selectedIds.length,
            " selected"
          ] }),
          entityConfig.ui.features.bulkOperations && /* @__PURE__ */ jsxs(
            Button,
            {
              variant: "destructive",
              size: "sm",
              onClick: handleBulkDelete,
              disabled: isDeleting,
              children: [
                isDeleting ? /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }) : /* @__PURE__ */ jsx(Trash2, { className: "mr-2 h-4 w-4" }),
                "Delete Selected"
              ]
            }
          )
        ] }),
        error && /* @__PURE__ */ jsxs(Alert, { variant: "destructive", children: [
          /* @__PURE__ */ jsx(AlertCircle, { className: "h-4 w-4" }),
          /* @__PURE__ */ jsx(AlertDescription, { children: error })
        ] }),
        data.length === 0 ? /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "flex flex-col items-center justify-center py-12", children: [
          React.createElement(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: searchQuery ? `No ${entityConfig.names.plural.toLowerCase()} match your search criteria.` : `Get started by creating your first ${entityConfig.names.singular.toLowerCase()}.` }),
          !searchQuery && canCreate && /* @__PURE__ */ jsx(Button, { className: "mt-4", asChild: true, children: /* @__PURE__ */ jsxs(Link, { href: `/dashboard/${entityConfig.slug}/create`, children: [
            /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }),
            "Add ",
            entityConfig.names.singular
          ] }) })
        ] }) }) : /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(Table, { "data-testid": testIds.table, "data-cy": sel("entities.table.element", { slug: entityConfig.slug }), children: [
          /* @__PURE__ */ jsx(TableHeader, { children: /* @__PURE__ */ jsxs(TableRow, { children: [
            enableBulkOperations && /* @__PURE__ */ jsx(TableHead, { className: "w-12", children: /* @__PURE__ */ jsx(
              Checkbox,
              {
                checked: selectedIds.length === data.length && data.length > 0,
                onCheckedChange: handleSelectAll,
                "aria-label": "Select all rows",
                "data-testid": testIds.bulkSelect
              }
            ) }),
            listFields.map((field) => /* @__PURE__ */ jsx(TableHead, { className: "min-w-[100px]", children: field.api.sortable && onSort ? /* @__PURE__ */ jsxs(
              Button,
              {
                variant: "ghost",
                onClick: () => handleSort(field.name),
                className: "-ml-3 h-8 font-medium",
                children: [
                  field.display.label,
                  getSortIcon(field.name)
                ]
              }
            ) : /* @__PURE__ */ jsx("span", { className: "font-medium", children: field.display.label }) }, field.name)),
            enableRowActions && (canUpdate || canDelete) && /* @__PURE__ */ jsx(TableHead, { className: "w-12", children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Actions" }) })
          ] }) }),
          /* @__PURE__ */ jsx(TableBody, { children: data.map((item) => {
            const itemId = String(item.id);
            const isSelected = selectedIds.includes(itemId);
            return /* @__PURE__ */ jsxs(
              TableRow,
              {
                className: isSelected ? "bg-muted/50" : "",
                "data-testid": testIds.row(itemId),
                "data-cy": sel("entities.table.row", { slug: entityConfig.slug, id: itemId }),
                children: [
                  enableBulkOperations && /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsx(
                    Checkbox,
                    {
                      checked: isSelected,
                      onCheckedChange: (checked) => handleRowSelect(itemId, !!checked),
                      "aria-label": `Select row ${itemId}`
                    }
                  ) }),
                  listFields.map((field) => /* @__PURE__ */ jsx(TableCell, { children: field.name === "title" || field.name === "name" ? /* @__PURE__ */ jsx(
                    Link,
                    {
                      href: `/dashboard/${entityConfig.slug}/${itemId}`,
                      className: "font-medium text-primary hover:underline",
                      children: /* @__PURE__ */ jsx(
                        EntityFieldRenderer,
                        {
                          field,
                          value: item[field.name],
                          mode: "list",
                          context: {
                            entityType: entityConfig.slug,
                            formData: item,
                            // Pass the record data so RelationDisplay can access parentId
                            teamId
                            // Pass teamId for relation resolution
                          }
                        }
                      )
                    }
                  ) : /* @__PURE__ */ jsx(
                    EntityFieldRenderer,
                    {
                      field,
                      value: item[field.name],
                      mode: "list",
                      context: {
                        entityType: entityConfig.slug,
                        formData: item,
                        // Pass the record data so RelationDisplay can access parentId
                        teamId
                        // Pass teamId for relation resolution
                      }
                    }
                  ) }, field.name)),
                  enableRowActions && (canUpdate || canDelete) && /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsxs(DropdownMenu, { children: [
                    /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
                      Button,
                      {
                        variant: "ghost",
                        className: "h-8 w-8 p-0",
                        "data-testid": testIds.actions(itemId),
                        "data-cy": sel("entities.table.rowActionsMenu", { slug: entityConfig.slug, id: itemId }),
                        children: [
                          /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Open menu" }),
                          /* @__PURE__ */ jsx(MoreVertical, { className: "h-4 w-4" })
                        ]
                      }
                    ) }),
                    /* @__PURE__ */ jsxs(DropdownMenuContent, { align: "end", children: [
                      canUpdate && /* @__PURE__ */ jsx(DropdownMenuItem, { asChild: true, children: /* @__PURE__ */ jsxs(Link, { href: `/dashboard/${entityConfig.slug}/${itemId}/edit`, children: [
                        /* @__PURE__ */ jsx(Edit, { className: "mr-2 h-4 w-4" }),
                        "Edit"
                      ] }) }),
                      getPublicUrl && getPublicUrl(item) && /* @__PURE__ */ jsx(DropdownMenuItem, { asChild: true, children: /* @__PURE__ */ jsxs(
                        "a",
                        {
                          href: getPublicUrl(item),
                          target: "_blank",
                          rel: "noopener noreferrer",
                          children: [
                            /* @__PURE__ */ jsx(ExternalLink, { className: "mr-2 h-4 w-4" }),
                            "View"
                          ]
                        }
                      ) }),
                      canDelete && onDelete && /* @__PURE__ */ jsxs(Fragment, { children: [
                        /* @__PURE__ */ jsx(DropdownMenuSeparator, {}),
                        /* @__PURE__ */ jsxs(
                          DropdownMenuItem,
                          {
                            className: "text-destructive focus:text-destructive",
                            onClick: () => handleRowDeleteClick(
                              itemId,
                              String(item.title || item.name || itemId)
                            ),
                            children: [
                              /* @__PURE__ */ jsx(Trash2, { className: "mr-2 h-4 w-4" }),
                              "Delete"
                            ]
                          }
                        )
                      ] })
                    ] })
                  ] }) })
                ]
              },
              itemId
            );
          }) })
        ] }) }),
        totalPages > 1 && onPageChange && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
          /* @__PURE__ */ jsxs("div", { className: "text-sm text-muted-foreground", children: [
            "Showing ",
            (currentPage - 1) * pageSize + 1,
            " to ",
            Math.min(currentPage * pageSize, data.length),
            " of ",
            data.length,
            " entries"
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2", children: [
            /* @__PURE__ */ jsx(
              Button,
              {
                variant: "outline",
                size: "sm",
                onClick: () => onPageChange(currentPage - 1),
                disabled: currentPage <= 1,
                children: "Previous"
              }
            ),
            /* @__PURE__ */ jsx("div", { className: "flex items-center space-x-1", children: Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => /* @__PURE__ */ jsx(
              Button,
              {
                variant: page === currentPage ? "default" : "outline",
                size: "sm",
                onClick: () => onPageChange(page),
                className: "w-8 h-8 p-0",
                children: page
              },
              page
            )) }),
            /* @__PURE__ */ jsx(
              Button,
              {
                variant: "outline",
                size: "sm",
                onClick: () => onPageChange(currentPage + 1),
                disabled: currentPage >= totalPages,
                children: "Next"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsx(AlertDialog, { open: deleteDialogOpen, onOpenChange: setDeleteDialogOpen, children: /* @__PURE__ */ jsxs(AlertDialogContent, { children: [
          /* @__PURE__ */ jsxs(AlertDialogHeader, { children: [
            /* @__PURE__ */ jsx(AlertDialogTitle, { children: "Are you sure?" }),
            /* @__PURE__ */ jsxs(AlertDialogDescription, { children: [
              'This will permanently delete "',
              itemToDelete == null ? void 0 : itemToDelete.name,
              '". This action cannot be undone.'
            ] })
          ] }),
          /* @__PURE__ */ jsxs(AlertDialogFooter, { children: [
            /* @__PURE__ */ jsx(AlertDialogCancel, { onClick: handleRowDeleteCancel, disabled: isRowDeleting, children: "Cancel" }),
            /* @__PURE__ */ jsx(
              AlertDialogAction,
              {
                onClick: handleRowDeleteConfirm,
                disabled: isRowDeleting,
                className: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
                children: isRowDeleting ? /* @__PURE__ */ jsxs(Fragment, { children: [
                  /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }),
                  "Deleting..."
                ] }) : "Delete"
              }
            )
          ] })
        ] }) })
      ]
    }
  ) });
}
export {
  EntityList
};
