import { useModuleDictionary as w } from "@m4l/core";
import { useRef as R, useMemo as C, useCallback as S } from "react";
import { shallow as E } from "zustand/shallow";
import { useDynamicSortStore as d } from "../../store/useDynamicSortStore.js";
import { fieldFactory as u } from "../FieldTypes/fieldFactory.js";
function _() {
  let n, t, l, r, i;
  const { getLabel: a } = w(), o = d((e) => e.popoverSortData, E), { hidePopoverSort: s, addSort: F, updateSort: h, getNewId: v } = d(
    (e) => e.actions
  ), f = d((e) => e.actions.getElementRef()), p = R(o), g = C(() => {
    let e;
    return o && p.current === void 0 ? e = "ready" : o ? e = "reload_values_provider" : e = "initial", p.current = o, e;
  }, [o]);
  if (o?.openFor === "add") {
    n = f?.current, t = o.field;
    const e = u();
    i = e.getSchema(a), r = e.getFormValue(t, a), l = {
      field: t,
      id: v(),
      isSet: !0,
      fixed: !1,
      ...r
    };
  } else if (o) {
    n = f?.current, t = o?.sort.field;
    const e = u();
    i = e.getSchema(a), r = e.getFormValue(t, a, o.sort), l = { ...o?.sort, ...r };
  } else
    r = {}, t = {}, l = {}, n = {};
  const c = S(() => {
    s(!1);
  }, [s]), y = S((e) => {
    e.key === "Escape" && c();
  }, [c]);
  function D() {
    s(!1);
  }
  async function P(e) {
    const V = { ...r, ...e }, m = {
      ...l,
      // todo: mejorar el tipado que se le envía a getSortFromFormValue
      ...u().getSortFromFormValue(V),
      isSet: !0
    };
    o?.openFor === "add" ? F(m) : h(m), s(!1);
  }
  const b = t?.label ?? a(t?.dictionaryId ?? "");
  return {
    field: t,
    labelField: b,
    canRender: !!o,
    anchorEl: n,
    handleKeyDownPopper: y,
    handleClosePopover: D,
    onSubmit: P,
    onClose: c,
    sortFormValue: r,
    formSort: l,
    popupValidationSchema: i,
    statusLoad: g
  };
}
export {
  _ as default
};
