import { jsx as P } from "@emotion/react/jsx-runtime";
import S from "lodash-es/debounce";
import { useRef as b, useReducer as L, useCallback as s, useMemo as Y, useEffect as _ } from "react";
import { actionsType as i } from "./types.js";
import { autocompleteAsyncReducer as j, getInitialStateAutocompleteAsync as x } from "./reducer/AutocompleteAsyncReducer.js";
import { useFetchOptions as N } from "./hooks/useFetchOptions.js";
import { ASYNC_ONLY_KEYS as T } from "./constants.js";
import { AutocompleteAsyncRootStyled as I } from "./slots/AutocompleteAsyncSlots.js";
function q(l) {
  const {
    endPoint: p,
    timeout: u = 5e3,
    parms: a,
    resultField: f = "data",
    isRemote: d = !0,
    isExternalUrl: h = !1,
    onChangeFilterParms: t,
    responseToCamelCase: y,
    multiple: C,
    shouldFetch: o
  } = l, m = b(""), E = Object.fromEntries(
    Object.entries(l).filter(([e]) => !T.includes(e))
  ), [c, n] = L(
    j(t),
    x({ parms: a, onChangeFilterParms: t })
  );
  if (C && t)
    throw new Error(
      "multiple cannot be enabled when onChangeFilterParms is defined; define the filter in parms if needed."
    );
  N({
    state: c,
    dispatch: n,
    endPoint: p,
    timeout: u,
    isExternalUrl: h,
    parms: a,
    responseToCamelCase: y,
    isRemote: d,
    resultField: f
  });
  const F = s(() => n({ type: i.REFRESH }), []), A = s(() => {
    const e = !o || o(m.current);
    n({ type: i.OPEN, noFetch: !e });
  }, [o]), R = s(() => n({ type: i.CLOSE }), []), r = Y(
    () => S(
      (e) => {
        n({
          type: i.SET_QUERY_PARAMS,
          payload: e
        });
      },
      300,
      { trailing: !0 }
    ),
    [n]
  );
  _(
    () => () => {
      r.cancel();
    },
    [r]
  );
  const g = s(
    (e, O) => {
      m.current = e, t && O === "input" && (!o || o(e)) && r(t(e));
    },
    [t, r, o]
  );
  return /* @__PURE__ */ P(
    I,
    {
      ...E,
      loading: c.loading,
      options: c.options,
      onChangeFilterParmsLocal: t ? g : void 0,
      refresh: F,
      onOpen: A,
      onClose: R
    }
  );
}
export {
  q as AutocompleteAsync
};
