import {
  filterOptions
} from "./chunk-2JLZNSLY.js";

// src/components/Combobox/useComboboxOptions.ts
import { useDebouncedValue } from "@simplybusiness/mobius-hooks";
import { useEffect, useRef, useState } from "react";
function useComboboxOptions({
  options,
  asyncOptions,
  delay = 300,
  minSearchLength = 3,
  inputValue = "",
  skipNextDebounceRef,
  onSearched
}) {
  const [filteredOptions, setFilteredOptions] = useState(void 0);
  const debouncedInputValue = useDebouncedValue(
    inputValue,
    // Don't debounce synchronous options
    options ? 0 : delay
  );
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const asyncOptionsRef = useRef(asyncOptions);
  asyncOptionsRef.current = asyncOptions;
  const onSearchedRef = useRef(onSearched);
  onSearchedRef.current = onSearched;
  useEffect(() => {
    const controller = new AbortController();
    const { signal } = controller;
    const fetchOptions = async () => {
      setIsLoading(true);
      setError(null);
      try {
        if (asyncOptionsRef.current) {
          if (debouncedInputValue.length < minSearchLength) {
            setFilteredOptions(void 0);
            return;
          }
          const result = await asyncOptionsRef.current(debouncedInputValue, {
            signal
          });
          setFilteredOptions(result);
          onSearchedRef.current?.(debouncedInputValue);
        } else if (options) {
          setFilteredOptions(filterOptions(options, debouncedInputValue));
        } else {
          setError(new Error("No options provided"));
        }
      } catch (e) {
        if (e instanceof DOMException && e.name === "AbortError") {
          return;
        }
        setError(e);
      } finally {
        setIsLoading(false);
      }
    };
    if (!skipNextDebounceRef?.current) {
      void fetchOptions();
    } else {
      skipNextDebounceRef.current = false;
    }
    return () => {
      controller.abort();
    };
  }, [
    debouncedInputValue,
    options,
    delay,
    minSearchLength,
    skipNextDebounceRef
  ]);
  function updateFilteredOptions(newOptions) {
    setIsLoading(true);
    return newOptions.then(setFilteredOptions).catch(setError).finally(() => setIsLoading(false));
  }
  return {
    filteredOptions,
    updateFilteredOptions,
    isLoading,
    error,
    isError: error != null
  };
}

export {
  useComboboxOptions
};
//# sourceMappingURL=chunk-GU5OMKTM.js.map
