"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { E } from "../../../../../../generated/entities.ids.generated.js";
import { OrganizationSelect } from "@open-mercato/core/modules/directory/components/OrganizationSelect";
import { TenantSelect } from "@open-mercato/core/modules/directory/components/TenantSelect";
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 { collectCustomFieldValues } from "@open-mercato/ui/backend/utils/customFieldValues";
import { createCrud } from "@open-mercato/ui/backend/utils/crud";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
function ChildTreeSelect({ nodes, value, onChange }) {
  const t = useT();
  const selected = React.useMemo(() => new Set(value), [value]);
  const handleToggle = React.useCallback((id) => {
    const next = new Set(value);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    onChange(Array.from(next));
  }, [value, onChange]);
  if (!nodes.length) {
    return /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: t("directory.organizations.form.children.empty", "No organizations available to assign.") });
  }
  return /* @__PURE__ */ jsx("div", { className: "rounded border px-3 py-2 max-h-64 overflow-auto space-y-2", children: /* @__PURE__ */ jsx(TreeCheckboxGroup, { nodes, selected, onToggle: handleToggle, level: 0 }) });
}
function TreeCheckboxGroup({ nodes, selected, onToggle, level }) {
  return /* @__PURE__ */ jsx("div", { className: level === 0 ? "space-y-1" : "space-y-1 pl-5", children: nodes.map((node) => /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
    /* @__PURE__ */ jsxs("label", { className: "inline-flex items-start gap-2 text-sm", children: [
      /* @__PURE__ */ jsx(
        "input",
        {
          type: "checkbox",
          className: "size-4 mt-0.5",
          checked: selected.has(node.id),
          onChange: () => onToggle(node.id)
        }
      ),
      /* @__PURE__ */ jsx("span", { children: node.name })
    ] }),
    node.children?.length ? /* @__PURE__ */ jsx(TreeCheckboxGroup, { nodes: node.children, selected, onToggle, level: level + 1 }) : null
  ] }, node.id)) });
}
function CreateOrganizationPage() {
  const [tree, setTree] = React.useState([]);
  const [actorIsSuperAdmin, setActorIsSuperAdmin] = React.useState(false);
  const [selectedTenantId, setSelectedTenantId] = React.useState(null);
  const t = useT();
  const loadTree = React.useCallback(async (tenantId) => {
    const params = new URLSearchParams({ view: "tree", includeInactive: "true" });
    if (tenantId) params.set("tenantId", tenantId);
    try {
      const call = await apiCall(`/api/directory/organizations?${params.toString()}`);
      const items = Array.isArray(call.result?.items) ? call.result.items : [];
      setTree(items);
    } catch {
      setTree([]);
    }
  }, []);
  React.useEffect(() => {
    let cancelled = false;
    async function bootstrap() {
      try {
        const call = await apiCall("/api/auth/roles?page=1&pageSize=1");
        if (!cancelled) setActorIsSuperAdmin(Boolean(call.result?.isSuperAdmin));
      } catch {
        if (!cancelled) setActorIsSuperAdmin(false);
      }
      if (!cancelled) await loadTree(null);
    }
    bootstrap();
    return () => {
      cancelled = true;
    };
  }, [loadTree]);
  React.useEffect(() => {
    if (!actorIsSuperAdmin) return;
    void loadTree(selectedTenantId);
  }, [actorIsSuperAdmin, loadTree, selectedTenantId]);
  const fields = React.useMemo(() => [
    ...actorIsSuperAdmin ? [
      {
        id: "tenantId",
        label: t("directory.organizations.form.field.tenant", "Tenant"),
        type: "custom",
        required: true,
        component: ({ value, setValue }) => /* @__PURE__ */ jsx(
          TenantSelect,
          {
            id: "tenantId",
            value: typeof value === "string" ? value : selectedTenantId,
            onChange: (next) => {
              const normalized = next ?? null;
              setSelectedTenantId(normalized);
              setValue(normalized);
            },
            includeEmptyOption: true,
            emptyOptionLabel: t("directory.organizations.form.tenant.select", "Select tenant"),
            className: "w-full h-9 rounded border px-2 text-sm"
          }
        )
      }
    ] : [],
    { id: "name", label: t("directory.organizations.form.field.name", "Name"), type: "text", required: true },
    {
      id: "slug",
      label: t("directory.organizations.form.field.slug", "Slug"),
      type: "text",
      description: t("directory.organizations.form.field.slug.description", "URL-safe identifier used for the customer portal (lowercase letters, numbers, hyphens, underscores). Generated from the name when left blank.")
    },
    {
      id: "parentId",
      label: t("directory.organizations.form.field.parent", "Parent"),
      type: "custom",
      component: ({ id, value, setValue }) => /* @__PURE__ */ jsx(
        OrganizationSelect,
        {
          id,
          value: value ? String(value) : null,
          onChange: (next) => setValue(next ?? ""),
          tenantId: selectedTenantId,
          fetchOnMount: true,
          includeEmptyOption: true,
          emptyOptionLabel: t("directory.organizations.form.rootOption", "\u2014 Root level \u2014"),
          className: "w-full h-9 rounded border px-2 text-sm"
        }
      )
    },
    {
      id: "childIds",
      label: t("directory.organizations.form.field.children", "Children"),
      type: "custom",
      component: ({ value, setValue }) => /* @__PURE__ */ jsx(
        ChildTreeSelect,
        {
          nodes: tree,
          value: Array.isArray(value) ? value : [],
          onChange: (vals) => setValue(vals)
        }
      )
    },
    { id: "isActive", label: t("directory.organizations.form.field.isActive", "Active"), type: "checkbox" }
  ], [actorIsSuperAdmin, selectedTenantId, t, tree]);
  const detailFields = React.useMemo(() => actorIsSuperAdmin ? ["tenantId", "name", "slug", "parentId", "childIds", "isActive"] : ["name", "slug", "parentId", "childIds", "isActive"], [actorIsSuperAdmin]);
  const groups = React.useMemo(() => [
    { id: "details", title: t("directory.organizations.form.group.details", "Details"), column: 1, fields: detailFields },
    { id: "custom", title: t("directory.organizations.form.group.customFields", "Custom Data"), column: 2, kind: "customFields" }
  ], [detailFields, t]);
  const formTitle = t("directory.nav.organizations.create", "Create Organization");
  const successMessage = encodeURIComponent(t("directory.organizations.flash.created", "Organization created"));
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
    CrudForm,
    {
      title: formTitle,
      backHref: "/backend/directory/organizations",
      fields,
      groups,
      entityId: E.directory.organization,
      initialValues: { tenantId: selectedTenantId ?? null, name: "", slug: "", parentId: "", childIds: [], isActive: true },
      submitLabel: t("directory.organizations.form.action.create", "Create"),
      cancelHref: "/backend/directory/organizations",
      successRedirect: `/backend/directory/organizations?flash=${successMessage}&type=success`,
      onSubmit: async (values) => {
        await submitCreateOrganization({
          values,
          actorIsSuperAdmin,
          selectedTenantId,
          messages: {
            tenantRequired: t("directory.organizations.errors.tenantRequired", "Tenant selection is required for super administrators")
          }
        });
      }
    }
  ) }) });
}
async function defaultCreateOrganizationRequest(payload) {
  await createCrud("directory/organizations", payload);
}
async function submitCreateOrganization(options) {
  const {
    values,
    actorIsSuperAdmin,
    selectedTenantId,
    createOrganization = defaultCreateOrganizationRequest,
    messages
  } = options;
  const customFields = collectCustomFieldValues(values);
  const tenantValue = typeof values.tenantId === "string" && values.tenantId.trim().length ? values.tenantId.trim() : selectedTenantId;
  if (actorIsSuperAdmin && !tenantValue) {
    const message = messages?.tenantRequired ?? "Tenant selection is required for super administrators";
    throw createCrudFormError(message, {
      tenantId: message
    });
  }
  const payload = {
    name: typeof values.name === "string" ? values.name : "",
    isActive: values.isActive !== false,
    parentId: typeof values.parentId === "string" && values.parentId.length ? values.parentId : null,
    childIds: Array.isArray(values.childIds) ? values.childIds.filter((id) => typeof id === "string") : []
  };
  if (typeof values.slug === "string") {
    const trimmedSlug = values.slug.trim();
    if (trimmedSlug.length) payload.slug = trimmedSlug;
  }
  if (tenantValue) payload.tenantId = tenantValue;
  if (Object.keys(customFields).length > 0) payload.customFields = customFields;
  await createOrganization(payload);
}
export {
  CreateOrganizationPage as default,
  submitCreateOrganization
};
//# sourceMappingURL=page.js.map
