import { useState as E, useRef as u, useEffect as _, useCallback as o } from "react";
import { useFormContext as w, useWatch as T } from "react-hook-form";
import { parseWatchedValues as A } from "../../helpers/parseWatchedValues/index.js";
import { getInitialFieldValues as C } from "../../helpers/getInitialFieldValues/index.js";
function O() {
  const { trigger: d, getValues: f, clearErrors: m } = w(), [e, V] = E([]), [a, g] = E(!1), h = T({
    name: "statusLoad"
  }), p = T({
    name: e.length > 0 ? e : ["__dummy__"]
  }), s = u({}), i = u(/* @__PURE__ */ new Set()), r = u(null);
  _(() => {
    if (e.length === 0 || h !== "ready" || a)
      return;
    const c = A(p, e), l = e.filter((t) => {
      const n = c[t], y = s.current[t], F = JSON.stringify(n) !== JSON.stringify(y);
      return F && (s.current[t] = n), F;
    });
    l.length > 0 && (l.forEach((t) => i.current.add(t)), r.current && clearTimeout(r.current), r.current = setTimeout(async () => {
      const t = Array.from(i.current);
      i.current.clear(), r.current = null;
      for (const n of t)
        await d(n) && m(n);
    }, 150));
  }, [
    e,
    d,
    m,
    p,
    h,
    a
  ]);
  const v = o(() => {
    g(!0);
  }, []), x = o(() => {
    g(!1);
  }, []), R = o(
    (c, l = !0) => {
      if (l && a)
        return;
      const t = f();
      V(c);
      const n = C(t, c);
      s.current = n;
    },
    [f, a]
  ), S = o(() => {
    V([]), s.current = {}, i.current.clear(), r.current && (clearTimeout(r.current), r.current = null);
  }, []);
  return {
    activateFieldsValidation: R,
    clearAllValidation: S,
    activeFields: e,
    startExternalValidation: v,
    endExternalValidation: x
  };
}
export {
  O as useDynamicValidation
};
