import { useMemo as p } from "react";
import { EMPTY_DATA as h } from "../../constants.js";
import { createValidationPartialObject as b, createValidationSchema as g, createValidationFullObject as A } from "../../../hook-form/RHFormProvider/schema.js";
import { useModuleDictionary as N } from "@m4l/core";
import { resolveInitialValue as T } from "../../helpers/resolveInitialValue/resolveInitialValue.js";
import { createFieldValidationSchema as w } from "../../helpers/createFieldValidationSchema/createFieldValidationSchema.js";
import { evaluateConditionalRule as f } from "../../helpers/evaluateConditionalRule/evaluateConditionalRule.js";
function P(c) {
  const n = c.fields ?? h.fields, m = c.conditionalRules ?? h.conditionalRules, { getLabel: l } = N(), d = p(() => {
    const a = {};
    return n.forEach((o) => {
      o.isVisible !== !1 && typeof o.name == "string" && o.name.trim() !== "" && (a[o.name] = T(o));
    }), a;
  }, [n]), y = p(() => {
    const a = b({});
    return n.forEach((o) => {
      if (typeof o.name != "string" || o.name.trim() === "")
        return;
      const i = w(o, l);
      if (!i)
        return;
      const F = !o.isConditional && o.isVisible !== !1;
      if (o.isConditional === !1) {
        a[o.name] = F ? i : i.optional();
        return;
      }
      const u = m.filter(
        (e) => e.isActive && e.targetFieldName === o.name
      ), r = [...new Set(u.map((e) => e.sourceFieldName))];
      if (r.length === 0) {
        a[o.name] = i.optional();
        return;
      }
      const V = i.when(
        r,
        {
          /** Returns true when the field is visible (any show rule met or any hide rule not met). */
          is: (e) => {
            const v = Array.isArray(e) ? e : [e], s = {};
            return r.forEach((t, S) => {
              s[t] = v[S];
            }), u.some(
              (t) => t.actionType === "show" && f(t, s[t.sourceFieldName]) || t.actionType === "hide" && !f(t, s[t.sourceFieldName])
            );
          },
          then: (e) => e,
          otherwise: (e) => e.optional()
        }
      );
      a[o.name] = V;
    }), g(A(a));
  }, [n, m, l]);
  return {
    initialValues: d,
    validationSchema: y
  };
}
export {
  P as useDynamicForm
};
