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