import { useState as v, useRef as R, useEffect as C } from "react";
import { useNetwork as E } from "@m4l/core";
import { stringifyJsonFieldsForSubmit as D } from "../../helpers/stringifyJsonFieldsForSubmit/stringifyJsonFieldsForSubmit.js";
import { getFieldTypeApiKey as L } from "../../helpers/getFieldTypeApiKey/getFieldTypeApiKey.js";
function N(P) {
  const {
    formId: g,
    formInstanceId: t,
    inputEndpoint: i,
    outputEndpoint: y,
    submitMode: F = "form",
    formatInputData: w,
    formatOutputData: h,
    onSubmit: c,
    initialData: u
  } = P, { networkOperation: p } = E(), [l, S] = v(u || null), [n, d] = v(
    i ? "edit" : u ? "ready" : "new"
  ), [I, o] = v(!1), s = R(null);
  return C(() => {
    let r = !0;
    if (n === "edit" && i) {
      s.current && s.current.abort(), s.current = new AbortController(), o(!0);
      const f = {};
      t !== void 0 && (f.form_instance_id = t), p({
        method: "GET",
        endPoint: i,
        parms: f,
        timeout: 6e4,
        isRemote: !0,
        responseToCamelCase: !0,
        signal: s.current.signal
      }).then((b) => {
        if (!r)
          return;
        let e = b;
        w && (e = w(e)), S(e), d("reload_values_provider"), o(!1);
      }).catch(() => {
        r && (d("error"), o(!1));
      });
    } else n === "reload_values_provider" ? (d("ready"), o(!1)) : (n === "new" || n === "ready" && l) && o(!1);
    return () => {
      r = !1, s.current && s.current.abort();
    };
  }, [n, i, g, t, w, p, l]), C(() => {
    i || (u ? (S(u), d("ready")) : (S(null), d("new")));
  }, [u, i]), {
    formData: l,
    statusLoad: n,
    handleSubmit: async (r) => {
      const f = t ?? l?.instance?.id, b = F === "perField" && f !== void 0;
      if (!y && !b) {
        c && await c(D(r));
        return;
      }
      o(!0);
      try {
        let e = r;
        if (h && (e = h(r)), e = D(e, !0), b) {
          const m = new Map(
            (l?.fields ?? []).map((a) => [a.name, a])
          );
          await Promise.all(
            Object.entries(e).filter(([a]) => m.has(a)).map(([a, _]) => {
              const T = m.get(a), k = L(T);
              return p({
                method: "PATCH",
                endPoint: `forms/instances/${f}/fields/${T.id}/values`,
                data: { [k]: _ },
                timeout: 6e4,
                isRemote: !0,
                bodyToSnakeCase: !0
              });
            })
          );
        } else {
          let m = y;
          t !== void 0 && (m = `${y}/${t}`), await p({
            method: t !== void 0 ? "PUT" : "POST",
            endPoint: m,
            data: e,
            timeout: 6e4,
            isRemote: !0,
            bodyToSnakeCase: !0
          });
        }
        c && await c(e);
      } finally {
        o(!1);
      }
    },
    isLoading: I
  };
}
export {
  N as useDynamicFormData
};
