// (C) 2026 GoodData Corporation
import { useCallback, useEffect, useState } from "react";
/**
 * @internal
 */
export function useCatalogItemPickerState({ isOpen, selectionMode, itemTypes, }) {
    const [searchString, setSearchString] = useState("");
    const [selectedIds, setSelectedIds] = useState(new Set());
    const [activeType, setActiveType] = useState(itemTypes[0]);
    useEffect(() => {
        if (!itemTypes.includes(activeType)) {
            setActiveType(itemTypes[0]);
        }
    }, [activeType, itemTypes]);
    useEffect(() => {
        if (!isOpen) {
            setSearchString("");
            setSelectedIds(new Set());
        }
    }, [isOpen]);
    const handleItemSelect = useCallback((id) => {
        if (selectionMode === "single") {
            return;
        }
        setSelectedIds((prev) => {
            const next = new Set(prev);
            if (next.has(id)) {
                next.delete(id);
            }
            else {
                next.add(id);
            }
            return next;
        });
    }, [selectionMode]);
    const handleSearchChange = useCallback((value) => {
        setSearchString(String(value));
    }, []);
    const handleSearchEscKeyPress = useCallback((e) => {
        if (searchString.length > 0) {
            e.stopPropagation();
        }
    }, [searchString]);
    const resetSelection = useCallback(() => {
        setSelectedIds(new Set());
    }, []);
    return {
        searchString,
        selectedIds,
        activeType,
        setActiveType,
        setSelectedIds,
        handleItemSelect,
        handleSearchChange,
        handleSearchEscKeyPress,
        resetSelection,
    };
}
