"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { createCrud } from "@open-mercato/ui/backend/utils/crud";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
import { OrganizationSelect } from "@open-mercato/core/modules/directory/components/OrganizationSelect";
import { fetchRoleOptions } from "@open-mercato/core/modules/auth/backend/users/roleOptions";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { Button } from "@open-mercato/ui/primitives/button";
import { useRouter } from "next/navigation";
import { useOrganizationScopeDetail, useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
function CreateApiKeyPage() {
  const [createdSecret, setCreatedSecret] = React.useState(null);
  const [actorIsSuperAdmin, setActorIsSuperAdmin] = React.useState(false);
  const [actorResolved, setActorResolved] = React.useState(false);
  const [selectedTenantId, setSelectedTenantId] = React.useState(null);
  const router = useRouter();
  const scopeDetail = useOrganizationScopeDetail();
  const scopeVersion = useOrganizationScopeVersion();
  const t = useT();
  React.useEffect(() => {
    let cancelled = false;
    async function loadInitialScope() {
      try {
        const { ok, result } = await apiCall(
          "/api/directory/organization-switcher"
        );
        if (!ok || cancelled) {
          if (!ok && !cancelled) setActorIsSuperAdmin(false);
          return;
        }
        const rawTenant = typeof result?.tenantId === "string" ? result.tenantId : null;
        const normalizedTenant = rawTenant && rawTenant.trim().length > 0 ? rawTenant.trim() : null;
        setSelectedTenantId(normalizedTenant);
        setActorIsSuperAdmin(Boolean(result?.isSuperAdmin));
      } catch {
        if (!cancelled) setActorIsSuperAdmin(false);
      } finally {
        if (!cancelled) setActorResolved(true);
      }
    }
    loadInitialScope();
    return () => {
      cancelled = true;
    };
  }, []);
  React.useEffect(() => {
    if (scopeVersion === 0) return;
    const rawTenant = scopeDetail.tenantId;
    const normalizedTenant = typeof rawTenant === "string" && rawTenant.trim().length > 0 ? rawTenant.trim() : null;
    setSelectedTenantId((prev) => {
      if ((prev ?? null) === (normalizedTenant ?? null)) return prev;
      return normalizedTenant;
    });
  }, [scopeDetail.tenantId, scopeVersion]);
  const loadRoleOptions = React.useCallback(async (query) => {
    if (!actorResolved) return [];
    if (actorIsSuperAdmin) {
      const tenant = typeof selectedTenantId === "string" && selectedTenantId.trim().length > 0 ? selectedTenantId.trim() : null;
      if (!tenant) return [];
      return fetchRoleOptions(query, { tenantId: tenant });
    }
    return fetchRoleOptions(query);
  }, [actorIsSuperAdmin, actorResolved, selectedTenantId]);
  const fields = React.useMemo(() => [
    { id: "name", label: t("api_keys.form.name"), type: "text", required: true },
    { id: "description", label: t("api_keys.form.description"), type: "textarea", description: t("api_keys.form.descriptionHint") },
    {
      id: "organizationId",
      label: t("api_keys.form.organization"),
      required: false,
      type: "custom",
      component: ({ id, value, setValue }) => /* @__PURE__ */ jsx(
        OrganizationSelect,
        {
          id,
          value: typeof value === "string" ? value : null,
          onChange: (next) => setValue(next ?? null),
          includeEmptyOption: true,
          emptyOptionLabel: t("api_keys.form.organizationPlaceholder"),
          className: "w-full h-9 rounded border px-2 text-sm"
        }
      )
    },
    {
      id: "roles",
      label: t("api_keys.form.roles"),
      type: "tags",
      loadOptions: loadRoleOptions,
      description: t("api_keys.form.rolesHint")
    },
    { id: "expiresAt", label: t("api_keys.form.expiresAt"), type: "date", description: t("api_keys.form.expiresHint") }
  ], [loadRoleOptions, t]);
  const groups = React.useMemo(() => [
    { id: "details", title: t("api_keys.form.details"), column: 1, fields: ["name", "description", "organizationId", "roles", "expiresAt"] }
  ], [t]);
  if (createdSecret) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center", children: /* @__PURE__ */ jsxs("div", { className: "w-full max-w-2xl rounded-xl border bg-card shadow-sm", children: [
      /* @__PURE__ */ jsxs("div", { className: "border-b p-6", children: [
        /* @__PURE__ */ jsx("h1", { className: "text-lg font-semibold leading-7", children: t("api_keys.copy.title") }),
        /* @__PURE__ */ jsx("p", { className: "mt-2 text-sm text-muted-foreground", children: t("api_keys.copy.subtitle") })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-4 p-6", children: [
        /* @__PURE__ */ jsx("div", { className: "rounded-md border bg-muted/50 p-4 font-mono text-sm break-all", children: createdSecret.secret }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between text-xs text-muted-foreground", children: [
          /* @__PURE__ */ jsx("span", { className: "inline-flex items-center rounded-full border px-2 py-1 font-medium", children: t("api_keys.copy.prefix", { prefix: createdSecret.keyPrefix }) }),
          /* @__PURE__ */ jsx("span", { children: t("api_keys.copy.warning") })
        ] }),
        /* @__PURE__ */ jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsx(Button, { onClick: () => router.push("/backend/api-keys"), children: t("common.close") }) })
      ] })
    ] }) }) }) });
  }
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx("div", { className: "space-y-6", children: /* @__PURE__ */ jsx(
    CrudForm,
    {
      title: t("api_keys.form.title"),
      backHref: "/backend/api-keys",
      fields,
      groups,
      initialValues: { name: "", description: null, organizationId: null, roles: [], expiresAt: null },
      submitLabel: t("common.create"),
      cancelHref: "/backend/api-keys",
      onSubmit: async (values) => {
        const payload = {
          name: values.name,
          description: values.description || null,
          organizationId: values.organizationId || null,
          roles: Array.isArray(values.roles) ? values.roles : [],
          expiresAt: values.expiresAt || null
        };
        if (actorIsSuperAdmin) {
          const tenant = typeof selectedTenantId === "string" && selectedTenantId.trim().length > 0 ? selectedTenantId.trim() : null;
          if (!tenant) {
            const message = t("api_keys.errors.tenantRequired");
            throw createCrudFormError(message, { tenantId: message });
          }
          payload.tenantId = tenant;
        }
        const { result } = await createCrud(
          "api_keys/keys",
          payload
        );
        const created = result;
        if (!created || typeof created.secret !== "string") {
          throw createCrudFormError(t("api_keys.form.error.secretMissing"));
        }
        const keyPrefix = typeof created.keyPrefix === "string" ? created.keyPrefix : "";
        setCreatedSecret({ secret: created.secret, keyPrefix });
        flash(t("api_keys.form.success"), "success");
      }
    }
  ) }) }) });
}
export {
  CreateApiKeyPage as default
};
//# sourceMappingURL=page.js.map
