import { jsx as r } from "../../../../../../../external/.pnpm/preact@10.28.2/node_modules/preact/jsx-runtime/dist/jsxRuntime.module.js";
import { useState as I, useCallback as d, useMemo as w, useEffect as K } from "../../../../../../../external/.pnpm/preact@10.28.2/node_modules/preact/hooks/dist/hooks.module.js";
import { useWizardFormContext as P } from "../../../../../../../hooks/form/wizard/WizardFormContext.js";
import { VisibleField as W } from "../../../../../../internal/FormWrappers/VisibleField.js";
import $ from "../../../../../../internal/FormWrappers/FormField.js";
import { LINK_VALIDITY_DURATION_UNITS as G } from "../../../../constants.js";
import H from "../../../../../../internal/FormFields/InputBase.js";
import { FieldError as J } from "../../../../../../internal/FormFields/FieldError/FieldError.js";
import Q from "../../../../../../../core/Context/preact/useCoreContext.js";
import { transformToMS as N } from "../../../../../../../utils/datetime/main.js";
import { Controller as A } from "../../../../../../../hooks/form/Controller.js";
import Z from "../../../../../../internal/FormFields/Select/Select.js";
const M = 70, u = "flexible", yi = ({ configuration: D }) => {
  const [O, p] = I(""), [E, f] = I(void 0), [y, q] = I(""), { i18n: e } = Q(), { control: U, fieldsConfig: c, setValue: s, getValues: V, trigger: m } = P(), a = d(
    () => [V("linkValidity.durationUnit"), V("linkValidity.quantity")],
    [V]
  ), o = w(() => (D?.linkValidity?.options ?? []).map(({ quantity: t, durationUnit: n, type: l }) => {
    if (l === u)
      return { id: u, name: e.get("payByLink.creation.fields.validity.linkValidityUnit.custom") };
    const k = `payByLink.creation.fields.validity.linkValidityUnit.${n}`;
    return { id: `${t} ${n}`, name: e.get(k, { values: { quantity: t }, count: t }) };
  }), [D, e]), L = d(() => {
    if (!o.length) return;
    const [i, t] = a();
    if (!t || !i) {
      const [n, l] = `${o[0]?.id}`.split(" ");
      s("linkValidity.quantity", n), s("linkValidity.durationUnit", l);
    }
  }, [o, s, a]), h = d(() => {
    const [i, t] = a();
    return !t || !i ? o[0] : o.find((n) => n.id === `${t} ${i}`) || { id: u };
  }, [o, a]);
  K(() => {
    const [i, t] = a();
    p(i || ""), f(t || ""), q(h()?.id || ""), L();
  }, [a, o, h, L]);
  const C = c["linkValidity.durationUnit"]?.required, B = c["linkValidity.quantity"]?.required, g = c["linkValidity.durationUnit"]?.readOnly || c["linkValidity.quantity"]?.readOnly, R = d(
    (i) => {
      const t = i.target?.value, n = parseInt(t, 10);
      s("linkValidity.quantity", n), f(n), m("linkValidity.durationUnit");
    },
    [s, m]
  ), S = d(
    (i) => {
      s("linkValidity.durationUnit", i), p(i), m("linkValidity.quantity");
    },
    [s, m]
  ), Y = w(
    () => G.map((i) => ({
      id: i,
      name: e.get(`payByLink.creation.fields.validity.linkValidityUnit.${i}__plural`)
    })),
    [e]
  ), T = d(() => {
    if (y !== u) return { valid: !0 };
    const [i, t] = a(), n = parseInt(t, 10);
    return t ? isNaN(n) || n <= 0 ? { valid: !1, message: e.get("payByLink.creation.fields.validity.customDuration.error.invalidDurationValue") } : i ? N(i, n) > N("day", M) ? {
      valid: !1,
      message: e.get("payByLink.creation.fields.validity.customDuration.error.durationTooLong", {
        values: { maxDays: M }
      })
    } : { valid: !0 } : { valid: !1, message: e.get("payByLink.creation.fields.validity.customDuration.error.missingDurationUnit") } : { valid: !1, message: e.get("payByLink.creation.fields.validity.customDuration.error.missingDurationValue") };
  }, [y, e, a]);
  return /* @__PURE__ */ r(W, { name: "linkValidity.durationUnit", children: /* @__PURE__ */ r(
    A,
    {
      name: "linkValidity.durationUnit",
      control: U,
      rules: {
        required: C,
        validate: T
      },
      render: ({ field: i, fieldState: t }) => /* @__PURE__ */ r(
        A,
        {
          name: "linkValidity.quantity",
          control: U,
          rules: { required: B, validate: T },
          render: ({ field: n, fieldState: l }) => {
            const k = (z) => {
              const v = z.target?.value;
              if (v !== u) {
                const [X, j] = v?.split(" ") || [];
                n.onInput(X), i.onInput(j), n.triggerValidation(), i.triggerValidation();
              } else
                i.onInput(""), n.onInput(""), f(void 0), p("");
              q(v);
            }, _ = (l.error || t.error) && l.isTouched && t.isTouched, b = !l.error || !t.error, x = l.error?.message || t.error?.message;
            return /* @__PURE__ */ r("div", { children: [
              /* @__PURE__ */ r("div", { className: "adyen-pe-payment-link-creation-form__validity-container", children: [
                /* @__PURE__ */ r(
                  $,
                  {
                    label: e.get("payByLink.creation.fields.validity.label"),
                    supportText: e.get("payByLink.creation.fields.validity.supportText"),
                    optional: !C && !B,
                    testId: "form-field-linkValidity.durationUnit",
                    children: /* @__PURE__ */ r(
                      Z,
                      {
                        selected: y,
                        onChange: k,
                        items: o,
                        isValid: b,
                        isInvalid: !y,
                        readonly: g
                      }
                    )
                  }
                ),
                y === u && /* @__PURE__ */ r(
                  $,
                  {
                    label: e.get("payByLink.creation.fields.validity.customDuration.label"),
                    optional: !1,
                    testId: "form-field-linkValidity.quantity",
                    children: /* @__PURE__ */ r(
                      H,
                      {
                        ...n,
                        dropdown: {
                          ...i,
                          items: Y,
                          value: O || "",
                          readonly: g
                        },
                        onDropdownInput: S,
                        dropdownPosition: "end",
                        value: E,
                        type: "number",
                        onInput: R,
                        isValid: b,
                        isInvalid: _,
                        readonly: g
                      }
                    )
                  }
                )
              ] }),
              _ && x && /* @__PURE__ */ r(J, { errorMessage: x, testId: "field-error-linkValidity.quantity", withTopMargin: !0 })
            ] });
          }
        }
      )
    }
  ) });
};
export {
  yi as ValidityField
};
