"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { usePathname } from "next/navigation";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { extractCustomFieldEntries } from "@open-mercato/shared/lib/crud/custom-fields-client";
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 {
  buildOrganizationTreeOptions
} from "@open-mercato/core/modules/directory/lib/tree";
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 { deleteCrud, updateCrud } from "@open-mercato/ui/backend/utils/crud";
import { collectCustomFieldValues } from "@open-mercato/ui/backend/utils/customFieldValues";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
import { ErrorMessage, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
import { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from "@open-mercato/ui/backend/injection/recordContext";
const TREE_STEP = 16;
const TREE_PADDING = 12;
function EditOrganizationPage({ params }) {
  const orgId = params?.id;
  const t = useT();
  const pathname = usePathname();
  const [initialValues, setInitialValues] = React.useState(null);
  const [pathLabel, setPathLabel] = React.useState("");
  const [tenantId, setTenantId] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  const [parentTree, setParentTree] = React.useState([]);
  const [childSummary, setChildSummary] = React.useState([]);
  const [originalChildIds, setOriginalChildIds] = React.useState([]);
  const [actorIsSuperAdmin, setActorIsSuperAdmin] = React.useState(false);
  const skipTenantEffectRef = React.useRef(true);
  React.useEffect(() => {
    let cancelled = false;
    async function loadActor() {
      try {
        const { ok, result } = await apiCall("/api/auth/roles?page=1&pageSize=1");
        if (!cancelled && ok) setActorIsSuperAdmin(Boolean(result?.isSuperAdmin));
      } catch {
        if (!cancelled) setActorIsSuperAdmin(false);
      }
    }
    loadActor();
    return () => {
      cancelled = true;
    };
  }, []);
  const markSelectable = React.useCallback((nodes, excluded) => nodes.map((node) => ({
    ...node,
    selectable: !excluded.has(node.id),
    children: Array.isArray(node.children) ? markSelectable(node.children, excluded) : []
  })), []);
  const loadParentTree = React.useCallback(async (targetTenantId, excludedIds) => {
    const treeParams = new URLSearchParams({ view: "tree", includeInactive: "true" });
    if (targetTenantId) treeParams.set("tenantId", targetTenantId);
    if (orgId) treeParams.set("ids", orgId);
    try {
      const { ok, result } = await apiCall(`/api/directory/organizations?${treeParams.toString()}`);
      if (!ok) {
        setParentTree([]);
        return [];
      }
      const baseTree = Array.isArray(result?.items) ? result.items ?? [] : [];
      const excludedSet = new Set(excludedIds);
      if (orgId) excludedSet.add(orgId);
      setParentTree(markSelectable(baseTree, excludedSet));
      return baseTree;
    } catch {
      setParentTree([]);
      return [];
    }
  }, [markSelectable, orgId]);
  React.useEffect(() => {
    if (!orgId) return;
    const currentOrgId = orgId;
    let cancelled = false;
    async function load() {
      setLoading(true);
      setError(null);
      setIsNotFound(false);
      try {
        const { ok, status, result } = await apiCall(
          `/api/directory/organizations?view=manage&ids=${currentOrgId}&status=all&includeInactive=true&page=1&pageSize=1`
        );
        if (!ok) {
          if (status === 404) {
            if (!cancelled) setIsNotFound(true);
            return;
          }
          throw new Error(t("directory.organizations.form.errors.load", "Failed to load organization"));
        }
        const record = Array.isArray(result?.items) ? result.items?.[0] : void 0;
        if (!record) {
          if (!cancelled) setIsNotFound(true);
          return;
        }
        const resolvedTenantId = record.tenantId || null;
        setTenantId(resolvedTenantId);
        const baseTree = await loadParentTree(resolvedTenantId, record.descendantIds ?? []);
        const fullTree = buildOrganizationTreeOptions(baseTree);
        const nodeMap = new Map(fullTree.map((opt) => [opt.value, opt]));
        const childrenDetails = record.childIds.map((id) => nodeMap.get(id)).filter((node) => !!node);
        setChildSummary(childrenDetails);
        setOriginalChildIds(Array.isArray(record.childIds) ? record.childIds : []);
        const customValues = extractCustomFieldEntries(record);
        setInitialValues({
          id: record.id,
          name: record.name,
          slug: record.slug ?? "",
          parentId: record.parentId || "",
          isActive: record.isActive,
          tenantId: resolvedTenantId,
          updatedAt: typeof record.updatedAt === "string" ? record.updatedAt : typeof record.updated_at === "string" ? record.updated_at : null,
          ...customValues
        });
        setPathLabel(record.pathLabel);
      } catch (err) {
        if (!cancelled) {
          const fallback = t("directory.organizations.form.errors.load", "Failed to load organization");
          const message = err instanceof Error && err.message ? err.message : fallback;
          setError(message);
        }
      } finally {
        if (!cancelled) {
          skipTenantEffectRef.current = false;
          setLoading(false);
        }
      }
    }
    load();
    return () => {
      cancelled = true;
    };
  }, [loadParentTree, orgId, t]);
  React.useEffect(() => {
    if (!actorIsSuperAdmin) return;
    if (skipTenantEffectRef.current) {
      skipTenantEffectRef.current = false;
      return;
    }
    if (!orgId) return;
    if (!tenantId) {
      setParentTree([]);
      setChildSummary([]);
      setOriginalChildIds([]);
      return;
    }
    void loadParentTree(tenantId, []);
    setChildSummary([]);
    setOriginalChildIds([]);
  }, [actorIsSuperAdmin, loadParentTree, orgId, tenantId]);
  const fields = React.useMemo(() => [
    ...actorIsSuperAdmin ? [
      {
        id: "tenantId",
        label: t("directory.organizations.form.field.tenant", "Tenant"),
        type: "custom",
        component: ({ value, setValue }) => /* @__PURE__ */ jsx(
          TenantSelect,
          {
            id: "tenantId",
            value: typeof value === "string" ? value : tenantId,
            onChange: (next) => {
              const normalized = next ?? null;
              setTenantId(normalized);
              setValue(normalized);
            },
            includeEmptyOption: false,
            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).")
    },
    {
      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 ?? ""),
          nodes: parentTree,
          includeEmptyOption: true,
          emptyOptionLabel: t("directory.organizations.form.rootOption", "\u2014 Root level \u2014"),
          className: "w-full h-9 rounded border px-2 text-sm"
        }
      )
    },
    {
      id: "childrenInfo",
      label: t("directory.organizations.form.field.children", "Children"),
      type: "custom",
      component: () => {
        if (!childSummary.length) {
          return /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("directory.organizations.form.children.empty", "No direct children assigned.") });
        }
        return /* @__PURE__ */ jsx("ul", { className: "space-y-1 text-sm", children: childSummary.map((child) => /* @__PURE__ */ jsx("li", { className: "leading-none", children: /* @__PURE__ */ jsxs("span", { style: { paddingLeft: child.depth > 0 ? TREE_PADDING + (child.depth - 1) * TREE_STEP : 0 }, children: [
          child.depth > 0 ? /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "\u21B3 " }) : null,
          child.name
        ] }) }, child.value)) });
      }
    },
    { id: "isActive", label: t("directory.organizations.form.field.isActive", "Active"), type: "checkbox" }
  ], [actorIsSuperAdmin, childSummary, parentTree, t, tenantId]);
  const detailFields = React.useMemo(() => actorIsSuperAdmin ? ["tenantId", "name", "slug", "parentId", "childrenInfo", "isActive"] : ["name", "slug", "parentId", "childrenInfo", "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]);
  useSetCurrentRecordInjectionContext(
    buildRecordInjectionContext({
      resourceKind: "directory.organization",
      resourceId: orgId || null,
      updatedAt: typeof initialValues?.updatedAt === "string" ? initialValues.updatedAt : null,
      data: initialValues,
      path: pathname
    })
  );
  if (!orgId) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx("div", { className: "rounded border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive", children: t("directory.organizations.form.errors.missingId", "Organization identifier is missing.") }) }) });
  }
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("directory.organizations.form.errors.notFound", "Organization not found"),
        backHref: "/backend/directory/organizations",
        backLabel: t("directory.organizations.form.actions.backToList", "Back to organizations")
      }
    ) }) });
  }
  if (error && !loading && !initialValues) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(ErrorMessage, { label: error }) }) });
  }
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
    CrudForm,
    {
      title: t("directory.organizations.form.title.edit", "Edit Organization"),
      backHref: "/backend/directory/organizations",
      versionHistory: { resourceKind: "directory.organization", resourceId: orgId ? String(orgId) : "" },
      fields,
      groups,
      entityId: E.directory.organization,
      initialValues: initialValues ?? { id: orgId, tenantId: tenantId ?? null, name: "", slug: "", parentId: "", isActive: true, childIds: [] },
      optimisticLockUpdatedAt: typeof initialValues?.updatedAt === "string" ? initialValues.updatedAt : null,
      isLoading: loading,
      loadingMessage: t("directory.organizations.form.loading", "Loading organization..."),
      submitLabel: t("directory.organizations.form.action.save", "Save"),
      cancelHref: "/backend/directory/organizations",
      successRedirect: `/backend/directory/organizations?flash=${encodeURIComponent(t("directory.organizations.flash.updated", "Organization updated"))}&type=success`,
      extraActions: pathLabel ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t("directory.organizations.form.pathLabel", { path: pathLabel }) }) : null,
      onSubmit: async (values) => {
        await submitUpdateOrganization({
          values,
          orgId: orgId ?? "",
          tenantId,
          originalChildIds,
          messages: {
            orgIdRequired: t("directory.organizations.errors.orgIdRequired", "Organization identifier is required")
          }
        });
      },
      onDelete: async () => {
        await deleteCrud("directory/organizations", orgId ?? "", {
          errorMessage: t("directory.organizations.errors.deleteFailed", "Failed to delete organization")
        });
      },
      deleteRedirect: `/backend/directory/organizations?flash=${encodeURIComponent(t("directory.organizations.flash.deleted", "Organization deleted"))}&type=success`
    }
  ) }) });
}
const defaultUpdateOrganizationRequest = async (payload) => {
  await updateCrud("directory/organizations", payload);
};
async function submitUpdateOrganization(options) {
  const {
    values,
    orgId,
    tenantId,
    originalChildIds,
    updateOrganization = defaultUpdateOrganizationRequest,
    messages
  } = options;
  const payloadId = typeof values.id === "string" && values.id.length ? values.id : orgId;
  if (!payloadId) {
    const message = messages?.orgIdRequired ?? "Organization identifier is required";
    throw createCrudFormError(message, { id: message });
  }
  const customFields = collectCustomFieldValues(values);
  const submittedTenantId = typeof values.tenantId === "string" && values.tenantId.trim().length ? values.tenantId.trim() : tenantId;
  const payload = {
    id: payloadId,
    name: typeof values.name === "string" ? values.name : "",
    isActive: values.isActive !== false,
    parentId: typeof values.parentId === "string" && values.parentId.length ? values.parentId : null,
    childIds: originalChildIds
  };
  if (typeof values.slug === "string") {
    const trimmedSlug = values.slug.trim();
    payload.slug = trimmedSlug.length ? trimmedSlug : null;
  }
  if (submittedTenantId !== void 0 && submittedTenantId !== null) {
    payload.tenantId = submittedTenantId;
  }
  if (Object.keys(customFields).length > 0) {
    payload.customFields = customFields;
  }
  await updateOrganization(payload);
}
export {
  EditOrganizationPage as default,
  submitUpdateOrganization
};
//# sourceMappingURL=page.js.map
