import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2024-2026 GoodData Corporation
import { useCallback, useState } from "react";
import cx from "classnames";
import { FormattedMessage, useIntl } from "react-intl";
import { objRefToString } from "@gooddata/sdk-model";
import { LoadingComponent } from "@gooddata/sdk-ui";
import { Button, SELECT_ITEM_ACTION, ScopedIdStore, Typography, UiFocusManager, UiIcon, UiIconButton, UiLink, UiTooltip, useFocusWithinContainer, useId, useIdPrefixed, useListWithActionsKeyboardNavigation, useScopedIdStoreValue, } from "@gooddata/sdk-ui-kit";
import { applyFilterView, deleteFilterView, setFilterViewAsDefault, } from "../../../../model/commands/filters.js";
import { useDashboardDispatch, useDashboardSelector, } from "../../../../model/react/DashboardStoreProvider.js";
import { selectFilterViewsAreLoading } from "../../../../model/store/filterViews/filterViewsReducersSelectors.js";
import { selectCanCreateFilterView } from "../../../../model/store/permissions/permissionsSelectors.js";
import { FilterViewDeleteConfirm } from "./FilterViewDeleteConfirm.js";
function SetAsDefaultButton({ isDefault, isFocused, onClick, title, id, }) {
    const { formatMessage } = useIntl();
    return (_jsx("div", { className: cx("gd-filter-view__item__button", {
            "gd-filter-view__item__button--isFocused": isFocused,
        }), role: "gridcell", children: _jsx(UiLink, { variant: "primary", flipUnderline: true, onClick: onClick, id: id, tabIndex: isFocused ? 0 : -1, role: "button", "aria-label": isDefault
                ? formatMessage({ id: "filters.filterViews.dropdown.unsetAsDefault.ariaLabel" }, { name: title })
                : formatMessage({ id: "filters.filterViews.dropdown.setAsDefault.ariaLabel" }, { name: title }), children: isDefault ? (_jsx(FormattedMessage, { id: "filters.filterViews.dropdown.unsetAsDefault" })) : (_jsx(FormattedMessage, { id: "filters.filterViews.dropdown.setAsDefault" })) }) }));
}
function DeleteButton({ isFocused, onClick, title, id, }) {
    const { formatMessage } = useIntl();
    return (_jsx("div", { className: "gd-filter-view__item__delete-button-wrapper", role: "gridcell", children: _jsx(UiTooltip, { arrowPlacement: "top-end", triggerBy: isFocused ? [] : ["hover"], content: formatMessage({ id: "filters.filterViews.add.deleteTooltip" }), anchor: _jsx("div", { className: cx("gd-filter-view__item__button gd-filter-view__item__button--delete", {
                    "gd-filter-view__item__button--isFocused": isFocused,
                }), role: "button", "aria-label": formatMessage({ id: "filters.filterViews.add.deleteTooltip.ariaLabel" }, { name: title }), onClick: onClick, id: id, tabIndex: isFocused ? 0 : -1, children: _jsx(UiIcon, { type: "trash", size: 12, layout: "block", color: "currentColor" }) }) }) }));
}
function FilterListItem({ item, index, focusedAction, onApply, onDelete, onSetAsDefault, }) {
    const { name, isDefault = false } = item;
    const isFocused = !!focusedAction;
    const makeId = ScopedIdStore.useContextStoreOptional((ctx) => ctx.makeId);
    const titleId = useIdPrefixed("title");
    return (_jsxs("div", { className: cx("gd-filter-view__item", {
            "gd-filter-view__item--isFocused": isFocused,
            "gd-filter-view__item--isFocusedSelectItem": focusedAction === SELECT_ITEM_ACTION,
        }), role: "row", "aria-rowindex": index + 1, "aria-labelledby": titleId, tabIndex: -1, children: [
            _jsx("div", { className: "gd-filter-view__item__value", onClick: onApply, id: titleId, role: "gridcell", children: _jsxs("div", { role: "button", tabIndex: focusedAction === SELECT_ITEM_ACTION ? 0 : -1, id: makeId?.({ item, specifier: SELECT_ITEM_ACTION }) ?? undefined, children: [
                        _jsx("span", { className: "gd-filter-view__item__value__title", children: name }), isDefault ? (_jsxs("span", { className: "gd-filter-view__item__value__suffix", children: ["\u00A0",
                                _jsx(FormattedMessage, { id: "filters.filterViews.dropdown.isDefault" })
                            ] })) : null] }) }), onSetAsDefault ? (_jsx(SetAsDefaultButton, { isDefault: isDefault, title: name, onClick: onSetAsDefault, isFocused: focusedAction === "setDefault", id: makeId?.({ item, specifier: "setDefault" }) })) : null, onDelete ? (_jsx(DeleteButton, { onClick: onDelete, title: name, isFocused: focusedAction === "delete", id: makeId?.({ item, specifier: "delete" }) })) : null] }));
}
export function FilterViewsList({ filterViews = [], onAddNew, onClose, titleId: titleIdProp, }) {
    const intl = useIntl();
    const dispatch = useDashboardDispatch();
    const [filterViewToDelete, setFilterViewToDelete] = useState(undefined);
    const isLoading = useDashboardSelector(selectFilterViewsAreLoading);
    const canCreateFilterView = useDashboardSelector(selectCanCreateFilterView);
    const id = useId();
    const createViewId = `create-view-${id}`;
    const filterViewTooltipId = `filter-view-tooltip-${id}`;
    const titleId = titleIdProp ?? `filter-views-title-${id}`;
    const getItemAdditionalActions = useCallback(() => {
        if (!canCreateFilterView) {
            return [];
        }
        return ["setDefault", "delete"];
    }, [canCreateFilterView]);
    const createSelectHandler = useCallback((filterView) => () => {
        dispatch(applyFilterView(filterView.ref));
        onClose();
    }, [dispatch, onClose]);
    const createSetAsDefaultHandler = useCallback((filterView) => {
        if (!canCreateFilterView) {
            return undefined;
        }
        return () => {
            dispatch(setFilterViewAsDefault(filterView.ref, !filterView.isDefault));
        };
    }, [canCreateFilterView, dispatch]);
    const createSetAsDefaultAndCloseHandler = useCallback((filterView) => {
        const handler = createSetAsDefaultHandler(filterView);
        if (handler === undefined) {
            return undefined;
        }
        return () => {
            handler();
            onClose();
        };
    }, [createSetAsDefaultHandler, onClose]);
    const createDeleteHandler = useCallback((filterView) => {
        if (!canCreateFilterView) {
            return undefined;
        }
        return () => {
            setFilterViewToDelete(filterView);
        };
    }, [canCreateFilterView]);
    const refocusKey = `${isLoading}`;
    const { onKeyboardNavigation, focusedItem, focusedAction, setFocusedAction } = useListWithActionsKeyboardNavigation({
        items: filterViews,
        getItemAdditionalActions,
        actionHandlers: {
            selectItem: createSelectHandler,
            setDefault: createSetAsDefaultAndCloseHandler,
            delete: createDeleteHandler,
        },
        isSimple: true,
    });
    const contentTooltip = (_jsx("div", { className: "gd-filter-view__list__tooltip", children: _jsx(FormattedMessage, { id: "filters.filterViews.dropdown.tooltip", values: {
                p: (chunks) => _jsx("p", { children: chunks }),
            } }) }));
    const scopedIdStoreValue = useScopedIdStoreValue((item) => item ? objRefToString(item.ref) : "");
    const { containerRef } = useFocusWithinContainer(scopedIdStoreValue.makeId({ item: focusedItem, specifier: focusedAction }) ?? "");
    const handleBlur = useCallback(
    // Select the default action when the focus leaves the list
    (e) => {
        if (containerRef.current?.contains(e.relatedTarget)) {
            return;
        }
        setFocusedAction(SELECT_ITEM_ACTION);
    }, [containerRef, setFocusedAction]);
    return (_jsxs(UiFocusManager, { enableFocusTrap: true, enableAutofocus: { refocusKey, initialFocus: createViewId }, children: [filterViewToDelete ? (_jsx(FilterViewDeleteConfirm, { filterView: filterViewToDelete, onConfirm: () => {
                    dispatch(deleteFilterView(filterViewToDelete.ref));
                    setFilterViewToDelete(undefined);
                }, onCancel: () => setFilterViewToDelete(undefined) })) : null, _jsxs("div", { className: "configuration-panel configuration-panel__filter-view__list", children: [
                    _jsx("div", { className: "configuration-panel-header", children: _jsxs("div", { className: "gd-title-with-icon", children: [
                                _jsx(Typography, { tagName: "h3", className: "configuration-panel-header-title", id: titleId, children: _jsx(FormattedMessage, { id: "filters.filterViews.dropdown.title" }) }), _jsx(UiTooltip, { id: filterViewTooltipId, arrowPlacement: "top-end", content: contentTooltip, anchor: _jsx(UiIconButton, { icon: "question", variant: "tertiary", size: "small", accessibilityConfig: {
                                            ariaDescribedBy: filterViewTooltipId,
                                            ariaLabel: intl.formatMessage({
                                                id: "filters.filterViews.tooltip.ariaLabel",
                                            }),
                                        } }), triggerBy: ["hover", "focus"] })
                            ] }) }), _jsx(ScopedIdStore, { value: scopedIdStoreValue, children: _jsx("div", { className: "configuration-category gd-filter-view__list", role: "grid", ref: containerRef, onKeyDown: onKeyboardNavigation, onBlur: handleBlur, tabIndex: -1, id: scopedIdStoreValue.containerId, "aria-label": canCreateFilterView
                                ? intl.formatMessage({ id: "filters.filterViews.list.ariaLabel.withActions" })
                                : intl.formatMessage({ id: "filters.filterViews.list.ariaLabel.noActions" }), "aria-rowcount": filterViews.length, children: isLoading ? (_jsx("div", { className: "gd-filter-view__list__empty", children: _jsx(LoadingComponent, {}) })) : filterViews.length > 0 ? (filterViews.map((filterView, index) => (_jsx(FilterListItem, { item: filterView, index: index, focusedAction: filterView === focusedItem ? focusedAction : undefined, onApply: createSelectHandler(filterView), onSetAsDefault: createSetAsDefaultHandler(filterView), onDelete: createDeleteHandler(filterView) }, objRefToString(filterView.ref))))) : (_jsx("div", { className: "gd-filter-view__list__empty", children: _jsx(FormattedMessage, { id: "filters.filterViews.dropdown.emptyList" }) })) }) }), _jsx("div", { className: "configuration-panel-footer", children: _jsx("div", { className: "configuration-panel-footer__content", children: _jsx(Button, { id: createViewId, className: "gd-button gd-button gd-button-link", iconLeft: "gd-icon-plus", size: "small", onClick: onAddNew, disabled: !canCreateFilterView, accessibilityConfig: {
                                    ariaExpanded: false,
                                    ariaHaspopup: "dialog",
                                }, children: _jsx(FormattedMessage, { id: "filters.filterViews.dropdown.newButton" }) }) }) })
                ] })
        ] }));
}
//# sourceMappingURL=FilterViewsList.js.map