import { jsx } from "react/jsx-runtime";
import { useCallback } from "react";
import { DSAutocomplete } from "@elliemae/ds-controlled-form";
import { useFormContext } from "react-hook-form";
const filterOptions = (allOptions, newFilter) => {
  if (!newFilter) return allOptions;
  const filtered = allOptions.filter(
    (option) => option.type === "section" || option.label.toLowerCase().includes(newFilter?.toLowerCase())
  );
  return filtered.length === 1 && filtered[0].type === "section" ? [] : filtered;
};
const Autocomplete = ({ children, ...rest }) => {
  const { watch, setValue } = useFormContext();
  const watchedFilter = watch(rest.name);
  const onSelect = useCallback(
    (newValue, ...otherArgs) => {
      if (rest.onSelect) rest.onSelect(newValue, ...otherArgs);
      else
        setValue(rest.name, newValue, {
          shouldValidate: true,
          shouldDirty: true,
          shouldTouch: true
        });
    },
    [rest, setValue]
  );
  return /* @__PURE__ */ jsx(
    DSAutocomplete,
    {
      id: "",
      filter: watchedFilter ?? "",
      onSelect,
      options: filterOptions(rest.options, watchedFilter),
      children
    }
  );
};
export {
  Autocomplete
};
