import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2007-2026 GoodData Corporation
import { useCallback, useEffect, useRef, useState } from "react";
import cx from "classnames";
import { FormattedMessage, defineMessage, defineMessages, useIntl } from "react-intl";
import { objRefToString } from "@gooddata/sdk-model";
import { Button, Dropdown, DropdownButton, DropdownList, ScrollableItem, ShortenedText, isDateDatasetHeader, } from "@gooddata/sdk-ui-kit";
import { simplifyText } from "@gooddata/util";
import { getDateConfigurationDropdownHeight, getSortedDateDatasetsItems, removeDateFromTitle, } from "./utils.js";
const DEFAULT_HYPHEN_CHAR = "-";
const alignPoints = [{ align: "bl tl" }, { align: "tl bl" }];
const tooltipAlignPoints = [
    { align: "cl cr", offset: { x: -10, y: 0 } },
    { align: "cr cl", offset: { x: 10, y: 0 } },
];
const DROPDOWN_MIN_HEIGHT = 170;
const DEFAULT_DROPDOWN_ITEM_HEIGHT = 28;
// work around the evil DateDatasetsListItem from kit that magically translates SOME of the items' titles
// this way the i18n actually has a chance to detect these
const dateDatasetHeaderMessages = defineMessages({
    "gs.date.date-dataset.recommended": { id: "gs.date.date-dataset.recommended" },
    "gs.date.date-dataset.other": { id: "gs.date.date-dataset.other" },
    "gs.date.date-dataset.related": { id: "gs.date.date-dataset.related" },
    "gs.date.date-dataset.unrelated": { id: "gs.date.date-dataset.unrelated" },
});
function DateDatasetsListItem({ id, title = "", isHeader, isSelected, isUnrelated, onClick, }) {
    if (isHeader) {
        return _jsx("div", { className: "gd-list-item gd-list-item-header", children: title });
    }
    const classNames = cx("gd-list-item", "gd-list-item-shortened", `s-${id}`, `s-${simplifyText(title)}`, {
        "is-selected": isSelected,
        "is-unrelated": isUnrelated,
    });
    return (_jsx("div", { className: classNames, onClick: onClick, children: _jsx(ShortenedText, { tooltipAlignPoints: tooltipAlignPoints, children: title }) }));
}
export function DateDatasetDropdown(props) {
    const { className = "s-date-dataset-switch", isLoading = false, autoOpen = false, onDateDatasetChange, activeDateDataset, unrelatedDateDataset, dateFromVisualization, relatedDateDatasets, widgetRef, enableUnrelatedItemsVisibility, unrelatedDateDatasets, } = props;
    const intl = useIntl();
    const { onItemScroll, closeOnParentScroll } = useAutoScroll(autoOpen);
    const [showUnavailableItems, setShowUnavailableItems] = useState(false);
    const unrelatedDateDataSetId = unrelatedDateDataset ? unrelatedDateDataset.dataSet.id : null;
    let activeDateDataSetId;
    let activeDateDataSetTitle = DEFAULT_HYPHEN_CHAR;
    let activeDateDataSetUri;
    let recommendedDateDataSet;
    if (!isLoading && activeDateDataset) {
        activeDateDataSetId = activeDateDataset.dataSet.id;
        activeDateDataSetTitle = activeDateDataset.dataSet.title;
        activeDateDataSetUri = activeDateDataset.dataSet.uri;
    }
    if (dateFromVisualization) {
        recommendedDateDataSet = relatedDateDatasets.find((d) => d.dataSet.uri === dateFromVisualization.dataSet.uri);
    }
    const sortedItems = getSortedDateDatasetsItems(relatedDateDatasets, recommendedDateDataSet, unrelatedDateDataset, unrelatedDateDatasets, enableUnrelatedItemsVisibility && showUnavailableItems);
    const unrelatedDateDatasetCount = (unrelatedDateDatasets?.length ?? 0) - (unrelatedDateDataset ? 1 : 0);
    const buttonRef = useRef(null);
    const [{ height, width }, setDropdownDimensions] = useState({
        width: props.width,
        height: DROPDOWN_MIN_HEIGHT,
    });
    const dropdownBodyHeight = (sortedItems?.length || 0) * DEFAULT_DROPDOWN_ITEM_HEIGHT;
    useEffect(() => {
        const buttonRect = buttonRef?.current?.getBoundingClientRect();
        const calculatedWidth = buttonRect?.width ?? 0;
        const calculatedHeight = getDateConfigurationDropdownHeight(buttonRect?.top ?? 0, buttonRect?.height ?? 0, dropdownBodyHeight, !unrelatedDateDatasets?.length);
        setDropdownDimensions({ width: calculatedWidth, height: calculatedHeight });
    }, [dropdownBodyHeight, unrelatedDateDatasets, buttonRef]);
    const onShowHideUnrelatedItemsClick = () => {
        setShowUnavailableItems(!showUnavailableItems);
    };
    const renderDropdownBody = ({ closeDropdown }) => {
        if (isLoading) {
            return null;
        }
        return (_jsxs("div", { style: { width }, children: [_jsx(DropdownList, { className: "configuration-dropdown dataSets-list", height: height, width: width, items: sortedItems, itemsCount: sortedItems.length, renderItem: ({ item }) => {
                        const isHeader = isDateDatasetHeader(item);
                        const isSelected = !isDateDatasetHeader(item) && activeDateDataSetId === item.id;
                        const isUnrelated = !isDateDatasetHeader(item) && unrelatedDateDataSetId === item.id;
                        return (_jsx(DateDatasetsListItem, { title: isHeader
                                ? intl.formatMessage(dateDatasetHeaderMessages[item.title])
                                : removeDateFromTitle(item.title), isHeader: isHeader, isSelected: isSelected, isUnrelated: isUnrelated, onClick: (e) => {
                                e.preventDefault();
                                if (isDateDatasetHeader(item)) {
                                    return;
                                }
                                closeDropdown();
                                onDateDatasetChange(item.id);
                            } }));
                    } }), enableUnrelatedItemsVisibility && unrelatedDateDatasetCount > 0 ? (_jsxs("div", { className: "gd-list-footer", children: [
                        _jsx(FormattedMessage, { id: "gs.date.date-dataset.unrelated_hidden", values: {
                                count: unrelatedDateDatasetCount,
                                isShow: showUnavailableItems,
                            } }), _jsx(Button, { onClick: onShowHideUnrelatedItemsClick, className: "gd-button-link-dimmed unrelated-date-button", value: intl.formatMessage({
                                id: showUnavailableItems
                                    ? defineMessage({ id: "gs.date.date-dataset.unrelated.hide" }).id
                                    : defineMessage({ id: "gs.date.date-dataset.unrelated.show" }).id,
                            }) })
                    ] })) : null] }));
    };
    return (_jsx(Dropdown
    // We want to open the dropdown, when user selects a metric
    // without a recommended data set
    , { openOnInit: autoOpen, ignoreClicksOnByClass: [".dash-content"], renderButton: ({ isOpen, toggleDropdown }) => {
            const buttonClassName = cx("s-date-dataset-button", isOpen ? "s-expanded" : "s-collapsed", {
                "is-loading": isLoading,
                "is-unrelated": !isLoading && unrelatedDateDataset?.dataSet.uri === activeDateDataSetUri,
            });
            const buttonValue = isLoading
                ? intl.formatMessage({ id: "loading" })
                : removeDateFromTitle(activeDateDataSetTitle);
            return (_jsx(ScrollableItem, { scrollIntoView: autoOpen, onItemScrolled: onItemScroll, children: _jsx("div", { ref: (ref) => {
                        if (ref && ref !== buttonRef.current) {
                            buttonRef.current = ref;
                        }
                    }, children: _jsx(DropdownButton, { className: buttonClassName, value: buttonValue, isOpen: isOpen, onClick: toggleDropdown, disabled: isLoading }) }) }));
        }, className: className, closeOnParentScroll: closeOnParentScroll, closeOnMouseDrag: true, alignPoints: alignPoints, renderBody: renderDropdownBody }, `${objRefToString(widgetRef)}_${autoOpen}`));
}
/**
 * Purpose of this hook is keep value of closeOnParentScroll derived from autoOpen
 * We need set closeOnParentScroll to false and after item scrolled return to true
 * otherwise dropdown is immediately closed when item is scrolled to view
 */
export function useAutoScroll(autoOpen) {
    const [closeOnParentScroll, setCloseOnParentScroll] = useState(!autoOpen);
    useEffect(() => {
        setCloseOnParentScroll(!autoOpen);
    }, [autoOpen]);
    const onItemScroll = useCallback(() => {
        setTimeout(() => {
            setCloseOnParentScroll(true);
        }, 300);
    }, []);
    return {
        onItemScroll,
        closeOnParentScroll,
    };
}
//# sourceMappingURL=DateDatasetDropdown.js.map