import { useCallback as w, useMemo as E } from "react";
import { useFormContext as O } from "react-hook-form";
import { useStepper as h } from "../../../hooks/useStepper/index.js";
import { useDynamicValidation as D } from "../../../hooks/useDynamicValidation/index.js";
import { focusFirstErrorField as b } from "../../../helpers/focusFirstErrorField/index.js";
import { deepShallow as A } from "../../../../../utils/deepShallow.js";
function H(I) {
  const { visibleSteps: r } = I, { trigger: u, clearErrors: S, setFocus: f, getFieldState: m } = O(), {
    activateFieldsValidation: F,
    startExternalValidation: k,
    endExternalValidation: y
  } = D(), {
    currentStep: p,
    steps: n,
    visibleTitle: v,
    setCurrentStep: c,
    orientation: g,
    setStepValidationStatus: s,
    stepValidationStatus: x
  } = h(
    (t) => ({
      currentStep: t.currentStep,
      steps: t.steps,
      visibleTitle: t.visibleTitle,
      setCurrentStep: t.actions.setCurrentStep,
      indicatorType: t.indicatorType,
      orientation: t.orientation,
      setStepValidationStatus: t.actions.setStepValidationStatus,
      stepValidationStatus: t.stepValidationStatus
    }),
    A
  ), C = w(async (t) => {
    const a = r.findIndex(
      (e) => e.key === n[p].key
    );
    if (t === a)
      return;
    const T = t > a, V = n.findIndex(
      (e) => e.key === r[t].key
    );
    if (!T) {
      c(V);
      return;
    }
    if (t > a + 1)
      for (let e = a; e < t; e++) {
        const i = r[e], o = n.findIndex((d) => d.key === i.key);
        k();
        const l = await u(i.validationFields);
        if (y(), !l) {
          c(o), s(o, !1), F(i.validationFields || []), b(i.validationFields || [], m, f);
          return;
        }
        s(o, !0);
      }
    else {
      const e = r[a], i = n.findIndex(
        (l) => l.key === e.key
      );
      k();
      const o = await u(e.validationFields);
      if (y(), !o) {
        s(i, !1), F(e.validationFields || []), b(e.validationFields || [], m, f);
        return;
      }
      s(i, !0);
    }
    if (c(V), T) {
      const e = r[a], i = n.findIndex(
        (l) => l.key === e.key
      );
      if (x[i] !== !1) {
        const d = r[t].validationFields || [];
        d.length > 0 && (S(d), setTimeout(() => {
          S(d), s(V, !0);
        }, 100));
      }
    }
  }, [r, n, c, p, k, u, y, s, F, x, S, m, f]);
  return E(() => ({
    visibleTitle: v,
    orientation: g,
    handleStepClick: C,
    steps: n,
    currentStep: p
  }), [v, g, C, n, p]);
}
export {
  H as useStepArea
};
