import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { useEditContext } from "../client/editContext";
import { executeSearch } from "../services/searchService";
import { toast } from "sonner";
import { useDebouncedCallback } from "use-debounce";
import { ItemList } from "./ItemList";
import { FilterInput } from "../../components/FilterInput";
import { GUID_REGEX_EXACT } from "../utils";
export const ItemSearch = ({ rootItemIds, setHoveredItem, itemSelected, language, resultClassName, autoFocus = false, disabled = false, database = "master", placeholder = "Search...", }) => {
    const [query, setQuery] = useState("");
    const [results, setResults] = useState([]);
    const [loading, setLoading] = useState(false);
    const editContext = useEditContext();
    const inputRef = useRef(null);
    const handleSearch = useDebouncedCallback(async (searchPrompt) => {
        if (!editContext || disabled)
            return;
        setLoading(true);
        const trimmedPrompt = searchPrompt.trim();
        const currentQuery = searchPrompt;
        // Try a direct GUID lookup first, but fall back to normal search if it doesn't resolve.
        if (GUID_REGEX_EXACT.test(trimmedPrompt)) {
            const normalizedGuid = trimmedPrompt.replace(/[{}()]/g, "");
            const item = await editContext.itemsRepository.getItem({
                id: normalizedGuid,
                language: language || "en",
                version: 0,
            });
            if (item) {
                if (query === currentQuery) {
                    const resultItem = {
                        id: item.id,
                        name: item.name,
                        displayName: item.displayName,
                        language: item.language || language || "en",
                        icon: item.icon,
                        path: item.path || item.name,
                        idPath: item.idPath,
                    };
                    setResults([resultItem]);
                }
                setLoading(false);
                return;
            }
        }
        // Check for item path pattern (starts with /)
        const isPath = trimmedPrompt.startsWith("/");
        // If it looks like a path, search with skipValidation to allow exact path matching
        const result = await executeSearch({
            index: database,
            query: trimmedPrompt,
            editContext,
            rootItemIds,
            maxResults: isPath ? 15 : 15,
            skipValidation: isPath,
        });
        if (query === currentQuery) {
            if (result.type == "success") {
                setResults(() => result.data);
            }
            else {
                toast.error(result.response.statusText || "Error searching");
            }
        }
        setLoading(false);
    }, 600);
    useEffect(() => {
        if (query && !disabled) {
            setLoading(true);
            handleSearch(query);
        }
        else {
            setResults([]);
        }
    }, [query, disabled]);
    useEffect(() => {
        if (inputRef.current && autoFocus) {
            inputRef.current.focus();
        }
    }, []);
    return (_jsxs(_Fragment, { children: [_jsx("div", { className: "relative", children: _jsx(FilterInput, { className: "focus:border-feedback-blue focus:ring-feedback-blue", onChange: setQuery, value: query, ref: inputRef, autoFocus: autoFocus, placeholder: placeholder, loading: loading, disabled: disabled }) }), results.length > 0 && (_jsx(ItemList, { items: results, onItemHover: setHoveredItem, onItemClick: (item) => {
                    itemSelected(item);
                    setResults([]);
                    setQuery("");
                }, maxItems: 15, className: `mt-1 ${resultClassName} max-h-[200px] overflow-y-auto` })), results.length === 0 && !loading && query && (_jsx("div", { "data-slot": "item-search-empty", className: "text-neutral-grey-50 mt-2 mb-2 px-3 text-xs", children: "No results found" }))] }));
};
export default ItemSearch;
//# sourceMappingURL=ItemSearch.js.map