import { useState as A, useRef as O, useEffect as w, useCallback as f } from "react";
import { deepEqual as E } from "fast-equals";
function J(q) {
  const {
    getOptionLabel: C,
    isOptionEqualToValue: L,
    options: d = [],
    onOpen: m,
    onClose: D,
    onChangeFilterParmsLocal: u,
    multiple: l,
    refresh: K,
    onChange: h,
    value: n,
    readOnly: o
  } = q, [g, v] = A(!1), [c, p] = A(""), R = O(0), P = n ?? (l ? [] : null), [s, V] = A(P), b = O(s), k = O(P);
  w(() => {
    const t = n ?? (l ? [] : null);
    if (E(b.current, t) || (b.current = t, E(s, t)))
      return;
    V(t), (t === null || Array.isArray(t) && t.length === 0) && p("");
  }, [l, n, s]);
  const y = f(
    (e, t) => t == null ? !1 : L(e, t),
    [L]
  ), i = f(
    (e) => typeof e == "string" ? e : e == null ? "" : C(e),
    [C]
  );
  w(() => {
    const e = n ?? (l ? [] : null);
    E(k.current, e) || (k.current = e, !g && u && (n == null ? u("", "reset") : d.length === 0 && u(i(n), "reset")));
  }, [n, g, l, d.length, u, i]);
  const T = f((e) => {
    if (!o && Array.isArray(s)) {
      const t = s.filter(
        (r) => !y(r, e)
      );
      V(t), h?.(
        { target: { value: t } },
        t,
        "removeOption"
      );
    }
  }, [s, y, h, o]), z = f(() => {
    K?.(), v(!0);
  }, [K]), F = (e, t, r) => {
    let a = l ? Array.isArray(t) ? t : [] : t;
    l && Array.isArray(a) && (a = a?.filter((x) => d.some((N) => y(N, x)))), V(a), h?.(
      { target: { value: a } },
      a,
      r
    );
  }, H = (e, t, r) => {
    o || (p(t), u && r === "input" && u(t, r));
  }, I = (e, t) => {
    let r = !0;
    t !== "selectOption" && t !== "removeOption" || l && (r = !1), r && (R.current = 0, v(!1), D && D({ type: e.type }, t));
  }, U = f((e) => {
    o || (v((t) => !t), m && m({ type: e.type }));
  }, [m, o]);
  return w(() => {
    if (o && n !== null && n !== void 0 && !l) {
      const e = i(n);
      c !== e && p(e);
    } else o && l && c !== "" && p("");
  }, [o, n, i, l, c]), {
    open: g,
    inputValue: c,
    selectedValue: s,
    isOptionEqualToValueLocal: y,
    handleDelete: T,
    handleRefresh: z,
    handleChange: F,
    handleInputChange: H,
    onCloseLocal: I,
    onOpenLocal: U,
    getOptionLabelLocal: i,
    checkKeyDown: (e) => {
      e.code === "Enter" && e.preventDefault(), o && ![
        "Tab",
        "Escape",
        "ArrowUp",
        "ArrowDown",
        "ArrowLeft",
        "ArrowRight",
        "Home",
        "End",
        "PageUp",
        "PageDown"
      ].includes(e.key) && !e.ctrlKey && !e.metaKey && e.preventDefault();
    },
    scrollPositionOptionsRef: R
  };
}
export {
  J as useValuesAndHandlers
};
