"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { LookupSelect } from "@open-mercato/ui/backend/inputs";
import { Input } from "@open-mercato/ui/primitives/input";
import { EmailInput } from "@open-mercato/ui/primitives/email-input";
import { Button } from "@open-mercato/ui/primitives/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { SwitchField } from "@open-mercato/ui/primitives/switch-field";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { createCrud } from "@open-mercato/ui/backend/utils/crud";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { collectCustomFieldValues } from "@open-mercato/ui/backend/utils/customFieldValues";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { E } from "../../../../generated/entities.ids.generated.js";
import {
  DictionaryEntrySelect
} from "@open-mercato/core/modules/dictionaries/components/DictionaryEntrySelect";
import { Building2, Plus, Store, UserRound } from "lucide-react";
import { useEmailDuplicateCheck } from "@open-mercato/core/modules/customers/backend/hooks/useEmailDuplicateCheck";
import { useCurrencyDictionary } from "@open-mercato/core/modules/customers/components/detail/hooks/useCurrencyDictionary";
import {
  buildCompanyPayload,
  buildPersonPayload,
  createCompanyFormFields,
  createCompanyFormGroups,
  createCompanyFormSchema,
  createPersonFormFields,
  createPersonFormGroups,
  createPersonFormSchema
} from "@open-mercato/core/modules/customers/components/formConfig";
import { useOrganizationScopeDetail } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import {
  formatAddressString
} from "@open-mercato/core/modules/customers/utils/addressFormat";
import { AddressEditor } from "@open-mercato/core/modules/customers/components/AddressEditor";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("sales");
function CustomerQuickCreate({ t, onCreated }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [dialog, setDialog] = React.useState(null);
  const [saving, setSaving] = React.useState(false);
  const [formError, setFormError] = React.useState(null);
  const menuRef = React.useRef(null);
  const { organizationId } = useOrganizationScopeDetail();
  const personSchema = React.useMemo(() => createPersonFormSchema(), []);
  const personFields = React.useMemo(() => createPersonFormFields(t), [t]);
  const personGroups = React.useMemo(() => createPersonFormGroups(t), [t]);
  const companySchema = React.useMemo(() => createCompanyFormSchema(), []);
  const companyFields = React.useMemo(() => createCompanyFormFields(t), [t]);
  const companyGroups = React.useMemo(() => createCompanyFormGroups(t), [t]);
  React.useEffect(() => {
    if (!menuOpen) return;
    const handleClick = (event) => {
      if (menuRef.current && !menuRef.current.contains(event.target)) {
        setMenuOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, [menuOpen]);
  const closeDialog = React.useCallback(() => {
    setDialog(null);
    setFormError(null);
    setSaving(false);
  }, []);
  const handlePersonCreate = React.useCallback(
    async (values) => {
      setSaving(true);
      try {
        const payload = buildPersonPayload(values, organizationId);
        const { result } = await createCrud("customers/people", payload, {
          errorMessage: t("sales.documents.form.customer.quick.error", "Failed to create customer.")
        });
        const id = result && typeof result.entityId === "string" && result.entityId || result && typeof result.id === "string" && result.id || null;
        if (!id) throw new Error("Missing customer id");
        const displayName = typeof values.displayName === "string" && values.displayName.trim().length ? values.displayName.trim() : t("customers.people.form.displayName.placeholder", "New person");
        flash(t("sales.documents.form.customer.quick.personSuccess", "Customer created."), "success");
        onCreated({
          id,
          kind: "person",
          email: typeof values.primaryEmail === "string" ? values.primaryEmail : null,
          label: displayName,
          subtitle: typeof values.primaryEmail === "string" ? values.primaryEmail : null
        });
        closeDialog();
      } catch (err) {
        logger.error("sales.documents.quickCreate.person", { err });
        const message = err instanceof Error && err.message ? err.message : t("sales.documents.form.customer.quick.error", "Failed to create customer.");
        setFormError(message);
        throw err;
      } finally {
        setSaving(false);
      }
    },
    [closeDialog, onCreated, organizationId, t]
  );
  const handleCompanyCreate = React.useCallback(
    async (values) => {
      setSaving(true);
      try {
        const payload = buildCompanyPayload(values, organizationId);
        const { result } = await createCrud("customers/companies", payload, {
          errorMessage: t("sales.documents.form.customer.quick.error", "Failed to create customer.")
        });
        const id = result && typeof result.entityId === "string" && result.entityId || result && typeof result.id === "string" && result.id || null;
        if (!id) throw new Error("Missing customer id");
        const displayName = typeof values.displayName === "string" && values.displayName.trim().length ? values.displayName.trim() : t("customers.companies.form.displayName.placeholder", "New company");
        const email = typeof values.primaryEmail === "string" ? values.primaryEmail : null;
        const domain = typeof values.domain === "string" && values.domain.trim().length ? values.domain.trim() : null;
        flash(t("sales.documents.form.customer.quick.companySuccess", "Customer created."), "success");
        onCreated({
          id,
          kind: "company",
          email,
          label: displayName,
          subtitle: domain || email || null
        });
        closeDialog();
      } catch (err) {
        logger.error("sales.documents.quickCreate.company", { err });
        const message = err instanceof Error && err.message ? err.message : t("sales.documents.form.customer.quick.error", "Failed to create customer.");
        setFormError(message);
        throw err;
      } finally {
        setSaving(false);
      }
    },
    [closeDialog, onCreated, organizationId, t]
  );
  const renderMenu = () => /* @__PURE__ */ jsxs("div", { className: "absolute right-0 z-dropdown mt-2 w-48 rounded border bg-popover p-1 shadow-lg", children: [
    /* @__PURE__ */ jsxs(
      "button",
      {
        type: "button",
        className: "flex w-full items-center gap-2 rounded px-2 py-2 text-sm hover:bg-muted",
        onClick: () => {
          setDialog("person");
          setMenuOpen(false);
          setFormError(null);
        },
        children: [
          /* @__PURE__ */ jsx(UserRound, { className: "h-4 w-4 text-muted-foreground" }),
          t("sales.documents.form.customer.addPerson", "Create person")
        ]
      }
    ),
    /* @__PURE__ */ jsxs(
      "button",
      {
        type: "button",
        className: "flex w-full items-center gap-2 rounded px-2 py-2 text-sm hover:bg-muted",
        onClick: () => {
          setDialog("company");
          setMenuOpen(false);
          setFormError(null);
        },
        children: [
          /* @__PURE__ */ jsx(Building2, { className: "h-4 w-4 text-muted-foreground" }),
          t("sales.documents.form.customer.addCompany", "Create company")
        ]
      }
    )
  ] });
  return /* @__PURE__ */ jsxs("div", { className: "relative", ref: menuRef, children: [
    /* @__PURE__ */ jsxs(
      Button,
      {
        type: "button",
        size: "sm",
        variant: "outline",
        className: "gap-2",
        onClick: () => setMenuOpen((open) => !open),
        "aria-expanded": menuOpen,
        children: [
          /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4" }),
          t("sales.documents.form.customer.create", "Create customer")
        ]
      }
    ),
    menuOpen ? renderMenu() : null,
    /* @__PURE__ */ jsx(Dialog, { open: dialog === "person", onOpenChange: (open) => open ? setDialog("person") : closeDialog(), children: /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-5xl max-h-[90vh] overflow-y-auto", children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: t("sales.documents.form.customer.addPerson", "Create person") }),
        /* @__PURE__ */ jsx(DialogDescription, { children: t("sales.documents.form.customer.quick.dialogDescription", "Add a person without leaving this form.") })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        formError ? /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: formError }) : null,
        /* @__PURE__ */ jsx(
          "div",
          {
            onSubmit: (event) => {
              event.stopPropagation();
              if (typeof event.nativeEvent?.stopImmediatePropagation === "function") {
                event.nativeEvent.stopImmediatePropagation();
              }
            },
            children: /* @__PURE__ */ jsx(
              CrudForm,
              {
                embedded: true,
                fields: personFields,
                groups: personGroups,
                schema: personSchema,
                initialValues: { addresses: [] },
                submitLabel: t("common.save", "Save"),
                cancelHref: void 0,
                onSubmit: (values) => handlePersonCreate(values),
                entityIds: [E.customers.customer_entity, E.customers.customer_person_profile]
              }
            )
          }
        )
      ] })
    ] }) }),
    /* @__PURE__ */ jsx(Dialog, { open: dialog === "company", onOpenChange: (open) => open ? setDialog("company") : closeDialog(), children: /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-5xl max-h-[90vh] overflow-y-auto", children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: t("sales.documents.form.customer.addCompany", "Create company") }),
        /* @__PURE__ */ jsx(DialogDescription, { children: t("sales.documents.form.customer.quick.dialogDescription", "Add a company without leaving this form.") })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        formError ? /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: formError }) : null,
        /* @__PURE__ */ jsx(
          "div",
          {
            onSubmit: (event) => {
              event.stopPropagation();
              if (typeof event.nativeEvent?.stopImmediatePropagation === "function") {
                event.nativeEvent.stopImmediatePropagation();
              }
            },
            children: /* @__PURE__ */ jsx(
              CrudForm,
              {
                embedded: true,
                fields: companyFields,
                groups: companyGroups,
                schema: companySchema,
                initialValues: { addresses: [] },
                submitLabel: t("common.save", "Save"),
                cancelHref: void 0,
                onSubmit: (values) => handleCompanyCreate(values),
                entityIds: [E.customers.customer_entity, E.customers.customer_company_profile]
              }
            )
          }
        )
      ] })
    ] }) })
  ] });
}
function parseCustomerOptions(items, kind) {
  const parsed = [];
  for (const item of items) {
    if (typeof item !== "object" || item === null) continue;
    const record = item;
    const id = typeof record.id === "string" ? record.id : null;
    if (!id) continue;
    const displayName = typeof record.display_name === "string" ? record.display_name : typeof record.name === "string" ? record.name : null;
    const email = typeof record.primary_email === "string" ? record.primary_email : null;
    const domain = typeof record.primary_domain === "string" ? record.primary_domain : null;
    const label = displayName ?? (email ?? domain ?? id);
    const subtitle = kind === "person" ? email : domain ?? email;
    parsed.push({ id, label: `${label}`, subtitle, kind, primaryEmail: email });
  }
  return parsed;
}
function normalizeAddressDraft(draft) {
  if (!draft) return null;
  const normalized = {};
  const assign = (key, target) => {
    const value = draft[key];
    if (typeof value === "string" && value.trim().length) normalized[target] = value.trim();
    if (typeof value === "boolean") normalized[target] = value;
  };
  assign("name", "name");
  assign("purpose", "purpose");
  assign("companyName", "companyName");
  assign("addressLine1", "addressLine1");
  assign("addressLine2", "addressLine2");
  assign("buildingNumber", "buildingNumber");
  assign("flatNumber", "flatNumber");
  assign("city", "city");
  assign("region", "region");
  assign("postalCode", "postalCode");
  assign("country", "country");
  assign("isPrimary", "isPrimary");
  return Object.keys(normalized).length ? normalized : null;
}
function DocumentNumberField({ value, setValue, values, t }) {
  const formValues = values ?? {};
  const kind = formValues.documentKind === "order" ? "order" : "quote";
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const autoValueRef = React.useRef(null);
  const lastKindRef = React.useRef(null);
  const requestNumber = React.useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const call = await apiCall("/api/sales/document-numbers", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ kind })
      });
      const nextNumber = typeof call.result?.number === "string" ? call.result.number : null;
      if (call.ok && nextNumber) {
        autoValueRef.current = nextNumber;
        lastKindRef.current = kind;
        setValue(nextNumber);
      } else {
        setError(call.result?.error || t("sales.documents.form.errors.numberGenerate", "Could not generate a document number."));
      }
    } catch (err) {
      logger.error("sales.documents.generateNumber", { err });
      setError(t("sales.documents.form.errors.numberGenerate", "Could not generate a document number."));
    } finally {
      setLoading(false);
    }
  }, [kind, setValue, t]);
  React.useEffect(() => {
    const current = typeof value === "string" ? value.trim() : "";
    if (!current.length && !lastKindRef.current) {
      void requestNumber();
    } else {
      lastKindRef.current = kind;
    }
  }, [kind, requestNumber, value]);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex w-full flex-col gap-2 md:flex-row md:items-center md:gap-3", children: [
      /* @__PURE__ */ jsx(
        Input,
        {
          value: typeof value === "string" ? value : "",
          onChange: (event) => setValue(event.target.value),
          disabled: loading,
          spellCheck: false,
          className: "w-full md:flex-1"
        }
      ),
      /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: requestNumber, disabled: loading, children: loading ? t("sales.documents.form.numberLoading", "Generating\u2026") : t("sales.documents.form.numberRefresh", "Generate") })
    ] }),
    /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: kind === "order" ? t("sales.documents.form.numberHintOrder", "Format applies to orders and uses the configured counter.") : t("sales.documents.form.numberHintQuote", "Format applies to quotes and uses the configured counter.") }),
    error ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: error }) : null
  ] });
}
function BillingAddressSectionField({ values, setFormValue, t, addressesLoading, addressOptions, addressFormat }) {
  const formValues = values ?? {};
  const updateValue = setFormValue ?? (() => {
  });
  const useCustom = formValues.useCustomBilling === true;
  const selectedId = typeof formValues.billingAddressId === "string" ? formValues.billingAddressId : "";
  const draft = formValues.billingAddressDraft ?? {};
  const customerRequired = !formValues.customerEntityId;
  const sameAsShipping = formValues.sameAsShipping !== false;
  const shippingId = typeof formValues.shippingAddressId === "string" ? formValues.shippingAddressId : null;
  const shippingDraft = formValues.shippingAddressDraft ?? {};
  const shippingDraftKey = JSON.stringify(shippingDraft);
  const billingDraftKey = JSON.stringify(draft);
  const useCustomShipping = formValues.useCustomShipping === true;
  React.useEffect(() => {
    if (!sameAsShipping) return;
    if ((formValues.billingAddressId ?? null) !== shippingId) {
      updateValue("billingAddressId", shippingId);
    }
    if (useCustomShipping !== (formValues.useCustomBilling === true)) {
      updateValue("useCustomBilling", useCustomShipping);
    }
    if (useCustomShipping && shippingDraftKey !== billingDraftKey) {
      updateValue("billingAddressDraft", shippingDraft);
    }
  }, [
    billingDraftKey,
    sameAsShipping,
    updateValue,
    shippingDraft,
    shippingDraftKey,
    shippingId,
    useCustomShipping,
    formValues.billingAddressId,
    formValues.useCustomBilling
  ]);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1 md:flex-row md:items-center md:justify-between", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("p", { className: "text-base font-semibold", children: t("sales.documents.form.billing.title", "Billing address") }),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: sameAsShipping ? t("sales.documents.form.address.sameAsShippingHint", "Billing will mirror the shipping address. Uncheck to edit.") : t("sales.documents.form.billing.hint", "Select an address or define a new one.") })
      ] }),
      /* @__PURE__ */ jsx(
        SwitchField,
        {
          label: t("sales.documents.form.address.sameAsShipping", "Same as shipping"),
          flip: true,
          checked: sameAsShipping,
          onCheckedChange: (checked) => {
            updateValue("sameAsShipping", checked);
            if (checked) {
              updateValue("useCustomBilling", useCustomShipping);
              updateValue("billingAddressId", shippingId);
              updateValue("billingAddressDraft", shippingDraft);
            }
          }
        }
      )
    ] }),
    !sameAsShipping ? /* @__PURE__ */ jsxs(Fragment, { children: [
      !useCustom ? /* @__PURE__ */ jsxs(
        Select,
        {
          value: selectedId || void 0,
          onValueChange: (value) => updateValue("billingAddressId", value || null),
          disabled: addressesLoading || customerRequired,
          children: [
            /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(
              SelectValue,
              {
                placeholder: addressesLoading ? t("sales.documents.form.address.loading", "Loading addresses\u2026") : t("sales.documents.form.address.placeholder", "Select address")
              }
            ) }),
            /* @__PURE__ */ jsx(SelectContent, { children: addressOptions.map((addr) => {
              const optionLabel = addr.summary ? `${addr.label} \u2014 ${addr.summary}` : addr.label;
              return /* @__PURE__ */ jsx(SelectItem, { value: addr.id, children: optionLabel }, addr.id);
            }) })
          ]
        }
      ) : null,
      /* @__PURE__ */ jsx(
        SwitchField,
        {
          label: t("sales.documents.form.shipping.custom", "Define new address"),
          flip: true,
          checked: useCustom,
          onCheckedChange: (checked) => updateValue("useCustomBilling", checked),
          disabled: false
        }
      ),
      useCustom ? /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsx(
          AddressEditor,
          {
            value: draft,
            format: addressFormat,
            t,
            onChange: (next) => updateValue("billingAddressDraft", next),
            hidePrimaryToggle: true
          }
        ),
        /* @__PURE__ */ jsx(
          SwitchField,
          {
            containerClassName: "col-span-2",
            label: t("sales.documents.form.address.saveToCustomer", "Save this address to the customer"),
            flip: true,
            checked: formValues.saveBillingAddress === true,
            onCheckedChange: (checked) => updateValue("saveBillingAddress", checked)
          }
        )
      ] }) : null
    ] }) : null
  ] });
}
function CustomerGroupComponent({ values, setValue, t, customers, setCustomers, customerQuerySetter, loadAddresses, loadCustomers, fetchCustomerEmail, resetAddressFormState }) {
  const emailValue = typeof values.customerEmail === "string" ? values.customerEmail : "";
  const { duplicate, checking } = useEmailDuplicateCheck(emailValue, {
    disabled: false,
    debounceMs: 400,
    matchMode: "prefix"
  });
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsx("div", { className: "space-y-3", children: /* @__PURE__ */ jsx(
      LookupSelect,
      {
        value: typeof values.customerEntityId === "string" ? values.customerEntityId : null,
        onChange: (next) => {
          if (next !== values.customerEntityId) {
            resetAddressFormState(setValue);
          }
          setValue("customerEntityId", next);
          loadAddresses(next).then((addrs) => {
            const primary = addrs.find((addr) => addr.isPrimary);
            if (primary) {
              setValue("shippingAddressId", primary.id);
            }
          }).catch((err) => {
            logger.error("sales.documents.autoSelectAddress", { err });
          });
          if (next) {
            const match = customers.find((entry) => entry.id === next);
            const possibleEmail = typeof match?.primaryEmail === "string" && match.primaryEmail.length ? match.primaryEmail : null;
            if (possibleEmail) {
              setValue("customerEmail", possibleEmail);
            } else {
              fetchCustomerEmail(next, match?.kind).then((email) => {
                if (email) setValue("customerEmail", email);
              }).catch(() => {
              });
            }
          }
        },
        fetchItems: async (query) => {
          const options = await loadCustomers(query);
          return options.map((opt) => ({
            id: opt.id,
            title: opt.label,
            subtitle: opt.subtitle ?? void 0,
            icon: opt.kind === "person" ? /* @__PURE__ */ jsx(UserRound, { className: "h-5 w-5 text-muted-foreground" }) : /* @__PURE__ */ jsx(Building2, { className: "h-5 w-5 text-muted-foreground" })
          }));
        },
        actionSlot: /* @__PURE__ */ jsx(
          CustomerQuickCreate,
          {
            t,
            onCreated: ({ id, email, label, kind, subtitle }) => {
              customerQuerySetter.current?.(label);
              setCustomers((prev) => {
                const exists = prev.some((entry) => entry.id === id);
                if (exists) return prev;
                const next = {
                  id,
                  label,
                  subtitle: subtitle ?? void 0,
                  kind,
                  primaryEmail: email ?? null
                };
                return [next, ...prev];
              });
              setValue("customerEntityId", id);
              resetAddressFormState(setValue);
              loadAddresses(id).then((addrs) => {
                const primary = addrs.find((addr) => addr.isPrimary);
                if (primary) {
                  setValue("shippingAddressId", primary.id);
                }
              }).catch((err) => {
                logger.error("sales.documents.autoSelectAddress", { err });
              });
              if (email && !values.customerEmail) {
                setValue("customerEmail", email);
              }
            }
          }
        ),
        onReady: ({ setQuery }) => {
          customerQuerySetter.current = setQuery;
        },
        searchPlaceholder: t("sales.documents.form.customer.placeholder", "Search customers\u2026"),
        loadingLabel: t("sales.documents.form.customer.loading", "Loading customers\u2026"),
        emptyLabel: t("sales.documents.form.customer.empty", "No customers found."),
        selectedHintLabel: (id) => t("sales.documents.form.customer.selected", "Selected customer: {{id}}", { id })
      }
    ) }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx(
        EmailInput,
        {
          value: emailValue,
          onChange: (event) => setValue("customerEmail", event.target.value),
          placeholder: t("sales.documents.form.email.placeholder", "Email used for the document"),
          spellCheck: false
        }
      ),
      duplicate ? /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between rounded border bg-muted px-3 py-2 text-xs text-muted-foreground", children: [
        /* @__PURE__ */ jsx("span", { children: t("customers.people.form.emailDuplicateNotice", void 0, { name: duplicate.displayName }) }),
        /* @__PURE__ */ jsx(
          Button,
          {
            size: "sm",
            variant: "secondary",
            className: "px-4",
            type: "button",
            disabled: values.customerEntityId === duplicate.id,
            "aria-disabled": values.customerEntityId === duplicate.id,
            onClick: () => {
              setValue("customerEntityId", duplicate.id);
              resetAddressFormState(setValue);
              loadAddresses(duplicate.id);
            },
            children: values.customerEntityId === duplicate.id ? t("sales.documents.form.email.alreadySelected", "Selected customer") : t("sales.documents.form.email.selectCustomer", "Select customer")
          }
        )
      ] }) : null,
      !duplicate && checking ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("customers.people.form.emailChecking") }) : null
    ] })
  ] });
}
function SalesDocumentForm({ onCreated, isSubmitting = false, initialKind, inboxPreFill }) {
  const t = useT();
  const [customers, setCustomers] = React.useState([]);
  const [customerLoading, setCustomerLoading] = React.useState(false);
  const [channels, setChannels] = React.useState([]);
  const [channelLoading, setChannelLoading] = React.useState(false);
  const [addressOptions, setAddressOptions] = React.useState([]);
  const [addressesLoading, setAddressesLoading] = React.useState(false);
  const [addressesError, setAddressesError] = React.useState(null);
  const [addressFormat, setAddressFormat] = React.useState("line_first");
  const [defaultCurrency, setDefaultCurrency] = React.useState("USD");
  const addressRequestRef = React.useRef(0);
  const addressAbortRef = React.useRef(null);
  const addressTimeoutRef = React.useRef(null);
  const customerQuerySetter = React.useRef(null);
  const currencyLabels = React.useMemo(() => ({
    placeholder: t("sales.documents.form.currency.placeholder", "Select currency"),
    addLabel: t("sales.documents.form.currency.add", "Add currency"),
    addPrompt: t("sales.documents.form.currency.prompt", "Currency code"),
    dialogTitle: t("sales.documents.form.currency.dialogTitle", "Add currency"),
    valueLabel: t("sales.documents.form.currency.valueLabel", "Currency code"),
    valuePlaceholder: t("sales.documents.form.currency.valuePlaceholder", "e.g. USD"),
    labelLabel: t("sales.documents.form.currency.labelLabel", "Label"),
    labelPlaceholder: t("sales.documents.form.currency.labelPlaceholder", "Display name"),
    emptyError: t("sales.documents.form.currency.emptyError", "Currency code is required"),
    cancelLabel: t("sales.documents.form.currency.cancel", "Cancel"),
    saveLabel: t("sales.documents.form.currency.save", "Save"),
    saveShortcutHint: "\u2318/Ctrl + Enter",
    successCreateLabel: t("sales.documents.form.currency.created", "Currency saved."),
    errorLoad: t("sales.documents.form.currency.errorLoad", "Failed to load currencies."),
    errorSave: t("sales.documents.form.currency.errorSave", "Failed to save currency."),
    loadingLabel: t("sales.documents.form.currency.loading", "Loading currencies\u2026"),
    manageTitle: t("sales.documents.form.currency.manage", "Manage currency dictionary")
  }), [t]);
  const { data: currencyDictionary, refetch: refetchCurrencyDictionary } = useCurrencyDictionary();
  const fetchCurrencyOptions = React.useCallback(async () => {
    try {
      const source = currencyDictionary ?? await refetchCurrencyDictionary();
      if (source && Array.isArray(source.entries)) {
        return source.entries.map((entry) => ({
          value: entry.value,
          label: entry.label,
          color: entry.color ?? null,
          icon: entry.icon ?? null
        }));
      }
      return [];
    } catch (err) {
      logger.error("sales.documents.currency", { err });
      return [];
    }
  }, [currencyDictionary, refetchCurrencyDictionary]);
  const loadCustomers = React.useCallback(async (query) => {
    setCustomerLoading(true);
    try {
      const params = new URLSearchParams({ page: "1", pageSize: "20" });
      if (query && query.trim().length) params.set("search", query.trim());
      const [people, companies] = await Promise.all([
        apiCall(`/api/customers/people?${params.toString()}`),
        apiCall(`/api/customers/companies?${params.toString()}`)
      ]);
      const peopleItems = Array.isArray(people.result?.items) ? people.result?.items ?? [] : [];
      const companyItems = Array.isArray(companies.result?.items) ? companies.result?.items ?? [] : [];
      const merged = [...parseCustomerOptions(peopleItems, "person"), ...parseCustomerOptions(companyItems, "company")];
      setCustomers(merged);
      return merged;
    } catch (err) {
      logger.error("sales.documents.loadCustomers", { err });
      flash(t("sales.documents.form.errors.customers", "Failed to load customers."), "error");
      return [];
    } finally {
      setCustomerLoading(false);
    }
  }, [t]);
  const fetchCustomerEmail = React.useCallback(
    async (id, kindHint) => {
      try {
        const kind = kindHint ?? customers.find((item2) => item2.id === id)?.kind ?? null;
        const endpoint = kind === "company" ? "/api/customers/companies" : "/api/customers/people";
        const params = new URLSearchParams({ id, pageSize: "1", page: "1" });
        const call = await apiCall(`${endpoint}?${params.toString()}`);
        if (!call.ok || !Array.isArray(call.result?.items) || !call.result.items.length) return null;
        const item = call.result.items[0];
        const email = typeof item?.primary_email === "string" && item.primary_email || typeof item?.primaryEmail === "string" && item.primaryEmail || null;
        if (email) {
          setCustomers(
            (prev) => prev.map((entry) => entry.id === id ? { ...entry, primaryEmail: email } : entry)
          );
        }
        return email ?? null;
      } catch (err) {
        logger.error("sales.documents.fetchCustomerEmail", { err });
        return null;
      }
    },
    [customers]
  );
  const loadChannels = React.useCallback(async (query) => {
    setChannelLoading(true);
    try {
      const params = new URLSearchParams({ page: "1", pageSize: "20" });
      if (query && query.trim().length) params.set("search", query.trim());
      const call = await apiCall(
        `/api/sales/channels?${params.toString()}`
      );
      if (call.ok && Array.isArray(call.result?.items)) {
        const options = call.result.items.map((item) => {
          const id = typeof item?.id === "string" ? item.id : null;
          if (!id) return null;
          const label = typeof item?.name === "string" && item.name.trim().length ? item.name : id;
          const code = typeof item?.code === "string" && item.code.trim().length ? item.code : null;
          return { id, label: code ? `${label} (${code})` : label };
        }).filter((opt) => !!opt);
        if (!query) setChannels(options);
        return options;
      } else {
        setChannels([]);
        return [];
      }
    } catch (err) {
      logger.error("sales.documents.loadChannels", { err });
      setChannels([]);
      return [];
    } finally {
      setChannelLoading(false);
    }
  }, []);
  const loadDefaultCurrency = React.useCallback(async () => {
    try {
      const call = await apiCall(
        "/api/catalog/price-kinds?isPromotion=false&isActive=true&pageSize=1"
      );
      if (call.ok && Array.isArray(call.result?.items) && call.result.items.length) {
        const code = call.result.items[0]?.currency_code;
        if (typeof code === "string" && code.trim().length) {
          setDefaultCurrency(code.trim().toUpperCase());
        }
      }
    } catch (err) {
      logger.error("sales.documents.loadDefaultCurrency", { err });
    }
  }, []);
  const loadAddresses = React.useCallback(async (customerId) => {
    addressRequestRef.current += 1;
    const requestId = addressRequestRef.current;
    if (addressTimeoutRef.current) {
      clearTimeout(addressTimeoutRef.current);
      addressTimeoutRef.current = null;
    }
    if (addressAbortRef.current) {
      addressAbortRef.current.abort();
      addressAbortRef.current = null;
    }
    if (!customerId) {
      setAddressesError(null);
      setAddressOptions([]);
      setAddressesLoading(false);
      return [];
    }
    setAddressesLoading(true);
    setAddressesError(null);
    setAddressOptions([]);
    const controller = new AbortController();
    addressAbortRef.current = controller;
    addressTimeoutRef.current = setTimeout(() => controller.abort(), 12e3);
    try {
      const params = new URLSearchParams({ page: "1", pageSize: "50", entityId: customerId });
      const call = await apiCall(
        `/api/customers/addresses?${params.toString()}`,
        { signal: controller.signal },
        { fallback: { items: [] } }
      );
      if (call.ok && Array.isArray(call.result?.items)) {
        const options = call.result.items.reduce((acc, item) => {
          const id = typeof item.id === "string" ? item.id : null;
          if (!id) return acc;
          const value = {
            addressLine1: typeof item.address_line1 === "string" ? item.address_line1 : null,
            addressLine2: typeof item.address_line2 === "string" ? item.address_line2 : null,
            buildingNumber: typeof item.building_number === "string" ? item.building_number : null,
            flatNumber: typeof item.flat_number === "string" ? item.flat_number : null,
            city: typeof item.city === "string" ? item.city : null,
            region: typeof item.region === "string" ? item.region : null,
            postalCode: typeof item.postal_code === "string" ? item.postal_code : null,
            country: typeof item.country === "string" ? item.country : null,
            companyName: typeof item.company_name === "string" ? item.company_name : null
          };
          const name = typeof item.name === "string" ? item.name.trim() : "";
          const summary = formatAddressString(value, addressFormat);
          const label = name || summary || id;
          const isPrimary = item.is_primary === true;
          acc.push({ id, label, summary, value, name: name || null, isPrimary });
          return acc;
        }, []);
        if (addressRequestRef.current === requestId) {
          setAddressOptions(options);
        }
        return options;
      } else {
        if (addressRequestRef.current === requestId) {
          setAddressOptions([]);
          setAddressesError(
            t("sales.documents.detail.addresses.loadError", "Failed to load addresses.")
          );
        }
      }
    } catch (err) {
      if (err?.name !== "AbortError") {
        logger.error("sales.documents.loadAddresses", { err });
      }
      if (addressRequestRef.current === requestId) {
        setAddressOptions([]);
        if (err?.name !== "AbortError") {
          setAddressesError(
            t("sales.documents.detail.addresses.loadError", "Failed to load addresses.")
          );
        }
      }
    } finally {
      if (addressTimeoutRef.current) {
        clearTimeout(addressTimeoutRef.current);
        addressTimeoutRef.current = null;
      }
      if (addressAbortRef.current === controller) {
        addressAbortRef.current = null;
      }
      if (addressRequestRef.current === requestId) {
        setAddressesLoading(false);
      }
    }
    return [];
  }, [addressFormat, t]);
  React.useEffect(() => {
    loadCustomers().catch(() => {
    });
    loadChannels().catch(() => {
    });
    loadDefaultCurrency().catch(() => {
    });
  }, [loadChannels, loadCustomers, loadDefaultCurrency]);
  React.useEffect(
    () => () => {
      if (addressAbortRef.current) {
        addressAbortRef.current.abort();
        addressAbortRef.current = null;
      }
      if (addressTimeoutRef.current) {
        clearTimeout(addressTimeoutRef.current);
        addressTimeoutRef.current = null;
      }
    },
    []
  );
  React.useEffect(() => {
    setAddressOptions(
      (prev) => prev.map((entry) => {
        const summary = formatAddressString(entry.value, addressFormat);
        const label = (entry.name && entry.name.trim().length ? entry.name : "") || summary || entry.id;
        return { ...entry, summary, label };
      })
    );
  }, [addressFormat]);
  React.useEffect(() => {
    let cancelled = false;
    async function fetchAddressFormat() {
      try {
        const call = await apiCall("/api/customers/settings/address-format");
        const format = typeof call.result?.addressFormat === "string" ? call.result.addressFormat : null;
        if (!cancelled && (format === "street_first" || format === "line_first")) {
          setAddressFormat(format);
        }
      } catch (err) {
        logger.error("sales.documents.addressFormat", { err });
      } finally {
      }
    }
    fetchAddressFormat().catch(() => {
    });
    return () => {
      cancelled = true;
    };
  }, []);
  const resetAddressFormState = React.useCallback(
    (updateValue) => {
      updateValue("shippingAddressId", null);
      updateValue("billingAddressId", null);
      updateValue("shippingAddressDraft", void 0);
      updateValue("billingAddressDraft", void 0);
      updateValue("useCustomShipping", false);
      updateValue("useCustomBilling", false);
      updateValue("saveShippingAddress", false);
      updateValue("saveBillingAddress", false);
      updateValue("sameAsShipping", true);
    },
    []
  );
  const fields = React.useMemo(() => [
    {
      id: "documentKind",
      label: "",
      type: "custom",
      required: false,
      component: ({ value, setValue }) => {
        const current = value === "order" ? "order" : "quote";
        const label = t("sales.documents.form.kind", "Document type");
        return /* @__PURE__ */ jsxs("div", { className: "space-y-2 pt-0", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
            /* @__PURE__ */ jsx("div", { className: "text-sm font-semibold text-foreground", children: label }),
            /* @__PURE__ */ jsx("div", { className: "inline-flex rounded-lg border bg-background p-1 shadow-sm", children: ["quote", "order"].map((kind) => /* @__PURE__ */ jsx(
              Button,
              {
                type: "button",
                variant: current === kind ? "default" : "ghost",
                onClick: () => setValue(kind),
                children: t(`sales.documents.form.kind.${kind}`, kind.charAt(0).toUpperCase() + kind.slice(1))
              },
              kind
            )) })
          ] }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
            "sales.documents.form.kind.hint",
            "Please select which kind of sales document you want to create. When creating Quotes - it's kind of Shopping cart or Request for negotiation and could be converted to regular order later"
          ) })
        ] });
      }
    },
    {
      id: "documentNumber",
      label: t("sales.documents.form.number", "Document number"),
      type: "custom",
      required: true,
      component: (props) => /* @__PURE__ */ jsx(DocumentNumberField, { ...props, t })
    },
    {
      id: "currencyCode",
      label: t("sales.documents.form.currency", "Currency"),
      type: "custom",
      required: true,
      component: ({ value, setValue }) => /* @__PURE__ */ jsx(
        DictionaryEntrySelect,
        {
          value: typeof value === "string" ? value : void 0,
          onChange: (next) => setValue(next ?? ""),
          fetchOptions: fetchCurrencyOptions,
          allowInlineCreate: false,
          manageHref: "/backend/config/dictionaries?key=currency",
          selectClassName: "w-full",
          sortOptions: "none",
          labels: currencyLabels
        }
      )
    },
    {
      id: "channelId",
      label: t("sales.documents.form.channel", "Sales channel"),
      type: "custom",
      component: ({ value, setValue }) => /* @__PURE__ */ jsx(
        LookupSelect,
        {
          value: typeof value === "string" ? value : null,
          onChange: (next) => setValue(next),
          fetchItems: async (query) => {
            const options = await loadChannels(query);
            return options.map((opt) => ({
              id: opt.id,
              title: opt.label,
              icon: /* @__PURE__ */ jsx(Store, { className: "h-5 w-5 text-muted-foreground" })
            }));
          },
          searchPlaceholder: t("sales.documents.form.channel.placeholder", "Select a channel"),
          loadingLabel: t("sales.documents.form.channel.loading", "Loading channels\u2026"),
          emptyLabel: t("sales.documents.form.channel.empty", "No channels found."),
          selectedHintLabel: (id) => t("sales.documents.form.channel.selected", "Selected channel: {{id}}", { id })
        }
      )
    },
    {
      id: "shippingAddressSection",
      label: "",
      type: "custom",
      component: ({ values, setFormValue }) => {
        const formValues = values ?? {};
        const updateValue = setFormValue ?? (() => {
        });
        const useCustom = formValues.useCustomShipping === true;
        const selectedId = typeof formValues.shippingAddressId === "string" ? formValues.shippingAddressId : "";
        const draft = formValues.shippingAddressDraft ?? {};
        const customerRequired = !formValues.customerEntityId;
        const customerId = typeof formValues.customerEntityId === "string" ? formValues.customerEntityId : null;
        return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1 md:flex-row md:items-center md:justify-between", children: [
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("p", { className: "text-base font-semibold", children: t("sales.documents.form.shipping.title", "Shipping address") }),
              /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: customerRequired ? t("sales.documents.form.address.customerRequired", "Select customer first or define custom address") : t("sales.documents.form.shipping.hint", "Select an address or define a new one.") })
            ] }),
            /* @__PURE__ */ jsx(
              SwitchField,
              {
                label: t("sales.documents.form.shipping.custom", "Define new address"),
                flip: true,
                checked: useCustom,
                onCheckedChange: (checked) => updateValue("useCustomShipping", checked)
              }
            )
          ] }),
          !useCustom ? /* @__PURE__ */ jsxs(
            Select,
            {
              value: selectedId || void 0,
              onValueChange: (value) => updateValue("shippingAddressId", value || null),
              disabled: addressesLoading || customerRequired,
              children: [
                /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(
                  SelectValue,
                  {
                    placeholder: addressesLoading ? t("sales.documents.form.address.loading", "Loading addresses\u2026") : t("sales.documents.form.address.placeholder", "Select address")
                  }
                ) }),
                /* @__PURE__ */ jsx(SelectContent, { children: addressOptions.map((addr) => {
                  const optionLabel = addr.summary ? `${addr.label} \u2014 ${addr.summary}` : addr.label;
                  return /* @__PURE__ */ jsx(SelectItem, { value: addr.id, children: optionLabel }, addr.id);
                }) })
              ]
            }
          ) : null,
          useCustom ? /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
            /* @__PURE__ */ jsx(
              AddressEditor,
              {
                value: draft,
                format: addressFormat,
                t,
                onChange: (next) => updateValue("shippingAddressDraft", next),
                hidePrimaryToggle: true
              }
            ),
            /* @__PURE__ */ jsx(
              SwitchField,
              {
                containerClassName: "col-span-2",
                label: t("sales.documents.form.address.saveToCustomer", "Save this address to the customer"),
                flip: true,
                checked: formValues.saveShippingAddress === true,
                onCheckedChange: (checked) => updateValue("saveShippingAddress", checked)
              }
            )
          ] }) : null,
          addressesError && customerId ? /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3 rounded border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive", children: [
            /* @__PURE__ */ jsx("span", { className: "flex-1", children: addressesError }),
            /* @__PURE__ */ jsx(
              Button,
              {
                type: "button",
                size: "sm",
                variant: "outline",
                onClick: () => loadAddresses(customerId),
                disabled: addressesLoading,
                className: "shrink-0",
                children: t("sales.documents.detail.retry", "Try again")
              }
            )
          ] }) : null
        ] });
      }
    },
    {
      id: "billingAddressSection",
      label: "",
      type: "custom",
      component: (props) => /* @__PURE__ */ jsx(BillingAddressSectionField, { ...props, t, addressesLoading, addressOptions, addressFormat })
    },
    {
      id: "comments",
      label: t("sales.documents.form.comments", "Comments"),
      type: "textarea"
    },
    {
      id: "infoNote",
      label: "",
      type: "custom",
      component: () => /* @__PURE__ */ jsx("div", { className: "rounded-lg border bg-muted/50 p-3 text-sm text-muted-foreground", children: t("sales.documents.form.nextStep", "After creation you will add items, prices, and fulfillment details.") })
    }
  ], [
    addressFormat,
    addressOptions,
    addressesError,
    addressesLoading,
    currencyLabels,
    fetchCurrencyOptions,
    loadAddresses,
    loadChannels,
    loadCustomers,
    resetAddressFormState,
    t
  ]);
  const groups = React.useMemo(() => [
    { id: "docType", title: "", column: 1, fields: ["documentKind", "documentNumber"] },
    {
      id: "customer",
      title: "",
      column: 1,
      fields: [],
      component: (ctx) => /* @__PURE__ */ jsx(CustomerGroupComponent, { ...ctx, t, customers, setCustomers, customerQuerySetter, loadAddresses, loadCustomers, fetchCustomerEmail, resetAddressFormState })
    },
    { id: "channels-comments", title: "", column: 1, fields: ["channelId", "comments"] },
    { id: "currency", title: "", column: 2, fields: ["currencyCode"] },
    { id: "shipping", title: "", column: 2, fields: ["shippingAddressSection"] },
    { id: "billing", title: "", column: 2, fields: ["billingAddressSection"] },
    { id: "custom", title: t("sales.documents.form.customFields", "Custom fields"), column: 2, kind: "customFields" }
  ], [
    customers,
    fetchCustomerEmail,
    loadAddresses,
    loadCustomers,
    resetAddressFormState,
    t
  ]);
  const initialValues = React.useMemo(
    () => ({
      documentKind: initialKind === "order" ? "order" : "quote",
      documentNumber: "",
      currencyCode: inboxPreFill?.currencyCode || defaultCurrency,
      channelId: inboxPreFill?.channelId || void 0,
      customerEntityId: inboxPreFill?.customerEntityId || void 0,
      comments: inboxPreFill?.comments || void 0,
      useCustomShipping: false,
      useCustomBilling: false,
      sameAsShipping: true
    }),
    [initialKind, inboxPreFill, defaultCurrency]
  );
  React.useEffect(() => {
    if (inboxPreFill?.customerEntityId) {
      loadAddresses(inboxPreFill.customerEntityId);
    }
  }, [inboxPreFill?.customerEntityId, loadAddresses]);
  const handleSubmit = React.useCallback(
    async (values) => {
      const safeValues = values ?? {};
      const customFields = collectCustomFieldValues(safeValues);
      const base = Object.fromEntries(
        Object.entries(safeValues).filter(([key]) => !key.startsWith("cf_") && !key.startsWith("cf:"))
      );
      const documentKind = base.documentKind === "order" ? "order" : "quote";
      const payload = {
        currencyCode: typeof base.currencyCode === "string" && base.currencyCode.trim().length ? base.currencyCode.trim().toUpperCase() : void 0,
        customerEntityId: base.customerEntityId || void 0,
        comments: base.comments ?? void 0,
        metadata: base.customerEmail ? { customerEmail: base.customerEmail } : void 0
      };
      payload.channelId = base.channelId || void 0;
      const documentNumber = typeof base.documentNumber === "string" ? base.documentNumber.trim() : "";
      if (!documentNumber) {
        throw createCrudFormError(t("sales.documents.form.errors.numberRequired", "Document number is required."));
      }
      if (documentKind === "order") {
        payload.orderNumber = documentNumber;
      } else {
        payload.quoteNumber = documentNumber;
      }
      const shippingSnapshot = base.useCustomShipping ? normalizeAddressDraft(base.shippingAddressDraft) : null;
      let billingSnapshot = base.useCustomBilling ? normalizeAddressDraft(base.billingAddressDraft) : null;
      const sameAsShipping = base.sameAsShipping !== false;
      if (sameAsShipping) {
        if (shippingSnapshot) {
          billingSnapshot = shippingSnapshot;
        } else if (!base.useCustomShipping) {
          payload.billingAddressId = base.shippingAddressId || void 0;
        }
      }
      if (shippingSnapshot) {
        payload.shippingAddressSnapshot = shippingSnapshot;
        payload.shippingAddressId = void 0;
      }
      if (billingSnapshot) {
        payload.billingAddressSnapshot = billingSnapshot;
        payload.billingAddressId = void 0;
      }
      if (!base.useCustomShipping) payload.shippingAddressId = base.shippingAddressId || void 0;
      if (!base.useCustomBilling && !sameAsShipping) payload.billingAddressId = base.billingAddressId || void 0;
      try {
        let shippingId = payload.shippingAddressId;
        let billingId = payload.billingAddressId;
        if (base.customerEntityId && shippingSnapshot && base.saveShippingAddress) {
          const res = await createCrud("customers/addresses", {
            entityId: base.customerEntityId,
            addressLine1: shippingSnapshot.addressLine1 ?? shippingSnapshot.name ?? "Address",
            name: shippingSnapshot.name ?? void 0,
            addressLine2: shippingSnapshot.addressLine2 ?? void 0,
            buildingNumber: shippingSnapshot.buildingNumber ?? void 0,
            flatNumber: shippingSnapshot.flatNumber ?? void 0,
            city: shippingSnapshot.city ?? void 0,
            region: shippingSnapshot.region ?? void 0,
            postalCode: shippingSnapshot.postalCode ?? void 0,
            country: shippingSnapshot.country ?? void 0,
            purpose: shippingSnapshot.purpose ?? void 0,
            isPrimary: shippingSnapshot.isPrimary ?? void 0
          });
          if (res?.result?.id) shippingId = res.result.id;
        }
        if (base.customerEntityId && billingSnapshot && base.saveBillingAddress) {
          const res = await createCrud("customers/addresses", {
            entityId: base.customerEntityId,
            addressLine1: billingSnapshot.addressLine1 ?? billingSnapshot.name ?? "Address",
            name: billingSnapshot.name ?? void 0,
            addressLine2: billingSnapshot.addressLine2 ?? void 0,
            buildingNumber: billingSnapshot.buildingNumber ?? void 0,
            flatNumber: billingSnapshot.flatNumber ?? void 0,
            city: billingSnapshot.city ?? void 0,
            region: billingSnapshot.region ?? void 0,
            postalCode: billingSnapshot.postalCode ?? void 0,
            country: billingSnapshot.country ?? void 0,
            purpose: billingSnapshot.purpose ?? void 0,
            isPrimary: billingSnapshot.isPrimary ?? void 0
          });
          if (res?.result?.id) billingId = res.result.id;
        }
        if (!base.useCustomShipping && shippingId) payload.shippingAddressId = shippingId;
        if (!base.useCustomBilling && !sameAsShipping && billingId) payload.billingAddressId = billingId;
        if (Object.keys(customFields).length) payload.customFields = customFields;
        const endpoint = documentKind === "order" ? "sales/orders" : "sales/quotes";
        const { result } = await createCrud(endpoint, payload, {
          errorMessage: t("sales.documents.form.errors.submit", "Failed to create document.")
        });
        const newId = result && typeof result.id === "string" && result.id || result && typeof result.orderId === "string" && result.orderId || result && typeof result.quoteId === "string" && result.quoteId || null;
        if (!newId) {
          throw createCrudFormError(t("sales.documents.form.errors.id", "Document id missing after create."));
        }
        flash(t("sales.documents.form.success", "Sales document created."), "success");
        onCreated({ id: newId, kind: documentKind });
      } catch (err) {
        if (err instanceof Error) throw err;
        throw createCrudFormError(t("sales.documents.form.errors.submit", "Failed to create document."));
      }
    },
    [onCreated, t]
  );
  const cancelHref = initialKind === "order" ? "/backend/sales/orders" : "/backend/sales/quotes";
  return /* @__PURE__ */ jsx(
    CrudForm,
    {
      title: t("sales.documents.form.title", "Create sales document"),
      backHref: cancelHref,
      fields,
      groups,
      initialValues,
      entityIds: [E.sales.sales_quote, E.sales.sales_order],
      submitLabel: t("sales.documents.form.submit", "Create"),
      cancelHref,
      onSubmit: handleSubmit
    }
  );
}
export {
  SalesDocumentForm
};
//# sourceMappingURL=SalesDocumentForm.js.map
