"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect, useCallback, useMemo, useRef } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Plus, Loader2, BarChart3, Pencil, Trash2 } from "lucide-react";
import { EntityTable } from "../../entities/EntityTable.js";
import { EntityBulkActions } from "../../entities/EntityBulkActions.js";
import { Alert, AlertDescription } from "../../ui/alert.js";
import { Button } from "../../ui/button.js";
import { SkeletonEntityList } from "../../ui/skeleton-list.js";
import { SearchInput } from "../../shared/SearchInput.js";
import { MultiSelectFilter } from "../../shared/MultiSelectFilter.js";
import { PatternDeleteDialog } from "../PatternDeleteDialog.js";
import { useEntityConfig } from "../../../hooks/useEntityConfig.js";
import { useUrlFilters } from "../../../hooks/useUrlFilters.js";
import { listEntityData, deleteEntityData } from "../../../lib/api/entities.js";
import { useTeam } from "../../../hooks/useTeam.js";
import { usePermission } from "../../../lib/permissions/hooks.js";
import { sel } from "../../../lib/test/index.js";
import { toast } from "sonner";
function PatternsListPage() {
  var _a, _b;
  const entityType = "patterns";
  const router = useRouter();
  const { config: entityConfig, isLoading, error: configError, isOverride } = useEntityConfig(entityType);
  const { teamId } = useTeam();
  const canCreate = usePermission(`${entityType}.create`);
  const filterSchema = useMemo(() => {
    var _a2;
    const schema = {
      search: { type: "search", urlParam: "search" }
    };
    (_a2 = entityConfig == null ? void 0 : entityConfig.ui.dashboard.filters) == null ? void 0 : _a2.forEach((filterConfig) => {
      if (filterConfig.type === "multiSelect" || filterConfig.type === "singleSelect") {
        schema[filterConfig.field] = {
          type: filterConfig.type,
          urlParam: filterConfig.urlParam || filterConfig.field
        };
      }
    });
    return schema;
  }, [entityConfig == null ? void 0 : entityConfig.ui.dashboard.filters]);
  const { filters, setFilter } = useUrlFilters(filterSchema);
  const [data, setData] = useState([]);
  const [isInitialLoad, setIsInitialLoad] = useState(true);
  const [isSearching, setIsSearching] = useState(false);
  const [dataError, setDataError] = useState(null);
  const [selectedIds, setSelectedIds] = useState(/* @__PURE__ */ new Set());
  const [deleteTarget, setDeleteTarget] = useState(null);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const buildApiFilters = useCallback(() => {
    var _a2;
    const apiFilters = {};
    if (filters.search && typeof filters.search === "string" && filters.search.trim()) {
      apiFilters.search = filters.search;
    }
    (_a2 = entityConfig == null ? void 0 : entityConfig.ui.dashboard.filters) == null ? void 0 : _a2.forEach((filterConfig) => {
      const value = filters[filterConfig.field];
      if (Array.isArray(value) && value.length > 0) {
        apiFilters[filterConfig.field] = value.join(",");
      } else if (typeof value === "string" && value) {
        apiFilters[filterConfig.field] = value;
      }
    });
    return apiFilters;
  }, [filters, entityConfig == null ? void 0 : entityConfig.ui.dashboard.filters]);
  const loadData = useCallback(async (isInitial = false) => {
    if (!entityConfig) return;
    if (!entityConfig.enabled) {
      setDataError(`Entity "${entityType}" is disabled`);
      return;
    }
    try {
      if (isInitial) {
        setIsInitialLoad(true);
      } else {
        setIsSearching(true);
      }
      setDataError(null);
      const apiFilters = buildApiFilters();
      const result = await listEntityData(entityType, {
        limit: 50,
        includeMeta: true,
        ...Object.keys(apiFilters).length > 0 && { filters: apiFilters }
      });
      setData(result.data);
      setDataError(null);
    } catch (err) {
      console.error(`[PatternsListPage] Error loading data:`, err);
      setDataError(`Error loading data: ${err instanceof Error ? err.message : "Unknown error"}`);
      setData([]);
    } finally {
      setIsInitialLoad(false);
      setIsSearching(false);
    }
  }, [entityConfig, entityType, buildApiFilters]);
  const filtersKey = JSON.stringify(filters);
  const prevFiltersKeyRef = useRef("");
  const hasLoadedRef = useRef(false);
  const schemaKeysForSync = useMemo(
    () => Object.keys(filterSchema).sort().join(","),
    [filterSchema]
  );
  const prevSchemaKeysRef = useRef(schemaKeysForSync);
  const filtersMatchUrl = useMemo(() => {
    if (typeof window === "undefined") return true;
    if (schemaKeysForSync !== prevSchemaKeysRef.current) {
      prevSchemaKeysRef.current = schemaKeysForSync;
      return false;
    }
    const urlParams = new URLSearchParams(window.location.search);
    for (const filterConfig of (entityConfig == null ? void 0 : entityConfig.ui.dashboard.filters) || []) {
      const urlValue = urlParams.get(filterConfig.field);
      const filterValue = filters[filterConfig.field];
      if (urlValue && (!filterValue || Array.isArray(filterValue) && filterValue.length === 0)) {
        return false;
      }
    }
    return true;
  }, [filters, entityConfig == null ? void 0 : entityConfig.ui.dashboard.filters, schemaKeysForSync]);
  useEffect(() => {
    if (!(entityConfig == null ? void 0 : entityConfig.slug)) return;
    if (!filtersMatchUrl) return;
    const isInitial = !hasLoadedRef.current;
    const filtersChanged = prevFiltersKeyRef.current !== filtersKey;
    if (isInitial || filtersChanged) {
      prevFiltersKeyRef.current = filtersKey;
      hasLoadedRef.current = true;
      loadData(isInitial);
    }
  }, [entityConfig == null ? void 0 : entityConfig.slug, filtersKey, filtersMatchUrl, loadData]);
  const handleSearch = useCallback((query) => {
    setFilter("search", query);
  }, [setFilter]);
  const handleDeleteClick = useCallback((item) => {
    setDeleteTarget(item);
    setIsDeleteDialogOpen(true);
  }, []);
  const handleConfirmDelete = useCallback(async () => {
    if (!deleteTarget) return;
    setIsDeleting(true);
    try {
      await deleteEntityData(entityType, deleteTarget.id);
      toast.success(`Pattern deleted successfully`);
      setSelectedIds((prev) => {
        const newSet = new Set(prev);
        newSet.delete(deleteTarget.id);
        return newSet;
      });
      await loadData(false);
    } catch (err) {
      console.error(`[PatternsListPage] Error deleting pattern:`, err);
      toast.error(`Error deleting: ${err instanceof Error ? err.message : "Unknown error"}`);
    } finally {
      setIsDeleting(false);
      setIsDeleteDialogOpen(false);
      setDeleteTarget(null);
    }
  }, [deleteTarget, entityType, loadData]);
  const handleBulkDelete = useCallback(async (ids) => {
    try {
      await Promise.all(ids.map((id) => deleteEntityData(entityType, id)));
      toast.success(`${ids.length} pattern${ids.length === 1 ? "" : "s"} deleted successfully`);
      await loadData(false);
    } catch (err) {
      console.error(`[PatternsListPage] Error bulk deleting patterns:`, err);
      toast.error(`Error deleting: ${err instanceof Error ? err.message : "Unknown error"}`);
      throw err;
    }
  }, [entityType, loadData]);
  const handleSelectAll = useCallback(() => {
    const allIds = new Set(data.map((item) => String(item.id)));
    setSelectedIds(allIds);
  }, [data]);
  const handleClearSelection = useCallback(() => {
    setSelectedIds(/* @__PURE__ */ new Set());
  }, []);
  const getItemName = useCallback((item) => {
    return String(item.name || item.title || item.id);
  }, []);
  const quickActions = useMemo(
    () => [
      {
        id: "view-usages",
        label: "View Usages",
        icon: /* @__PURE__ */ jsx(BarChart3, { className: "h-4 w-4" }),
        onClick: (item) => {
          router.push(`/dashboard/patterns/${item.id}/reports`);
        },
        dataCySuffix: "usages"
      }
    ],
    [router]
  );
  const dropdownActions = useMemo(
    () => [
      {
        id: "edit",
        label: "Edit",
        icon: /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4" }),
        onClick: (item) => router.push(`/dashboard/patterns/${item.id}/edit`),
        dataCySuffix: "edit"
      },
      {
        id: "delete",
        label: "Delete",
        icon: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" }),
        onClick: handleDeleteClick,
        variant: "destructive",
        separator: true,
        dataCySuffix: "delete"
      }
    ],
    [router, handleDeleteClick]
  );
  if (isLoading) {
    return /* @__PURE__ */ jsx(SkeletonEntityList, {});
  }
  if (configError || !entityConfig) {
    return /* @__PURE__ */ jsx(Alert, { children: /* @__PURE__ */ jsx(AlertDescription, { children: configError || `Could not load configuration for entity "${entityType}".` }) });
  }
  if (dataError) {
    return /* @__PURE__ */ jsx(Alert, { children: /* @__PURE__ */ jsx(AlertDescription, { children: dataError }) });
  }
  const bulkOperationsEnabled = entityConfig.ui.features.bulkOperations;
  const enableSearch = entityConfig.ui.features.searchable;
  const enableFilters = entityConfig.ui.features.filterable && ((_a = entityConfig.ui.dashboard.filters) == null ? void 0 : _a.length);
  const searchValue = typeof filters.search === "string" ? filters.search : "";
  return /* @__PURE__ */ jsx("div", { "data-cy": sel("entities.page.container", { slug: entityConfig.slug }), children: /* @__PURE__ */ jsxs("div", { className: "p-6 space-y-6", "data-cy": sel("entities.list.container", { slug: entityConfig.slug }), children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
        /* @__PURE__ */ jsx("h1", { className: "text-2xl font-bold tracking-tight", "data-cy": sel("entities.header.title", { slug: entityConfig.slug }), children: entityConfig.names.plural }),
        /* @__PURE__ */ jsxs("p", { className: "text-muted-foreground", children: [
          "Manage your ",
          entityConfig.names.plural.toLowerCase()
        ] })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2", children: canCreate && /* @__PURE__ */ jsx(Button, { asChild: true, "data-cy": sel("entities.list.addButton", { slug: entityConfig.slug }), children: /* @__PURE__ */ jsxs(Link, { href: `/dashboard/${entityConfig.slug}/create`, children: [
        /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4 mr-2" }),
        "Add ",
        entityConfig.names.singular
      ] }) }) })
    ] }),
    (enableSearch || enableFilters) && /* @__PURE__ */ jsxs("div", { className: "flex flex-col sm:flex-row gap-3 items-center flex-wrap", children: [
      enableSearch && /* @__PURE__ */ jsx(
        SearchInput,
        {
          placeholder: `Search ${entityConfig.names.plural.toLowerCase()}...`,
          value: searchValue,
          onChange: (e) => handleSearch(e.target.value),
          containerClassName: "flex-1 max-w-md",
          "data-cy": sel("entities.list.search.container", { slug: entityConfig.slug })
        }
      ),
      enableFilters && ((_b = entityConfig.ui.dashboard.filters) == null ? void 0 : _b.map((filterConfig) => {
        const field = entityConfig.fields.find((f) => f.name === filterConfig.field);
        if (!(field == null ? void 0 : field.options)) return null;
        const filterValues = filters[filterConfig.field];
        const values = Array.isArray(filterValues) ? filterValues : [];
        return /* @__PURE__ */ jsx(
          MultiSelectFilter,
          {
            label: filterConfig.label || field.display.label,
            options: field.options.map((opt) => ({
              value: String(opt.value),
              label: opt.label
            })),
            values,
            onChange: (newValues) => setFilter(filterConfig.field, newValues),
            "data-cy": sel("entities.list.filters.trigger", { slug: entityConfig.slug, field: filterConfig.field })
          },
          filterConfig.field
        );
      })),
      isSearching && /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin text-muted-foreground" })
    ] }),
    /* @__PURE__ */ jsx(
      EntityTable,
      {
        entityConfig,
        data,
        loading: isInitialLoad,
        selectable: bulkOperationsEnabled,
        selectedIds,
        onSelectionChange: setSelectedIds,
        enableSearch: false,
        searchQuery: searchValue,
        onSearch: handleSearch,
        getItemName,
        teamId,
        useDefaultActions: false,
        quickActions,
        dropdownActions,
        showHeader: false,
        pagination: {
          pageSize: 10,
          showPageSizeSelector: true,
          pageSizeOptions: [10, 20, 50, 100]
        }
      }
    ),
    bulkOperationsEnabled && /* @__PURE__ */ jsx(
      EntityBulkActions,
      {
        entitySlug: entityConfig.slug,
        selectedIds,
        onClearSelection: handleClearSelection,
        config: {
          enableSelectAll: true,
          totalItems: data.length,
          onSelectAll: handleSelectAll,
          enableDelete: true,
          onDelete: handleBulkDelete,
          itemLabel: entityConfig.names.singular,
          itemLabelPlural: entityConfig.names.plural
        }
      }
    ),
    deleteTarget && /* @__PURE__ */ jsx(
      PatternDeleteDialog,
      {
        patternId: deleteTarget.id,
        patternTitle: getItemName(deleteTarget),
        onConfirm: handleConfirmDelete,
        isDeleting,
        open: isDeleteDialogOpen,
        onOpenChange: setIsDeleteDialogOpen
      }
    )
  ] }) });
}
export {
  PatternsListPage as default
};
