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