"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";
const TREE_BASE_INDENT = 18;
const TREE_STEP_INDENT = 14;
function formatTreeLabel(name, depth) {
  if (depth <= 0) return name;
  return `${"\xA0".repeat(Math.max(0, (depth - 1) * 2))}\u21B3 ${name}`;
}
function computeIndent(depth) {
  if (depth <= 0) return 0;
  return TREE_BASE_INDENT + (depth - 1) * TREE_STEP_INDENT;
}
function DirectoryOrganizationsPage() {
  const queryClient = useQueryClient();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const [page, setPage] = React.useState(1);
  const [status, setStatus] = React.useState("all");
  const [search, setSearch] = React.useState("");
  const [canManage, setCanManage] = React.useState(false);
  const scopeVersion = useOrganizationScopeVersion();
  const t = useT();
  React.useEffect(() => {
    let cancelled = false;
    async function load() {
      try {
        const call = await apiCall("/api/auth/feature-check", {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ features: ["directory.organizations.manage"] })
        });
        if (!cancelled) {
          const granted = Array.isArray(call.result?.granted) ? call.result?.granted : [];
          setCanManage(call.result?.ok === true || granted.includes("directory.organizations.manage"));
        }
      } catch {
        if (!cancelled) setCanManage(false);
      }
    }
    load();
    return () => {
      cancelled = true;
    };
  }, []);
  const queryParams = React.useMemo(() => {
    const params = new URLSearchParams();
    params.set("view", "manage");
    params.set("page", String(page));
    params.set("pageSize", "50");
    params.set("status", status);
    if (status !== "active") params.set("includeInactive", "true");
    if (search) params.set("search", search);
    return params.toString();
  }, [page, status, search]);
  const { data, isLoading } = useQuery({
    queryKey: ["directory-organizations", queryParams, scopeVersion],
    queryFn: async () => {
      return readApiResultOrThrow(
        `/api/directory/organizations?${queryParams}`,
        void 0,
        { errorMessage: t("directory.organizations.list.error.load", "Failed to load organizations") }
      );
    }
  });
  const rows = data?.items ?? [];
  const isSuperAdmin = data?.isSuperAdmin ?? false;
  const columns = React.useMemo(() => {
    const base = [
      {
        accessorKey: "name",
        header: t("directory.organizations.list.columns.organization", "Organization"),
        cell: ({ row }) => {
          const depth = row.original.depth ?? 0;
          return /* @__PURE__ */ jsx("div", { className: "flex items-center text-sm font-medium leading-none text-foreground", children: /* @__PURE__ */ jsx(
            "span",
            {
              style: { marginLeft: computeIndent(depth), whiteSpace: "pre" },
              children: formatTreeLabel(row.original.name, depth)
            }
          ) });
        },
        meta: { priority: 1 }
      },
      {
        accessorKey: "pathLabel",
        header: t("directory.organizations.list.columns.path", "Path"),
        meta: { priority: 3 },
        cell: ({ getValue }) => {
          const value = getValue();
          return /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: value });
        }
      },
      {
        accessorKey: "parentName",
        header: t("directory.organizations.list.columns.parent", "Parent"),
        meta: { priority: 4 },
        cell: ({ getValue }) => getValue() || t("directory.organizations.common.none", "\u2014")
      },
      {
        accessorKey: "childrenCount",
        header: t("directory.organizations.list.columns.children", "Children"),
        meta: { priority: 5 }
      },
      {
        accessorKey: "isActive",
        header: t("directory.organizations.list.columns.active", "Active"),
        enableSorting: false,
        meta: { priority: 2 },
        cell: ({ getValue }) => /* @__PURE__ */ jsx(BooleanIcon, { value: Boolean(getValue()) })
      }
    ];
    if (isSuperAdmin) {
      base.splice(1, 0, {
        accessorKey: "tenantName",
        header: t("directory.organizations.list.columns.tenant", "Tenant"),
        meta: { priority: 2 },
        cell: ({ row }) => {
          const value = row.original.tenantName ?? row.original.tenantId;
          return /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: value });
        }
      });
    }
    return base;
  }, [isSuperAdmin, t]);
  const total = data?.total ?? 0;
  const totalPages = data?.totalPages ?? 0;
  const deleteMutationContextId = "directory-organizations-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 (org) => {
    const confirmLabel = t("directory.organizations.list.confirmDelete", 'Archive organization "{{name}}"?', { name: org.name });
    const confirmed = await confirm({
      title: t("directory.organizations.list.actions.delete", "Delete"),
      text: confirmLabel,
      variant: "destructive"
    });
    if (!confirmed) return;
    try {
      await runDeleteMutation({
        operation: () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(org.updatedAt),
          () => apiCallOrThrow(
            `/api/directory/organizations?id=${encodeURIComponent(org.id)}`,
            { method: "DELETE" },
            { errorMessage: t("directory.organizations.list.error.delete", "Failed to delete organization") }
          )
        ),
        context: {
          formId: deleteMutationContextId,
          resourceKind: "directory.organization",
          resourceId: org.id,
          retryLastMutation: retryDeleteMutation
        }
      });
      await queryClient.invalidateQueries({ queryKey: ["directory-organizations"] });
      flash(t("directory.organizations.flash.deleted", "Organization deleted"), "success");
    } catch (err) {
      if (surfaceRecordConflict(err, t)) {
        await queryClient.invalidateQueries({ queryKey: ["directory-organizations"] });
        return;
      }
      const fallback = t("directory.organizations.list.error.delete", "Failed to delete organization");
      const message = err instanceof Error ? err.message : fallback;
      flash(message, "error");
    }
  }, [confirm, deleteMutationContextId, queryClient, retryDeleteMutation, runDeleteMutation, t]);
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      DataTable,
      {
        title: t("directory.organizations.list.title", "Organizations"),
        actions: canManage ? /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsx(Link, { href: "/backend/directory/organizations/create", children: t("directory.organizations.list.actions.create", "Create") }) }) : void 0,
        columns,
        data: rows,
        searchValue: search,
        searchPlaceholder: t("directory.organizations.list.searchPlaceholder", "Search organizations"),
        onSearchChange: (value) => {
          setSearch(value);
          setPage(1);
        },
        filters: [
          {
            id: "status",
            label: t("directory.organizations.list.filters.status", "Status"),
            type: "select",
            options: [
              { value: "all", label: t("directory.organizations.list.filters.all", "All") },
              { value: "active", label: t("directory.organizations.list.filters.active", "Active") },
              { value: "inactive", label: t("directory.organizations.list.filters.inactive", "Inactive") }
            ]
          }
        ],
        filterValues: status === "all" ? {} : { status },
        onFiltersApply: (vals) => {
          const nextStatus = vals.status || "all";
          setStatus(nextStatus);
          setPage(1);
        },
        onFiltersClear: () => {
          setStatus("all");
          setPage(1);
        },
        sortable: false,
        perspective: { tableId: "directory.organizations.list" },
        rowActions: (row) => canManage ? /* @__PURE__ */ jsx(
          RowActions,
          {
            items: [
              { id: "edit", label: t("directory.organizations.list.actions.edit", "Edit"), href: `/backend/directory/organizations/${row.id}/edit` },
              { id: "delete", label: t("directory.organizations.list.actions.delete", "Delete"), destructive: true, onSelect: () => handleDelete(row) }
            ]
          }
        ) : null,
        emptyState: /* @__PURE__ */ jsx(
          ListEmptyState,
          {
            entityName: t("directory.organizations.list.title", "Organizations"),
            createHref: "/backend/directory/organizations/create",
            createLabel: t("directory.organizations.list.actions.create", "Create")
          }
        ),
        pagination: { page, pageSize: 50, total, totalPages, onPageChange: setPage },
        isLoading
      }
    ) }),
    ConfirmDialogElement
  ] });
}
export {
  DirectoryOrganizationsPage as default
};
//# sourceMappingURL=page.js.map
