"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { DataTable } from "@open-mercato/ui/backend/DataTable";
import { ListEmptyState } from "@open-mercato/ui/backend/filters/ListEmptyState";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { BooleanIcon } from "@open-mercato/ui/backend/ValueIcons";
import { Button } from "@open-mercato/ui/primitives/button";
import { apiCall, apiCallOrThrow, readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
function DirectoryTenantsPage() {
  const queryClient = useQueryClient();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const [sorting, setSorting] = React.useState([{ id: "name", desc: false }]);
  const [page, setPage] = React.useState(1);
  const [search, setSearch] = React.useState("");
  const [filters, setFilters] = React.useState({});
  const [canManage, setCanManage] = React.useState(false);
  const scopeVersion = useOrganizationScopeVersion();
  const t = useT();
  const columns = React.useMemo(() => [
    { accessorKey: "name", header: t("directory.tenants.list.columns.tenant", "Tenant"), meta: { priority: 1 } },
    {
      accessorKey: "isActive",
      header: t("directory.tenants.list.columns.active", "Active"),
      enableSorting: false,
      meta: { priority: 2 },
      cell: ({ getValue }) => /* @__PURE__ */ jsx(BooleanIcon, { value: Boolean(getValue()) })
    },
    {
      accessorKey: "createdAt",
      header: t("directory.tenants.list.columns.created", "Created"),
      meta: { priority: 3 },
      cell: ({ getValue }) => {
        const timestamp = getValue();
        if (!timestamp) return /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "\u2014" });
        const date = new Date(timestamp);
        if (Number.isNaN(date.getTime())) return /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "\u2014" });
        return /* @__PURE__ */ jsx("span", { children: date.toLocaleString() });
      }
    }
  ], [t]);
  React.useEffect(() => {
    let cancelled = false;
    async function loadFeature() {
      try {
        const call = await apiCall("/api/auth/feature-check", {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ features: ["directory.tenants.manage"] })
        });
        if (!cancelled) {
          const granted = Array.isArray(call.result?.granted) ? call.result.granted : [];
          setCanManage(call.result?.ok === true || granted.includes("directory.tenants.manage"));
        }
      } catch {
        if (!cancelled) setCanManage(false);
      }
    }
    loadFeature();
    return () => {
      cancelled = true;
    };
  }, []);
  const queryParams = React.useMemo(() => {
    const params = new URLSearchParams();
    params.set("page", String(page));
    params.set("pageSize", "20");
    if (sorting.length > 0) {
      params.set("sortField", sorting[0]?.id || "name");
      params.set("sortDir", sorting[0]?.desc ? "desc" : "asc");
    }
    if (search) params.set("search", search);
    if (filters.active !== void 0 && filters.active !== "") params.set("isActive", String(filters.active));
    return params.toString();
  }, [page, sorting, search, filters]);
  const { data, isLoading } = useQuery({
    queryKey: ["directory-tenants", queryParams, scopeVersion],
    queryFn: async () => {
      return readApiResultOrThrow(
        `/api/directory/tenants?${queryParams}`,
        void 0,
        { errorMessage: t("directory.tenants.list.error.load", "Failed to load tenants") }
      );
    }
  });
  const rows = data?.items ?? [];
  const total = data?.total ?? 0;
  const totalPages = data?.totalPages ?? 0;
  const deleteMutationContextId = "directory-tenants-list:single-delete";
  const { runMutation: runDeleteMutation, retryLastMutation: retryDeleteMutation } = useGuardedMutation({
    contextId: deleteMutationContextId,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const handleDelete = React.useCallback(async (tenant) => {
    const confirmMessage = t("directory.tenants.list.confirmDelete", 'Delete tenant "{{name}}"? This will archive it.').replace("{{name}}", tenant.name);
    const confirmed = await confirm({
      title: t("common.delete", "Delete"),
      text: confirmMessage,
      variant: "destructive"
    });
    if (!confirmed) return;
    try {
      await runDeleteMutation({
        operation: () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(tenant.updatedAt),
          () => apiCallOrThrow(
            `/api/directory/tenants?id=${encodeURIComponent(tenant.id)}`,
            { method: "DELETE" },
            { errorMessage: t("directory.tenants.list.error.delete", "Failed to delete tenant") }
          )
        ),
        context: {
          formId: deleteMutationContextId,
          resourceKind: "directory.tenant",
          resourceId: tenant.id,
          retryLastMutation: retryDeleteMutation
        }
      });
      await queryClient.invalidateQueries({ queryKey: ["directory-tenants"] });
      flash(t("directory.tenants.list.success.delete", "Tenant deleted"), "success");
    } catch (err) {
      if (surfaceRecordConflict(err, t)) {
        await queryClient.invalidateQueries({ queryKey: ["directory-tenants"] });
        return;
      }
      const message = err instanceof Error ? err.message : t("directory.tenants.list.error.delete", "Failed to delete tenant");
      flash(message, "error");
    }
  }, [confirm, deleteMutationContextId, queryClient, retryDeleteMutation, runDeleteMutation, t]);
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      DataTable,
      {
        title: t("directory.tenants.list.title", "Tenants"),
        actions: canManage ? /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsx(Link, { href: "/backend/directory/tenants/create", children: t("directory.tenants.list.actions.create", "Create") }) }) : void 0,
        columns,
        data: rows,
        searchValue: search,
        onSearchChange: (value) => {
          setSearch(value);
          setPage(1);
        },
        filters: [{ id: "active", label: t("directory.tenants.list.filters.status", "Status"), type: "select", options: [
          { value: "true", label: t("directory.tenants.list.filters.active", "Active") },
          { value: "false", label: t("directory.tenants.list.filters.inactive", "Inactive") }
        ] }],
        filterValues: filters,
        onFiltersApply: (vals) => {
          setFilters(vals);
          setPage(1);
        },
        onFiltersClear: () => {
          setFilters({});
          setPage(1);
        },
        sortable: true,
        sorting,
        onSortingChange: (state) => {
          setSorting(state);
          setPage(1);
        },
        perspective: { tableId: "directory.tenants.list" },
        rowActions: (row) => canManage ? /* @__PURE__ */ jsx(
          RowActions,
          {
            items: [
              { id: "edit", label: t("common.edit", "Edit"), href: `/backend/directory/tenants/${row.id}/edit` },
              { id: "delete", label: t("common.delete", "Delete"), destructive: true, onSelect: () => handleDelete(row) }
            ]
          }
        ) : null,
        emptyState: /* @__PURE__ */ jsx(
          ListEmptyState,
          {
            entityName: t("directory.tenants.list.title", "Tenants"),
            createHref: "/backend/directory/tenants/create",
            createLabel: t("directory.tenants.list.actions.create", "Create")
          }
        ),
        pagination: { page, pageSize: 20, total, totalPages, onPageChange: setPage },
        isLoading
      }
    ) }),
    ConfirmDialogElement
  ] });
}
export {
  DirectoryTenantsPage as default
};
//# sourceMappingURL=page.js.map
