"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSearch = void 0;
const react_1 = require("react");
const fuse_js_1 = __importDefault(require("fuse.js"));
const useDebounce_1 = require("../hooks/useDebounce");
function useSearch({ list, options, defaultInput = "", filter, }) {
    const inputRef = (0, react_1.useRef)(null);
    const [isActive, setIsActive] = (0, react_1.useState)(false);
    const [input, setInput] = (0, react_1.useState)(defaultInput);
    const debouncedInput = (0, useDebounce_1.useDebounce)(input, 500);
    const [isSearching, setIsSearching] = (0, react_1.useState)(false);
    const [result, setResult] = (0, react_1.useState)(list);
    const fuse = (0, react_1.useRef)(new fuse_js_1.default(list, options));
    const onChange = (0, react_1.useCallback)((value) => {
        if (value.length !== 0) {
            setIsSearching(true);
        }
        setInput(value);
    }, []);
    (0, react_1.useEffect)(() => {
        if (debouncedInput && fuse.current) {
            setIsSearching(true);
            setResult(fuse.current.search(debouncedInput).map(res => res.item));
        }
        else {
            setResult([]);
        }
        setIsSearching(false);
    }, [debouncedInput]);
    const onFocus = (0, react_1.useCallback)(() => {
        setIsActive(true);
    }, []);
    (0, react_1.useEffect)(() => {
        if (isActive) {
            inputRef.current?.focus();
        }
    }, [isActive]);
    const onCancel = (0, react_1.useCallback)(() => {
        setInput("");
        setIsActive(false);
        inputRef.current?.blur();
    }, []);
    const resultOut = (0, react_1.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,
    };
}
exports.useSearch = useSearch;
//# sourceMappingURL=useSearch.js.map