import { useMemo, useState, useEffect, useRef, useCallback } from "react";
import Fuse from "fuse.js";
import { useDebounce } from "../hooks/useDebounce";
export function useSearch({ list, options, defaultInput = "", filter, }) {
    const inputRef = useRef(null);
    const [isActive, setIsActive] = useState(false);
    const [input, setInput] = useState(defaultInput);
    const debouncedInput = useDebounce(input, 500);
    const [isSearching, setIsSearching] = useState(false);
    const [result, setResult] = useState(list);
    const fuse = useRef(new Fuse(list, options));
    const onChange = useCallback((value) => {
        if (value.length !== 0) {
            setIsSearching(true);
        }
        setInput(value);
    }, []);
    useEffect(() => {
        if (debouncedInput && fuse.current) {
            setIsSearching(true);
            setResult(fuse.current.search(debouncedInput).map(res => res.item));
        }
        else {
            setResult([]);
        }
        setIsSearching(false);
    }, [debouncedInput]);
    const onFocus = useCallback(() => {
        setIsActive(true);
    }, []);
    useEffect(() => {
        if (isActive) {
            inputRef.current?.focus();
        }
    }, [isActive]);
    const onCancel = useCallback(() => {
        setInput("");
        setIsActive(false);
        inputRef.current?.blur();
    }, []);
    const resultOut = useMemo(() => {
        const res = input === "" ? list : result;
        return filter ? res.filter(item => filter(item, input)) : res;
    }, [list, result, input, filter]);
    return {
        inputRef,
        input,
        result: resultOut,
        isActive,
        isSearching,
        onChange,
        onFocus,
        onCancel,
    };
}
//# sourceMappingURL=useSearch.js.map