import { jsx as e } from "../../../../../external/.pnpm/preact@10.28.2/node_modules/preact/jsx-runtime/dist/jsxRuntime.module.js";
import S from "../../../../internal/Typography/Typography.js";
import { TypographyVariant as _, TypographyElement as Ie } from "../../../../internal/Typography/types.js";
import { Stepper as Be } from "../../../../internal/Stepper/Stepper.js";
import { useRef as j, useState as C, useCallback as l, useMemo as f } from "../../../../../external/.pnpm/preact@10.28.2/node_modules/preact/hooks/dist/hooks.module.js";
import { WizardFormProvider as Ee } from "../../../../../hooks/form/wizard/WizardFormContext.js";
import { ButtonVariant as b } from "../../../../internal/Button/types.js";
/* empty css                             */
/* empty css                             */
import De from "../../../../../hooks/useMutation/useMutation.js";
import { usePaymentLinkFormData as we } from "./usePaymentLinkFormData.js";
import { scrollToFirstErrorField as Re } from "../../utils.js";
import { useResponsiveContainer as Pe, containerQueries as xe } from "../../../../../hooks/useResponsiveContainer.js";
import { FormStepRenderer as Me } from "./FormStepRenderer.js";
import Oe from "../../../PaymentLinkSettings/components/PaymentLinkSettingsContainer/PaymentLinkSettingsContainer.js";
import { AlertTypeOption as q } from "../../../../internal/Alert/types.js";
import { Alert as z } from "../../../../internal/Alert/Alert.js";
import { ErrorMessageDisplay as Ve } from "../../../../internal/ErrorMessageDisplay/ErrorMessageDisplay.js";
import { useInvalidFieldsConfig as We } from "../../hooks/useInvalidFieldsConfig.js";
import $e from "../../../../internal/CopyText/CopyText.js";
import Ye from "../../../../../core/Context/preact/useCoreContext.js";
import { Translation as je } from "../../../../internal/Translation/Translation.js";
import A from "../../../../internal/Button/Button.js";
import { Fragment as K } from "../../../../../external/.pnpm/preact@10.28.2/node_modules/preact/dist/preact.module.js";
import { Icon as qe } from "../../../../internal/Icon/Icon.js";
const G = 28, ze = () => /* @__PURE__ */ e("div", { className: "adyen-pe-payment-link-creation-form__skeleton", children: [
  /* @__PURE__ */ e("div", { className: "adyen-pe-payment-link-creation-form__skeleton-item adyen-pe-payment-link-creation-form__skeleton-item--large" }),
  [...Array(3)].map((m, c) => /* @__PURE__ */ e(K, { children: [
    /* @__PURE__ */ e(
      "div",
      {
        className: "adyen-pe-payment-link-creation-form__skeleton-item adyen-pe-payment-link-creation-form__skeleton-item--small"
      },
      `${c}-small`
    ),
    /* @__PURE__ */ e(
      "div",
      {
        className: "adyen-pe-payment-link-creation-form__skeleton-item adyen-pe-payment-link-creation-form__skeleton-item--large"
      },
      `${c}-large`
    )
  ] }))
] }), ht = ({
  fieldsConfig: m,
  storeIds: c,
  onCreationDismiss: D,
  onPaymentLinkCreated: U,
  onContactSupport: d,
  embeddedInOverview: H
}) => {
  const w = j(null), [Q, X] = C(!1), R = j(null), J = !!m?.data?.billingAddress || !!m?.data?.deliveryAddress, [Z, ee] = C(!J), [N, P] = C(""), { i18n: n } = Ye(), x = Pe(xe.down.xs), {
    storesData: p,
    configurationData: T,
    countriesData: te,
    isFetchingCountries: ne,
    countryDatasetData: re,
    isFetchingCountryDataset: oe,
    settingsData: ie,
    storesSelectorItems: ae,
    termsAndConditionsProvisioned: L,
    formSteps: M,
    stepperItems: se,
    formStepsAriaLabel: le,
    wizardForm: s,
    createPaymentLink: me,
    isDataLoading: ce,
    isFirstLoadDone: de,
    selectedStore: O,
    setSelectedStore: g
  } = we({
    defaultValues: m?.data,
    visibilityConfig: m?.visibility,
    storeIds: c
  }), { isLastStep: y, isFirstStep: V, currentStep: u, validateStep: W, canGoNext: pe, isStepComplete: ye, nextStep: $, previousStep: ue, goToStep: Y } = s, [fe, h] = C(!1), ge = l(
    async (t) => {
      if (!y) {
        if (!await W(t)) {
          const i = R.current?.getBoundingClientRect().height ?? 0, r = x ? i + G : G;
          Re(Object.keys(s.formState.errors), r, w.current);
          return;
        }
        await $();
      }
    },
    [y, $, W, s.formState.errors, x]
  ), he = l(
    (t) => {
      Y(t);
    },
    [Y]
  ), F = f(() => {
    const t = M?.[u];
    return t ? t.id : "store";
  }, [u, M]), ke = () => {
    if (V) {
      D?.();
      return;
    }
    a.reset(), ue();
  }, ve = async () => {
    await ge(u);
  }, a = De({
    queryFn: me
  }), Se = async () => {
    const t = s.getApiPayloadValues(), { store: o, ...i } = t;
    try {
      const r = await a.mutate(
        {
          body: i,
          contentType: "application/json"
        },
        { path: { storeId: o } }
      );
      U?.({ ...t, paymentLink: r });
    } catch (r) {
      throw console.error("Failed to create payment link:", r), r;
    }
  }, _e = l(() => {
    g(N), h(!1), P("");
  }, [N, h, g]), Ce = () => {
    X(!0);
  }, be = a.isLoading || ce, I = f(() => p && p.data && p.data.length === 0, [p]), B = f(() => F !== "store" && !T, [T, F]), Ae = f(() => !L || I || B, [I, B, L]), { invalidFieldsConfig: E } = We(), k = l(
    (t) => !t || !("invalidFields" in t) || !t.invalidFields?.length ? [] : t.invalidFields.map((o) => {
      const i = E.fields?.[o.name], r = E.messages?.[o.message];
      if (!i && !r) return null;
      const v = i ? n.get(i) : o.name;
      if (!r) return `${v}`;
      const Fe = n.get(r);
      return `${v} (${Fe})`;
    }).filter((o) => o !== null),
    [n, E]
  ), Ne = l(() => {
    P(O), g(""), h(!0);
  }, [O, g, h]), Te = l(
    (t) => k(t).length ? n.get("payByLink.creation.form.alert.invalidFields") : n.get("payByLink.creation.form.alert.somethingWentWrong"),
    [k, n]
  ), Le = f(() => {
    const t = a.error, o = k(t), i = o.length > 0;
    return /* @__PURE__ */ e("div", { className: "adyen-pe-payment-link-creation-form__error-alert", children: [
      i && /* @__PURE__ */ e("ul", { className: "adyen-pe-payment-link-creation-form__invalid-fields-error", children: o.map((r, v) => /* @__PURE__ */ e("li", { children: /* @__PURE__ */ e(S, { variant: _.CAPTION, children: r }) }, v)) }),
      d && /* @__PURE__ */ e("div", { className: "adyen-pe-payment-link-creation-form__contact-support", children: /* @__PURE__ */ e(
        je,
        {
          translationKey: "payByLink.creation.form.error.submit.contactSupport",
          fills: {
            contactSupport: /* @__PURE__ */ e(A, { variant: b.TERTIARY, onClick: d, children: n.get("common.actions.contactSupport.labels.reachOut") }),
            errorCode: /* @__PURE__ */ e($e, { stronger: !0, textToCopy: t?.requestId || t?.errorCode })
          }
        }
      ) })
    ] });
  }, [k, n, d, a.error]);
  return de ? fe ? /* @__PURE__ */ e(
    Oe,
    {
      hideTitle: !0,
      storeIds: N,
      settingsItems: ["termsAndConditions"],
      navigateBack: _e,
      embeddedInOverview: H
    }
  ) : /* @__PURE__ */ e("div", { className: "adyen-pe-payment-link-creation-form__component", children: [
    /* @__PURE__ */ e("div", { className: "adyen-pe-payment-link-creation-form__header", ref: R, children: [
      /* @__PURE__ */ e(S, { variant: _.SUBTITLE, stronger: !0, children: n.get("payByLink.creation.form.title") }),
      /* @__PURE__ */ e(
        Be,
        {
          nextStepDisabled: !pe || !ye(u),
          variant: "horizontal",
          activeIndex: u,
          ariaLabel: le,
          onChange: he,
          children: se.map((t) => /* @__PURE__ */ e(K, { children: t.label }))
        }
      )
    ] }),
    /* @__PURE__ */ e(Ee, { ...s, children: /* @__PURE__ */ e("div", { className: "adyen-pe-payment-link-creation-form__container", children: /* @__PURE__ */ e(
      "form",
      {
        className: "adyen-pe-payment-link-creation-form",
        onSubmit: (t) => {
          t.preventDefault(), s.handleSubmit(Se, Ce)(t);
        },
        ref: w,
        children: [
          /* @__PURE__ */ e("div", { children: /* @__PURE__ */ e(
            Me,
            {
              setShowTermsAndConditions: Ne,
              currentFormStep: F,
              settingsData: ie,
              storeIds: c,
              storesData: p,
              selectItems: ae,
              termsAndConditionsProvisioned: L,
              configurationData: T,
              isSameAddress: Z,
              setIsSameAddress: ee,
              countriesData: te,
              isFetchingCountries: ne,
              countryDatasetData: re,
              isFetchingCountryDataset: oe
            }
          ) }),
          (B || Q) && /* @__PURE__ */ e(
            Ve,
            {
              condensed: !0,
              title: "common.errors.somethingWentWrong",
              withImage: !0,
              absolutePosition: !1,
              outlined: !1,
              withBackground: !1,
              message: ["payByLink.creation.errors.unavailable", "common.errors.retry"]
            }
          ),
          I && /* @__PURE__ */ e(
            z,
            {
              type: q.WARNING,
              title: n.get("payByLink.common.errors.accountConfiguration"),
              description: /* @__PURE__ */ e("div", { className: "adyen-pe-payment-link-creation-form__warning-alert", children: [
                /* @__PURE__ */ e(S, { variant: _.CAPTION, el: Ie.SPAN, children: n.get("common.errors.contactSupport") }),
                d ? /* @__PURE__ */ e(A, { variant: b.TERTIARY, onClick: d, children: n.get("common.actions.contactSupport.labels.reachOut") }) : null
              ] })
            }
          ),
          a.isError && /* @__PURE__ */ e(
            z,
            {
              type: q.CRITICAL,
              title: Te(a.error),
              description: Le
            }
          ),
          /* @__PURE__ */ e("div", { className: "adyen-pe-payment-link-creation-form__buttons-container", children: [
            (!V || D) && /* @__PURE__ */ e(A, { variant: b.SECONDARY, onClick: ke, children: n.get("payByLink.creation.form.steps.back") }),
            /* @__PURE__ */ e(
              A,
              {
                className: "adyen-pe-payment-link-creation-form__submit-button",
                type: y ? "submit" : "button",
                variant: b.PRIMARY,
                onClick: y ? void 0 : ve,
                state: be ? "loading" : void 0,
                disabled: Ae,
                iconRight: /* @__PURE__ */ e(qe, { name: "arrow-right" }),
                children: y ? n.get("payByLink.creation.form.steps.submit") : n.get("payByLink.creation.form.steps.continue")
              }
            )
          ] })
        ]
      }
    ) }) })
  ] }) : /* @__PURE__ */ e("div", { className: "adyen-pe-payment-link-creation-form__component", children: /* @__PURE__ */ e("div", { className: "adyen-pe-payment-link-creation-form__header", children: [
    /* @__PURE__ */ e(S, { variant: _.SUBTITLE, stronger: !0, children: n.get("payByLink.creation.form.title") }),
    /* @__PURE__ */ e(ze, {})
  ] }) });
};
export {
  ht as PaymentLinkCreationFormContainer
};
