import { useState as f, useRef as m, useEffect as O } from "react";
import { useNetwork as S } from "@m4l/core";
import { normalizeOptionsResponse as w } from "./normalizeOptionsResponse.js";
const E = /* @__PURE__ */ new Set(["RHFSelect", "RHFCheckableList", "RHFRadioGroup"]);
function T(i) {
  const { fieldType: n, options: s, endpoint: c } = i;
  return !E.has(n.componentId) || !c ? !1 : !s?.length;
}
function k(i) {
  const { fields: n } = i, { networkOperation: s } = S(), [c, a] = f({}), [g, p] = f(0), d = m(/* @__PURE__ */ new Map()), u = m(/* @__PURE__ */ new Set()), l = n.map((t) => t.id).join(",");
  return O(() => {
    const t = n.filter(
      (e) => T(e) && !u.current.has(e.id)
    );
    if (t.length === 0)
      return;
    t.forEach((e) => u.current.add(e.id)), p((e) => e + t.length), t.forEach((e) => {
      const h = new AbortController();
      d.current.set(e.id, h);
      const F = { ...e.endpointParams ?? {} };
      s({
        method: "GET",
        endPoint: e.endpoint,
        parms: F,
        timeout: 3e4,
        isRemote: !0,
        responseToCamelCase: !0,
        signal: h.signal
      }).then((r) => {
        const R = w(r);
        a((C) => ({ ...C, [e.id]: R }));
      }).catch(() => {
        a((r) => ({ ...r, [e.id]: [] }));
      }).finally(() => {
        p((r) => Math.max(0, r - 1)), d.current.delete(e.id);
      });
    });
    const o = d.current;
    return () => {
      t.forEach((e) => {
        o.get(e.id)?.abort(), o.delete(e.id);
      });
    };
  }, [l, n, s]), O(() => {
    u.current.clear(), a({});
  }, [l]), {
    fields: n.map((t) => {
      const o = c[t.id];
      return o === void 0 ? t : { ...t, options: o };
    }),
    isLoadingOptions: g > 0
  };
}
export {
  k as useFieldsWithFetchedOptions
};
