import { useReducer } from "react";
import { pathReducer, focusedPathReducer, treePathReducer } from "../reducers";
import { getTextValue } from "../utils";
import { classes } from "../Combobox.tokens";
export const useListState = ({ disabled, readOnly, onToggle, multiple, alwaysOpened, renderValue, rootRef, value, valueToItemMap, setTextValue })=>{
    const [path, dispatchPath] = useReducer(pathReducer, alwaysOpened ? [
        'root'
    ] : []);
    const [treePath, dispatchTreePath] = useReducer(treePathReducer, {});
    const [focusedPath, dispatchFocusedPath] = useReducer(focusedPathReducer, []);
    const resetListState = ()=>{
        dispatchFocusedPath({
            type: 'reset'
        });
        dispatchPath({
            type: 'reset'
        });
        dispatchTreePath({
            type: 'reset'
        });
    };
    const handleListToggle = (opened)=>{
        if (disabled || readOnly) {
            return;
        }
        if (opened) {
            dispatchPath({
                type: 'opened_first_level'
            });
        } else {
            resetListState();
            setTextValue(getTextValue(multiple, value, valueToItemMap, renderValue));
            const chipsWrapperNode = rootRef?.current?.querySelector(`.${classes.inputScrollableWrapper}`);
            if (multiple && chipsWrapperNode) {
                chipsWrapperNode.scrollLeft = 0;
            }
        }
        if (onToggle) {
            onToggle(opened);
        }
    };
    return {
        path,
        treePath,
        focusedPath,
        dispatchPath,
        dispatchTreePath,
        dispatchFocusedPath,
        handleListToggle,
        resetListState,
        isListOpened: Boolean(path[0])
    };
};
