// (C) 2023-2026 GoodData Corporation
import { useCallback, useState } from "react";
import { setDashboardAttributeFilterConfigMode } from "../../../../../../model/commands/dashboard.js";
import { useDashboardSelector } from "../../../../../../model/react/DashboardStoreProvider.js";
import { useDashboardCommandProcessing } from "../../../../../../model/react/useDashboardCommandProcessing.js";
import { selectAttributeFilterConfigsOverrides } from "../../../../../../model/store/tabs/attributeFilterConfigs/attributeFilterConfigsSelectors.js";
export function useModeConfiguration(currentFilter, defaultAttributeFilterMode) {
    const { run: changeAttributeMode } = useDashboardCommandProcessing({
        commandCreator: setDashboardAttributeFilterConfigMode,
        successEvent: "GDC.DASH/EVT.ATTRIBUTE_FILTER_CONFIG.MODE_CHANGED",
        errorEvent: "GDC.DASH/EVT.COMMAND.FAILED",
    });
    const currentFilterConfig = useDashboardSelector(selectAttributeFilterConfigsOverrides).find((item) => item.localIdentifier === currentFilter.attributeFilter.localIdentifier);
    const currentFilterLocalId = currentFilterConfig?.localIdentifier || currentFilter?.attributeFilter.localIdentifier;
    const originalMode = currentFilterConfig?.mode ?? defaultAttributeFilterMode;
    const [mode, setMode] = useState(originalMode);
    const modeChanged = originalMode !== mode;
    const onModeUpdate = useCallback((value) => {
        setMode(value);
    }, []);
    const onModeChange = useCallback(() => {
        if (mode !== originalMode) {
            changeAttributeMode(currentFilterLocalId, mode);
        }
    }, [currentFilterLocalId, originalMode, changeAttributeMode, mode]);
    const onConfigurationClose = useCallback(() => {
        setMode(originalMode);
    }, [originalMode]);
    return {
        mode,
        modeChanged,
        onModeUpdate,
        onModeChange,
        onConfigurationClose,
    };
}
