import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2022-2026 GoodData Corporation
import { useCallback, useEffect, useRef, useState } from "react";
import cx from "classnames";
import { isAttributeAreaSort, isMeasureLocator, isMeasureSort, newAttributeAreaSort, newMeasureSort, objRefToString, sortDirection, } from "@gooddata/sdk-model";
import { simplifyText } from "@gooddata/util";
import { Bubble } from "../../Bubble/Bubble.js";
import { BubbleHoverTrigger } from "../../Bubble/BubbleHoverTrigger.js";
import { Dropdown } from "../../Dropdown/Dropdown.js";
import { DropdownButton } from "../../Dropdown/DropdownButton.js";
import { DropdownList } from "../../Dropdown/DropdownList.js";
const getItems = (intl, measures, measureNames, areaSortEnabled, availableId) => {
    const measureValues = [];
    if (areaSortEnabled) {
        measureValues.push({
            id: "aggregation",
            title: intl.formatMessage({
                id: "sorting.sum.of.all.measure",
            }),
            localIdentifier: objRefToString(availableId),
        });
    }
    if (measures) {
        measures.forEach((measure) => {
            const measureLocator = measure.locators.find(isMeasureLocator);
            if (!measureLocator) {
                return;
            }
            const bucketItem = measureNames[measureLocator.measureLocatorItem.measureIdentifier];
            if (bucketItem) {
                measureValues.push({
                    id: measureLocator.measureLocatorItem.measureIdentifier,
                    title: bucketItem?.name,
                    sequenceNumber: bucketItem?.sequenceNumber,
                    localIdentifier: measureLocator.measureLocatorItem.measureIdentifier,
                });
            }
        });
    }
    return measureValues;
};
const getButtonValue = (currentItem, intl, measureNames) => {
    if (isAttributeAreaSort(currentItem)) {
        return {
            id: "aggregation",
            title: intl.formatMessage({ id: "sorting.sum.of.all.measure" }),
        };
    }
    else if (isMeasureSort(currentItem)) {
        const measureLocator = currentItem.measureSortItem.locators.find(isMeasureLocator);
        if (measureLocator) {
            return {
                id: measureNames[measureLocator.measureLocatorItem.measureIdentifier]?.name ?? "",
                title: measureNames[measureLocator.measureLocatorItem.measureIdentifier]?.name ?? "",
                sequenceNumber: measureNames[measureLocator.measureLocatorItem.measureIdentifier]?.sequenceNumber,
            };
        }
    }
    return {
        id: "",
        title: "",
    };
};
const getMeasureIconClassNameBySelected = (id) => {
    if (id === "aggregation") {
        return "gd-icon-aggregation";
    }
    else {
        return "gd-icon-metric";
    }
};
export function MeasureDropdown({ currentItem, availableSorts, bucketItems, intl, onSelect, index, disabledExplanationTooltip, }) {
    const [width, setWidth] = useState(0);
    const buttonRef = useRef(null);
    const measures = availableSorts.metricSorts ?? [];
    const areaSortEnabled = availableSorts.attributeSort?.areaSortEnabled ?? false;
    const items = getItems(intl, measures, bucketItems, areaSortEnabled, availableSorts.itemId);
    const disableDropdown = items.length === 1;
    const buttonValue = getButtonValue(currentItem, intl, bucketItems);
    const measureName = buttonValue.sequenceNumber
        ? `${buttonValue.title} (${buttonValue.sequenceNumber})`
        : buttonValue.title;
    useEffect(() => {
        if (buttonRef?.current) {
            setWidth(buttonRef.current.getBoundingClientRect().width);
        }
    }, []);
    const onMeasureSelectHandler = useCallback((item) => {
        const direction = sortDirection(currentItem);
        if (item.id === "aggregation" && areaSortEnabled) {
            onSelect(newAttributeAreaSort(item.localIdentifier, direction));
        }
        else {
            onSelect(newMeasureSort(item.localIdentifier, direction));
        }
    }, [currentItem, onSelect, areaSortEnabled]);
    return (_jsxs("div", { className: "sort-measure-section", children: [
            _jsx("span", { className: "select-label", children: _jsx("span", { children: intl.formatMessage({ id: "sorting.by" }) }) }), _jsx("div", { className: "measure-sorting-dropdown", children: disableDropdown ? (_jsxs(BubbleHoverTrigger, { children: [
                        _jsx(DropdownButton, { className: "s-inner-aggregation-disabled-button s-measure-dropdown-button", value: measureName, disabled: true, iconLeft: getMeasureIconClassNameBySelected(buttonValue.id) }), disabledExplanationTooltip ? (_jsx(Bubble, { alignPoints: [{ align: "cr cl" }, { align: "cl cr" }] })) : null] })) : (_jsx(Dropdown, { className: "gd-measure-sorting-dropdown-body s-measure-sorting-dropdown-body", closeOnMouseDrag: true, closeOnParentScroll: true, renderButton: ({ isOpen, toggleDropdown }) => (_jsx("div", { ref: buttonRef, children: _jsx(DropdownButton, { className: `s-sort-type-measure-button s-measure-dropdown-button-${index}`, value: measureName, isOpen: isOpen, disabled: disableDropdown, onClick: toggleDropdown, iconLeft: getMeasureIconClassNameBySelected(buttonValue.id) }) })), renderBody: ({ closeDropdown }) => (_jsx(DropdownList, { width: width, items: items, className: "gd-measure-sorting-dropdown-body s-measure-sorting-dropdown-body", renderItem: ({ item, rowIndex }) => {
                            const isSelected = item.title === buttonValue.title &&
                                item.sequenceNumber === buttonValue.sequenceNumber;
                            const className = cx("gd-list-item", "gd-list-item-shortened", "gd-sorting-measure", "gd-button-link", getMeasureIconClassNameBySelected(item.id), {
                                "is-selected": isSelected,
                            }, `s-sorting-measure-${simplifyText(item.title)}`, `s-sorting-measure-${rowIndex}`);
                            // Set gd-measure-dropdown-list height to 28 to ensure that child elements with a larger height do not affect it.
                            // If an item’s height overflows 28px, it impacts the whole list And this is what we want to prevent.
                            return (_jsx("div", { className: "gd-measure-dropdown-list", style: { height: 28 }, children: _jsxs("button", { className: className, onClick: () => {
                                        onMeasureSelectHandler(item);
                                        closeDropdown();
                                    }, title: item.title, children: [
                                        _jsx("span", { className: "gd-sorting-measure-title", children: item.title }), item.sequenceNumber ? (_jsx("span", { className: "gd-sorting-sequence-number", children: item.sequenceNumber })) : null] }) }));
                        } })) })) })
        ] }));
}
