import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2022-2026 GoodData Corporation
import { useCallback, useEffect, useMemo, useRef } from "react";
import { invariant } from "ts-invariant";
import { DashboardAttributeFilterConfigModeValues, dashboardAttributeFilterItemDisplayForm, dashboardAttributeFilterItemLocalIdentifier, } from "@gooddata/sdk-model";
import { LoadingSpinner } from "@gooddata/sdk-ui-kit";
import { useTheme } from "@gooddata/sdk-ui-theme-provider";
import { useAttributes } from "../../../../../_staging/sharedHooks/useAttributes.js";
import { useMetricsAndFacts } from "../../../../../_staging/sharedHooks/useMetricsAndFacts.js";
import { useDashboardSelector } from "../../../../../model/react/DashboardStoreProvider.js";
import { selectBackendCapabilities, selectSupportsSingleSelectDependentFilters, } from "../../../../../model/store/backendCapabilities/backendCapabilitiesSelectors.js";
import { selectFilterContextAttributeFilterItems, selectOtherContextAttributeFilterItems, } from "../../../../../model/store/tabs/filterContext/filterContextSelectors.js";
import { ConfigModeSelect } from "../../../configuration/ConfigurationModeSelect.js";
import { AttributeTitleRenaming } from "../../../configuration/title/AttributeTitleRenaming.js";
import { useAttributeFilterParentFiltering } from "../../AttributeFilterParentFilteringContext.js";
import { ConfigurationCategory } from "./ConfigurationCategory.js";
import { ConfigurationPanelHeader } from "./ConfigurationPanelHeader.js";
import { AttributeDisplayFormsDropdown } from "./displayForms/AttributeDisplayFormsDropdown.js";
import { useAvailableDatasetsForItems } from "./hooks/useAvailableDatasetsForItems.js";
import { useConnectingAttributes } from "./hooks/useConnectingAttributes.js";
import { useValidNeighbourAttributes } from "./hooks/useValidNeighbourAttributes.js";
import { LocalizedLimitValuesConfiguration } from "./limitValues/LimitValuesConfiguration.js";
import { ParentFiltersList } from "./parentFilters/ParentFiltersList.js";
import { SelectionMode } from "./selectionMode/SelectionMode.js";
import { SelectionType } from "./selectionType/SelectionType.js";
export function AttributeFilterConfiguration({ filterRef, filterByText, displayValuesAsText, titleText, resetTitleText, selectionTitleText, multiSelectionOptionText, multiSelectionOptionTooltip, singleSelectionOptionText, singleSelectionDisabledTooltip, parentFiltersDisabledTooltip, closeHandler, intl, modeCategoryTitleText, showConfigModeSection, showSelectionTypeSection, selectionTypeAsText, selectionTypeListAndTextText, selectionTypeListAndTextTooltip, selectionTypeListText, selectionTypeListTooltip, selectionTypeTextText, selectionTypeTextTooltip, selectionTypeSingleDisabledTooltip, }) {
    const theme = useTheme();
    useEffect(() => {
        return () => {
            closeHandler();
        };
    }, [closeHandler]);
    const neighborFilters = useDashboardSelector(selectOtherContextAttributeFilterItems(filterRef));
    const supportsSingleSelectDependentFilters = useDashboardSelector(selectSupportsSingleSelectDependentFilters);
    const capabilities = useDashboardSelector(selectBackendCapabilities);
    const showDependentFiltersConfiguration = !capabilities.supportsAttributeFilterElementsLimiting;
    const neighborFilterDisplayForms = useMemo(() => {
        return neighborFilters.map((filter) => dashboardAttributeFilterItemDisplayForm(filter));
    }, [neighborFilters]);
    const currentFilterItem = useDashboardSelector(selectFilterContextAttributeFilterItems).find((filter) => neighborFilters.every((neighborFilter) => dashboardAttributeFilterItemLocalIdentifier(filter) !==
        dashboardAttributeFilterItemLocalIdentifier(neighborFilter)));
    invariant(currentFilterItem, "Cannot find current filter in the filter context store.");
    const { title, defaultAttributeFilterTitle, parents, onParentSelect, onConnectingAttributeChanged, showDisplayFormPicker, filterDisplayForms, onDisplayFormSelect, showResetTitle, onTitleUpdate, onTitleReset, selectionMode, onSelectionModeUpdate, mode, onModeUpdate, selectionType, onSelectionTypeUpdate, limitingItems, onLimitingItemsUpdate, availableDatasetsForFilter, dependentDateFilters, dependentCommonDateFilter, onDependentDateFiltersSelect, } = useAttributeFilterParentFiltering();
    const disableParentFiltersList = selectionMode === "single" && !supportsSingleSelectDependentFilters;
    const { connectingAttributesLoading, connectingAttributes } = useConnectingAttributes(dashboardAttributeFilterItemDisplayForm(currentFilterItem), neighborFilterDisplayForms);
    const { availableDatasetsForItemsLoading, availableDatasetForItems } = useAvailableDatasetsForItems(availableDatasetsForFilter);
    const { validNeighbourAttributesLoading, validNeighbourAttributes } = useValidNeighbourAttributes(filterDisplayForms.selectedDisplayForm, neighborFilterDisplayForms);
    const { attributes, attributesLoading } = useAttributes(neighborFilterDisplayForms);
    const { metricsAndFacts, metricsAndFactsLoading } = useMetricsAndFacts();
    const getIsSelectionDisabled = useCallback(() => {
        if (supportsSingleSelectDependentFilters) {
            return false;
        }
        return parents.filter((parent) => parent.isSelected).length > 0;
    }, [parents, supportsSingleSelectDependentFilters]);
    /** Preserves selection type across a temporary switch to single mode (single mode forces "list"). */
    const selectionTypeBeforeSingleModeRef = useRef(null);
    const handleSelectionModeChange = useCallback((value) => {
        onSelectionModeUpdate(value);
        if (value === "single") {
            selectionTypeBeforeSingleModeRef.current = selectionType;
            onSelectionTypeUpdate("list");
        }
        else if (value === "multi") {
            const previousSelectionType = selectionTypeBeforeSingleModeRef.current;
            selectionTypeBeforeSingleModeRef.current = null;
            if (previousSelectionType !== null) {
                onSelectionTypeUpdate(previousSelectionType);
            }
        }
    }, [onSelectionModeUpdate, onSelectionTypeUpdate, selectionType]);
    if (connectingAttributesLoading ||
        attributesLoading ||
        validNeighbourAttributesLoading ||
        metricsAndFactsLoading ||
        availableDatasetsForItemsLoading) {
        return (_jsx("div", { className: "gd-loading-equalizer-attribute-filter-config-wrap", children: _jsx(LoadingSpinner, { className: "large gd-loading-equalizer-spinner", color: theme?.palette?.complementary?.c9 }) }));
    }
    if (!filterRef ||
        !connectingAttributes ||
        !validNeighbourAttributes ||
        !attributes ||
        !availableDatasetForItems) {
        return null;
    }
    const handleModeChanged = (value) => {
        onModeUpdate(value);
    };
    return (_jsxs("div", { className: "s-attribute-filter-dropdown-configuration attribute-filter-dropdown-configuration sdk-edit-mode-on", children: [
            _jsx(ConfigurationPanelHeader, {}), _jsx(AttributeTitleRenaming, { categoryTitle: titleText, resetTitleText: resetTitleText, onClick: onTitleReset, onChange: onTitleUpdate, showResetTitle: showResetTitle, attributeTitle: title ?? defaultAttributeFilterTitle }), _jsx(SelectionMode, { selectionTitleText: selectionTitleText, multiSelectionOptionText: multiSelectionOptionText, multiSelectionOptionTooltip: multiSelectionOptionTooltip, singleSelectionOptionText: singleSelectionOptionText, singleSelectionDisabledTooltip: singleSelectionDisabledTooltip, selectionMode: selectionMode, onSelectionModeChange: handleSelectionModeChange, disabled: getIsSelectionDisabled() }), showSelectionTypeSection ? (_jsx(SelectionType, { asLabelText: selectionTypeAsText, listOrTextOptionText: selectionTypeListAndTextText, listOrTextTooltip: selectionTypeListAndTextTooltip, listOptionText: selectionTypeListText, listTooltip: selectionTypeListTooltip, textOptionText: selectionTypeTextText, textTooltip: selectionTypeTextTooltip, selectionType: selectionType, onSelectionTypeChange: onSelectionTypeUpdate, isSingleSelectionMode: selectionMode === "single", singleSelectionDisabledTooltip: selectionTypeSingleDisabledTooltip })) : null, _jsx(LocalizedLimitValuesConfiguration, { attributeTitle: title ?? defaultAttributeFilterTitle, parentFilters: parents, validParentFilters: validNeighbourAttributes, validateElementsBy: limitingItems, onLimitingItemUpdate: onLimitingItemsUpdate, onParentFilterUpdate: onParentSelect, onDependentDateFilterUpdate: onDependentDateFiltersSelect, metricsAndFacts: metricsAndFacts, intl: intl, availableDatasets: availableDatasetForItems, dependentDateFilters: dependentDateFilters, dependentCommonDateFilter: dependentCommonDateFilter }), showDependentFiltersConfiguration && parents.length > 0 ? (_jsxs(_Fragment, { children: [
                    _jsx(ConfigurationCategory, { categoryTitle: filterByText }), _jsx(ParentFiltersList, { currentFilterLocalId: dashboardAttributeFilterItemLocalIdentifier(currentFilterItem), parents: parents, setParents: onParentSelect, onConnectingAttributeChanged: onConnectingAttributeChanged, connectingAttributes: connectingAttributes, attributes: attributes, disabled: disableParentFiltersList, disabledTooltip: parentFiltersDisabledTooltip, validParents: validNeighbourAttributes })
                ] })) : null, showDisplayFormPicker ? (_jsxs("div", { className: "s-display-form-configuration", children: [
                    _jsx(ConfigurationCategory, { categoryTitle: displayValuesAsText }), _jsx("div", { className: "configuration-panel-body", children: _jsx(AttributeDisplayFormsDropdown, { displayForms: filterDisplayForms.availableDisplayForms, selectedDisplayForm: filterDisplayForms.selectedDisplayForm, onChange: onDisplayFormSelect }) })
                ] })) : null, showConfigModeSection ? (_jsxs(_Fragment, { children: [
                    _jsx(ConfigurationCategory, { categoryTitle: modeCategoryTitleText }), _jsx(ConfigModeSelect, { intl: intl, selectedMode: mode ?? DashboardAttributeFilterConfigModeValues.ACTIVE, onChanged: handleModeChanged })
                ] })) : null] }));
}
