import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2019-2026 GoodData Corporation
import { useCallback, useMemo } from "react";
import cx from "classnames";
import { FormattedMessage, useIntl } from "react-intl";
import { areObjRefsEqual, } from "@gooddata/sdk-model";
import { Dropdown, DropdownButton, UiMenu, } from "@gooddata/sdk-ui-kit";
import { getSelectedCatalogAttribute, getSelectedCatalogAttributeValue } from "../utils/getters.js";
const createInteractiveItem = (id, title, attribute, value, isSelected, subItems) => ({
    type: "interactive",
    id,
    stringTitle: title,
    isSelected,
    data: {
        attribute,
        value,
        isSelected,
    },
    ...(subItems && { subItems }),
});
const createSeparator = (id) => ({
    type: "static",
    id,
    data: {},
});
function CustomStaticItem({ item: _item }) {
    return _jsx("div", { className: "gd-alert-attribute-select__dropdown-separator" });
}
export function AlertAttributeSelect({ id, selectedAttribute: selectedAttributeProp, getAttributeValues, isResultLoading, selectedValue, onAttributeChange, attributes, catalogAttributes, catalogDateDatasets, showLabel = true, closeOnParentScroll, }) {
    const intl = useIntl();
    const availableAttributes = useMemo(() => {
        return attributes.filter((attr) => attr.type === "attribute");
    }, [attributes]);
    const selectedAttribute = useMemo(() => {
        return (selectedAttributeProp &&
            getSelectedCatalogAttribute(catalogAttributes, catalogDateDatasets, selectedAttributeProp));
    }, [selectedAttributeProp, catalogAttributes, catalogDateDatasets]);
    const selectedAttributeValue = useMemo(() => getSelectedCatalogAttributeValue(selectedAttribute, getAttributeValues, selectedValue), [selectedAttribute, getAttributeValues, selectedValue]);
    const accessibilityAriaLabel = intl.formatMessage({ id: "insightAlert.config.selectAttribute" });
    const uiMenuItems = useMemo(() => {
        // Create menu items based on available attributes
        const attributeItems = [];
        for (const attribute of availableAttributes) {
            const item = getSelectedCatalogAttribute(catalogAttributes, catalogDateDatasets, attribute);
            if (!item) {
                continue;
            }
            const values = getAttributeValues(item);
            const hasDisplayForm = selectedAttribute?.displayForms.some((df) => areObjRefsEqual(df.ref, attribute.attribute.attribute.displayForm));
            // Create sub-items for attribute values
            const subItems = [
                // "All" option
                createInteractiveItem(`all-${item.id}`, `${accessibilityAriaLabel} (${values.length})`, attribute, undefined, Boolean(hasDisplayForm && !selectedAttributeValue)),
                // Separator after All option
                createSeparator(`separator-${item.id}`),
            ];
            // Add individual value items
            for (const value of values) {
                subItems.push(createInteractiveItem(`value-${value.value}`, (value.title ?? value.name) || intl.formatMessage({ id: "empty_value" }), attribute, value, Boolean(hasDisplayForm && selectedAttributeValue?.value === value.value)));
            }
            // Check if any child is selected to determine parent selection state
            const hasSelectedChild = subItems.some((item) => item.type === "interactive" && "isSelected" in item && item.isSelected);
            // Create attribute item with submenu
            attributeItems.push(createInteractiveItem(`attribute-${item.id}`, item.title || intl.formatMessage({ id: "empty_value" }), attribute, undefined, Boolean((selectedAttribute &&
                areObjRefsEqual(selectedAttribute.ref, attribute.attribute.attribute.displayForm)) ||
                hasSelectedChild), subItems));
        }
        // Create the full menu items array
        return [
            // "Select Attribute" option
            createInteractiveItem("clear", accessibilityAriaLabel, undefined, undefined, Boolean(!selectedAttribute && !selectedAttributeValue)),
            // Separator
            createSeparator("top-separator"),
            // Attribute items
            ...attributeItems,
        ];
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [
        availableAttributes,
        catalogAttributes,
        catalogDateDatasets,
        getAttributeValues,
        intl,
        selectedAttribute,
        selectedAttributeValue,
    ]);
    const handleUiMenuSelect = useCallback((item) => {
        onAttributeChange(item.data.attribute, item.data.value);
    }, [onAttributeChange]);
    // if there are no attributes, return null
    if (availableAttributes.length === 0) {
        return null;
    }
    return (_jsxs(_Fragment, { children: [showLabel ? (_jsx("label", { htmlFor: id, className: "gd-edit-alert__measure-label", children: _jsx(FormattedMessage, { id: "insightAlert.config.for" }) })) : null, _jsx("div", { className: "gd-alert-attribute-select", children: _jsx(Dropdown, { autofocusOnOpen: true, closeOnParentScroll: closeOnParentScroll, renderButton: ({ isOpen, toggleDropdown, buttonRef, dropdownId }) => {
                        const buttonValue = selectedAttribute
                            ? `${selectedAttribute?.title} / ${selectedAttributeValue
                                ? (selectedAttributeValue.title ?? selectedAttributeValue.name) ||
                                    `(${intl.formatMessage({ id: "empty_value" })})`
                                : accessibilityAriaLabel}`
                            : accessibilityAriaLabel;
                        return (_jsx(DropdownButton, { id: id, className: cx("gd-alert-attribute-select__button", {
                                "is-active": isOpen,
                            }), value: buttonValue, iconLeft: "gd-icon-attribute", onClick: () => {
                                if (!isResultLoading) {
                                    toggleDropdown();
                                }
                            }, disabled: isResultLoading, buttonRef: buttonRef, dropdownId: dropdownId, isOpen: isOpen, accessibilityConfig: {
                                ariaExpanded: isOpen,
                                popupType: "menu",
                            } }));
                    }, renderBody: ({ closeDropdown, ariaAttributes }) => (_jsx(UiMenu, { items: uiMenuItems, onSelect: (item) => {
                            handleUiMenuSelect(item);
                        }, shouldCloseOnSelect: true, onClose: closeDropdown, StaticItem: CustomStaticItem, ariaAttributes: ariaAttributes, dataTestId: "s-alert-attribute-select-list", size: "small" })), alignPoints: [{ align: "bl tl" }] }) })
        ] }));
}
//# sourceMappingURL=AlertAttributeSelect.js.map