"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
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 { Button } from "@open-mercato/ui/primitives/button";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { apiCall, 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 { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
function formatDate(value, t) {
  if (!value) return t("api_keys.list.noDate");
  try {
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return t("api_keys.list.noDate");
    return date.toLocaleString();
  } catch {
    return t("api_keys.list.noDate");
  }
}
function ApiKeysListPage() {
  const [rows, setRows] = React.useState([]);
  const [page, setPage] = React.useState(1);
  const [total, setTotal] = React.useState(0);
  const [totalPages, setTotalPages] = React.useState(1);
  const [search, setSearch] = React.useState("");
  const [isLoading, setIsLoading] = React.useState(true);
  const [reloadToken, setReloadToken] = React.useState(0);
  const scopeVersion = useOrganizationScopeVersion();
  const t = useT();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  React.useEffect(() => {
    let cancelled = false;
    async function load() {
      setIsLoading(true);
      try {
        const params = new URLSearchParams();
        params.set("page", String(page));
        params.set("pageSize", "20");
        if (search) params.set("search", search);
        const fallback = { items: [], total: 0, page, totalPages: 1 };
        const call = await apiCall(
          `/api/api_keys/keys?${params.toString()}`,
          void 0,
          { fallback }
        );
        if (!call.ok) {
          const errorPayload = call.result;
          const message = typeof errorPayload?.error === "string" ? errorPayload.error : t("api_keys.list.error.loadFailed");
          flash(message, "error");
          return;
        }
        const payload = call.result ?? fallback;
        if (!cancelled) {
          setRows(Array.isArray(payload.items) ? payload.items : []);
          setTotal(payload.total || 0);
          setTotalPages(payload.totalPages || 1);
        }
      } catch (error) {
        if (!cancelled) {
          const message = error instanceof Error ? error.message : t("api_keys.list.error.loadFailed");
          flash(message, "error");
        }
      } finally {
        if (!cancelled) setIsLoading(false);
      }
    }
    load();
    return () => {
      cancelled = true;
    };
  }, [page, search, reloadToken, scopeVersion, t]);
  const handleDelete = React.useCallback(async (row) => {
    const confirmed = await confirm({
      title: t("api_keys.list.confirmDelete", { name: row.name }),
      variant: "destructive"
    });
    if (!confirmed) return;
    try {
      const call = await withScopedApiRequestHeaders(
        buildOptimisticLockHeader(row.updatedAt),
        () => apiCall(
          `/api/api_keys/keys?id=${encodeURIComponent(row.id)}`,
          { method: "DELETE" },
          { fallback: null }
        )
      );
      if (!call.ok) {
        const errorPayload = call.result;
        const message = typeof errorPayload?.error === "string" ? errorPayload.error : t("api_keys.list.error.deleteFailed");
        flash(message, "error");
        return;
      }
      flash(t("api_keys.list.success.deleted"), "success");
      setReloadToken((token) => token + 1);
    } catch (error) {
      const message = error instanceof Error ? error.message : t("api_keys.list.error.deleteFailed");
      flash(message, "error");
    }
  }, [confirm, t]);
  const columns = React.useMemo(() => [
    { accessorKey: "name", header: t("api_keys.list.columns.name") },
    {
      accessorKey: "keyPrefix",
      header: t("api_keys.list.columns.key"),
      cell: ({ row }) => /* @__PURE__ */ jsxs("code", { className: "text-xs", children: [
        row.original.keyPrefix,
        "\u2026"
      ] })
    },
    {
      accessorKey: "organizationName",
      header: t("api_keys.list.columns.organization"),
      cell: ({ row }) => row.original.organizationName || t("api_keys.list.noDate")
    },
    {
      accessorKey: "roles",
      header: t("api_keys.list.columns.roles"),
      cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-1", children: [
        row.original.roles.length === 0 && /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-xs", children: t("api_keys.list.noRoles") }),
        row.original.roles.map((role) => /* @__PURE__ */ jsx(
          "span",
          {
            className: "inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium",
            children: role.name || role.id
          },
          role.id
        ))
      ] })
    },
    {
      accessorKey: "lastUsedAt",
      header: t("api_keys.list.columns.lastUsed"),
      cell: ({ row }) => formatDate(row.original.lastUsedAt, t)
    },
    {
      accessorKey: "expiresAt",
      header: t("api_keys.list.columns.expires"),
      cell: ({ row }) => formatDate(row.original.expiresAt, t)
    }
  ], [t]);
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      DataTable,
      {
        title: t("api_keys.list.title"),
        actions: /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsx(Link, { href: "/backend/api-keys/create", children: t("api_keys.list.actions.create") }) }),
        columns,
        data: rows,
        searchValue: search,
        onSearchChange: (value) => {
          setSearch(value);
          setPage(1);
        },
        perspective: { tableId: "api_keys.list" },
        rowActions: (row) => /* @__PURE__ */ jsx(RowActions, { items: [
          { id: "delete", label: t("common.delete"), destructive: true, onSelect: () => {
            void handleDelete(row);
          } }
        ] }),
        emptyState: /* @__PURE__ */ jsx(
          ListEmptyState,
          {
            entityName: t("api_keys.list.title"),
            createHref: "/backend/api-keys/create",
            createLabel: t("api_keys.list.actions.create")
          }
        ),
        pagination: { page, pageSize: 20, total, totalPages, onPageChange: setPage },
        isLoading
      }
    ) }),
    ConfirmDialogElement
  ] });
}
export {
  ApiKeysListPage as default
};
//# sourceMappingURL=page.js.map
