import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2019-2026 GoodData Corporation
import { useMemo, useState } from "react";
import { isEqual } from "lodash-es";
import { defineMessages, useIntl } from "react-intl";
import { UiButton } from "../@ui/UiButton/UiButton.js";
import { Dropdown, } from "../Dropdown/Dropdown.js";
import { InvertableSelect, } from "../List/InvertableSelect/InvertableSelect.js";
import { useInvertableSelectionStatusText } from "../List/InvertableSelect/InvertableSelectSelectionStatus.js";
import { SeparatorLine } from "../SeparatorLine/SeparatorLine.js";
const messages = defineMessages({
    apply: {
        id: "gs.list.apply",
    },
    cancel: {
        id: "gs.list.cancel",
    },
});
/**
 * @internal
 */
export function DropdownInvertableSelect(props) {
    const { title, options, onChange, onOpen, onClose, closeOnEscape, className, bodyClassName, width = 240, alignPoints, getItemTitle, getItemKey, initialValue, initialIsInverted, initialSearchString, overlayPositionType, accessibilityConfig, header, renderStatusBar, renderSearchBar, renderNoData, renderActions, renderItem, renderListActions, } = props;
    const [searchString, setSearchString] = useState(initialSearchString ?? "");
    const [committedSelection, setCommitedSelection] = useState(initialValue ?? []);
    const [committedIsInverted, setCommitedIsInverted] = useState(initialIsInverted ?? true);
    const [selection, setSelection] = useState(initialValue ?? []);
    const [isInverted, setIsInverted] = useState(initialIsInverted ?? true);
    const { text, count } = useInvertableSelectionStatusText(committedSelection, committedIsInverted, getItemTitle);
    const buttonText = title ? `${title}: ${text}` : text;
    const onSearch = (searchString) => {
        setSearchString(searchString);
    };
    const onSelect = (selectedItems, isInverted) => {
        setSelection(selectedItems);
        setIsInverted(isInverted);
    };
    const resetTemporarySelection = () => {
        setSelection(committedSelection);
        setIsInverted(committedIsInverted);
        setSearchString("");
    };
    const onApply = () => {
        setCommitedSelection(selection);
        setCommitedIsInverted(isInverted);
        onChange(selection, isInverted);
    };
    const filteredOptions = options.filter((option) => {
        return !searchString || getItemTitle(option).toLowerCase().includes(searchString.toLowerCase());
    });
    const renderButton = useMemo(() => {
        return (props.renderButton ??
            (({ toggleDropdown }) => (_jsx(UiButton, { label: buttonText, badgeAfter: count, onClick: toggleDropdown, size: "small", variant: "secondary", iconAfter: "navigateDown" }))));
    }, [buttonText, count, props.renderButton]);
    return (_jsx(Dropdown, { accessibilityConfig: accessibilityConfig, className: className, alignPoints: alignPoints, overlayPositionType: overlayPositionType, onOpenStateChanged: (isOpen) => {
            if (isOpen) {
                onOpen?.();
            }
            else {
                resetTemporarySelection();
                onClose?.();
            }
        }, closeOnEscape: closeOnEscape, renderButton: renderButton, renderBody: (bodyProps) => {
            const { closeDropdown, ariaAttributes } = bodyProps;
            const isEmptySelection = !isInverted && selection.length === 0;
            const isSelectionEqual = isEqual(selection, committedSelection) && isInverted === committedIsInverted;
            const ariaAttrs = {
                ...ariaAttributes,
                ...(accessibilityConfig?.popupLabel
                    ? {
                        // We need to remove to aria-labelledby if
                        // popupLabel is provided
                        "aria-labelledby": undefined,
                    }
                    : {}),
                "aria-label": accessibilityConfig?.popupLabel,
            };
            return (_jsxs("div", { ...ariaAttrs, children: [header, _jsx(InvertableSelect, { width: width, className: bodyClassName, items: filteredOptions, getItemTitle: getItemTitle, getItemKey: getItemKey, isInverted: isInverted, searchString: searchString, onSearch: onSearch, selectedItems: selection, onSelect: onSelect, onEscKeyPress: closeDropdown, renderStatusBar: renderStatusBar, renderSearchBar: renderSearchBar, renderNoData: renderNoData, renderItem: renderItem, renderActions: renderListActions, totalItemsCount: filteredOptions.length }), renderActions?.(bodyProps) ?? (_jsx(DropdownInvertableSelectActions, { onApply: () => {
                            onApply();
                            closeDropdown();
                        }, onCancel: () => {
                            closeDropdown();
                        }, isApplyDisabled: isEmptySelection || isSelectionEqual }))] }));
        } }));
}
function DropdownInvertableSelectActions({ onApply, isApplyDisabled, onCancel, }) {
    const intl = useIntl();
    const cancelText = intl.formatMessage(messages.cancel);
    const applyText = intl.formatMessage(messages.apply);
    return (_jsx(_Fragment, { children: _jsxs("div", { className: "gd-invertable-select-actions", children: [
                _jsx(SeparatorLine, {}), _jsxs("div", { className: "gd-invertable-select-actions-buttons", children: [
                        _jsx(UiButton, { variant: "secondary", size: "small", onClick: onCancel, label: cancelText }), _jsx(UiButton, { variant: "primary", size: "small", onClick: onApply, label: applyText, isDisabled: isApplyDisabled })
                    ] })
            ] }) }));
}
