import { jsx as _jsx } from "react/jsx-runtime";
// (C) 2019-2026 GoodData Corporation
import { useRef } from "react";
import cx from "classnames";
import { useIntl } from "react-intl";
import { Dropdown, DropdownButton, SingleSelectListItem, UiListbox, } from "@gooddata/sdk-ui-kit";
import { getMeasureTitle } from "../utils/getters.js";
const measureIcon = _jsx("div", { className: "gd-alert-measure-select__icon gd-icon-metric" });
export function AlertMeasureSelect({ id, disabled, selectedMeasure, onMeasureChange, measures, overlayPositionType, closeOnParentScroll, }) {
    const intl = useIntl();
    const ref = useRef(null);
    const selectedMeasureTitle = selectedMeasure
        ? getMeasureTitle(selectedMeasure.measure)
        : intl.formatMessage({ id: "insightAlert.config.selectMetric" });
    return (_jsx(Dropdown, { closeOnParentScroll: closeOnParentScroll, overlayPositionType: overlayPositionType, autofocusOnOpen: true, renderButton: ({ isOpen, toggleDropdown, buttonRef, dropdownId }) => {
            return (_jsx("div", { ref: (item) => {
                    ref.current = item;
                }, children: _jsx(DropdownButton, { id: id, disabled: disabled, className: cx("gd-alert-measure-select__button s-alert-measure-select"), value: selectedMeasureTitle, iconLeft: selectedMeasure ? "gd-icon-metric" : undefined, onClick: toggleDropdown, buttonRef: buttonRef, dropdownId: dropdownId, isOpen: isOpen, accessibilityConfig: {
                        ariaExpanded: isOpen,
                        popupType: "listbox",
                    } }) }));
        }, renderBody: ({ closeDropdown, ariaAttributes }) => {
            const listboxItems = measures.map((measure, index) => ({
                type: "interactive",
                id: `measure-${index}`,
                stringTitle: getMeasureTitle(measure.measure) ?? "",
                data: measure,
            }));
            const selectedIndex = measures.findIndex((m) => m.measure === selectedMeasure?.measure);
            const selectedId = selectedIndex === -1 ? undefined : `measure-${selectedIndex}`;
            return (_jsx(UiListbox, { shouldKeyboardActionStopPropagation: true, shouldKeyboardActionPreventDefault: true, dataTestId: "s-alert-measure-select-list", items: listboxItems, maxWidth: ref.current?.offsetWidth, selectedItemId: selectedId, onSelect: (item) => {
                    onMeasureChange(item.data);
                }, onClose: closeDropdown, ariaAttributes: ariaAttributes, InteractiveItemComponent: ({ item, isSelected, onSelect, isFocused }) => {
                    return (_jsx(SingleSelectListItem, { icon: measureIcon, title: item.stringTitle, isSelected: isSelected, isFocused: isFocused, onClick: onSelect, className: "gd-alert-measure-select__list-item" }));
                } }));
        } }));
}
