import { jsx as n } from "../../../../../external/.pnpm/preact@10.28.2/node_modules/preact/jsx-runtime/dist/jsxRuntime.module.js";
import { useState as U, useCallback as d, useMemo as g } from "../../../../../external/.pnpm/preact@10.28.2/node_modules/preact/hooks/dist/hooks.module.js";
import K from "../../../../../hooks/useMutation/useMutation.js";
import X from "../../../../internal/Button/ButtonActions/ButtonActions.js";
import Z from "../../../../internal/Card/Card.js";
import { TypographyVariant as v } from "../../../../internal/Typography/types.js";
import N from "../../../../internal/Typography/Typography.js";
import { useDisputeFlow as ee } from "../../context/dispute/context.js";
import { DefendDocumentUpload as te } from "./DefendDocumentUpload.js";
import P from "./SelectAndUploadOptionalDoc.js";
import { ButtonVariant as F } from "../../../../internal/Button/types.js";
import { getDefenseDocumentContent as ne } from "../../utils/index.js";
import { validationErrors as S } from "../../../../internal/FormFields/FileInput/constants.js";
/* empty css                       */
import oe from "../../../../../core/Context/preact/useCoreContext.js";
import { Icon as z } from "../../../../internal/Icon/Icon.js";
import { Fragment as L } from "../../../../../external/.pnpm/preact@10.28.2/node_modules/preact/dist/preact.module.js";
import ie from "../../../../internal/Button/Button.js";
import { useConfigContext as se } from "../../../../../core/ConfigContext/preact/context.js";
import { getHumanReadableFileSize as de } from "../../../../../utils/file/size.js";
const re = [
  "disputes.management.defend.common.documentRequirements.language",
  "disputes.management.defend.common.documentRequirements.recommendedSize",
  "disputes.management.defend.common.documentRequirements.formatAndSize"
], Fe = () => {
  const { i18n: o } = oe(), { defendDispute: V } = se().endpoints, {
    clearFiles: D,
    clearStates: M,
    dispute: x,
    applicableDocuments: k,
    goBack: A,
    defendDisputePayload: r,
    defendResponse: T,
    onDefendSubmit: h,
    removeFieldFromDefendPayload: B,
    setFlowState: a,
    defenseDocumentConfig: I
  } = ee(), C = x?.dispute.pspReference, [R, $] = U(void 0), [m, _] = U([]), Y = d(() => {
    M(), a("details");
  }, [M, a]), q = d(
    (e, t) => {
      switch (e) {
        case S.DISALLOWED_FILE_TYPE:
          return o.get("common.inputs.file.errors.disallowedType");
        case S.FILE_REQUIRED:
          return o.get("disputes.management.defend.common.inputs.file.errors.required");
        case S.TOO_MANY_FILES:
          return o.get("common.inputs.file.errors.tooMany");
        case S.VERY_LARGE_FILE:
          return o.get("disputes.management.defend.common.inputs.file.errors.tooLarge", {
            values: {
              size: t?.size === void 0 ? void 0 : de(t.size),
              type: t?.type?.replace(/^([^/]+\/)*/gi, "")?.toUpperCase()
            }
          });
        default:
          return o.get("disputes.management.defend.common.inputs.file.errors.default");
      }
    },
    [o]
  ), { requiredDocuments: p, optionalDocuments: O, oneOrMoreDocuments: i } = g(() => {
    const e = {
      requiredDocuments: [],
      optionalDocuments: [],
      oneOrMoreDocuments: []
    };
    return (k ?? []).forEach(({ documentTypeCode: t, requirementLevel: s }) => {
      const l = ne(I, o, t)?.title || t;
      switch (s) {
        case "REQUIRED":
          e.requiredDocuments.push(t);
          break;
        case "OPTIONAL":
          e.optionalDocuments.push({
            id: t,
            name: l
          });
          break;
        case "ONE_OR_MORE":
          e.oneOrMoreDocuments.push({
            id: t,
            name: l
          });
          break;
      }
      return e;
    }), e;
  }, [k, o, I]), H = g(() => {
    if (!r) return !1;
    let e = p.every((t) => r.get(t) instanceof File);
    return i.length > 0 && (e &&= i.some((t) => r.get(t.id) instanceof File)), e;
  }, [r, i, p]), u = K({
    queryFn: V,
    options: {
      onSuccess: d(() => {
        D(), h("success"), a("defenseSubmitResponseView");
      }, [D, h, a]),
      onError: d(() => {
        D(), h("error"), a("defenseSubmitResponseView");
      }, [D, h, a])
    }
  }), f = T === "success", c = u.isLoading || f, b = r && H && !c, w = d(() => {
    b && u.mutate(
      { contentType: "multipart/form-data", body: r },
      { path: { disputePspReference: C } }
    );
  }, [b, C, u, r]), Q = g(() => [
    {
      title: o.get("disputes.management.defend.common.actions.submit"),
      disabled: !b,
      state: u.isLoading ? "loading" : "default",
      variant: F.PRIMARY,
      event: w,
      classNames: f ? ["adyen-pe-defend-dispute__defended-btn"] : void 0,
      renderTitle: (e) => f ? /* @__PURE__ */ n(L, { children: [
        /* @__PURE__ */ n(z, { name: "checkmark-circle-fill", className: "adyen-pe-defend-dispute__defended-icon" }),
        o.get("disputes.management.defend.common.defended")
      ] }) : e
    },
    {
      title: o.get("disputes.management.common.actions.goBack"),
      disabled: u.isLoading,
      variant: F.SECONDARY,
      event: f ? Y : A
    }
  ], [o, b, u.isLoading, w, f, Y, A]), y = d((e, t) => {
    e === void 0 ? _((s) => [...s, e]) : t !== void 0 && _((s) => {
      if (s[t] === e)
        return s;
      const l = [...s];
      return l[t] = e, l;
    });
  }, []), E = g(() => {
    if (c) return !1;
    const e = O.length + Math.max(0, i.length - 1);
    return !!(e && e !== m.length);
  }, [c, i, O, m]), W = d(() => {
    E && y();
  }, [E, y]), j = g(() => [...i.filter((t) => t.id !== R), ...O].map((t) => ({ ...t, disabled: m.includes(t.id) })), [i, R, O, m]), G = d(
    (e) => {
      _((t) => {
        if (e < 0 || e >= t.length)
          return t;
        const s = t[e];
        return s && B(s), t.filter((l, J) => J !== e);
      });
    },
    [B]
  );
  return /* @__PURE__ */ n(L, { children: /* @__PURE__ */ n(L, { children: [
    /* @__PURE__ */ n(N, { className: "adyen-pe-defend-dispute-file-uploader__subtitle", variant: v.BODY, children: o.get("disputes.management.defend.common.documentUploadInfo") }),
    /* @__PURE__ */ n(
      Z,
      {
        renderHeader: /* @__PURE__ */ n(N, { variant: v.BODY, stronger: !0, className: "adyen-pe-defend-dispute-document-requirements", children: o.get("disputes.management.defend.common.documentRequirements") }),
        filled: !0,
        expandable: !0,
        compact: !0,
        children: /* @__PURE__ */ n("ul", { className: "adyen-pe-defend-dispute-document-requirements--list", children: re.map((e, t) => /* @__PURE__ */ n("li", { className: "adyen-pe-defend-dispute-document-requirements--item", children: /* @__PURE__ */ n(N, { variant: v.BODY, children: o.get(e) }) }, `${e}-${t}`)) })
      }
    ),
    /* @__PURE__ */ n("div", { className: "adyen-pe-defend-dispute-file-uploader__container", children: [
      p.length || i.length ? /* @__PURE__ */ n("div", { className: "adyen-pe-defend-dispute-document-upload-box", children: [
        p.length ? /* @__PURE__ */ n("div", { className: "adyen-pe-defend-dispute-document-upload-box__required-documents", children: p?.map((e) => /* @__PURE__ */ n(
          te,
          {
            mapError: q,
            disabled: c,
            document: e,
            required: !0
          },
          e
        )) }) : null,
        i.length ? /* @__PURE__ */ n(
          P,
          {
            mapError: q,
            disabled: c,
            selection: R,
            setSelection: (e) => $(e),
            items: i,
            title: o.get("disputes.management.defend.common.documentTypes.required"),
            required: !0
          }
        ) : null
      ] }) : null,
      m.length ? m.map((e, t) => /* @__PURE__ */ n("div", { className: "adyen-pe-defend-dispute-document-upload-box", children: /* @__PURE__ */ n(
        P,
        {
          mapError: q,
          disabled: c,
          onRemoveOption: G,
          selection: e,
          setSelection: y,
          index: t,
          items: j,
          title: o.get("disputes.management.defend.common.documentTypes.optional"),
          required: !0
        }
      ) }, `optional-doc-${t}`)) : null,
      E && /* @__PURE__ */ n(ie, { align: "center", onClick: W, variant: F.SECONDARY, fullWidth: !0, children: [
        /* @__PURE__ */ n(z, { name: "plus" }),
        o.get("disputes.management.defend.common.actions.addOptionalDocument")
      ] })
    ] }),
    /* @__PURE__ */ n("div", { className: "adyen-pe-defend-file-uploader__actions", children: /* @__PURE__ */ n(X, { actions: Q }) })
  ] }) });
};
export {
  Fe as DefendDisputeFileUpload
};
