import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2025-2026 GoodData Corporation
import { useCallback, useMemo, useRef, } from "react";
import { useIntl } from "react-intl";
import { v4 as uuid } from "uuid";
import { usePropState } from "@gooddata/sdk-ui";
import { DefaultUiTabsTabValue, UiFocusManager, UiIcon, UiIconButton, UiTabs, UiTooltip, bemFactory, separatorStaticItem, useId, useScopedIdOptional, } from "@gooddata/sdk-ui-kit";
import { cancelRenamingDashboardTab, convertDashboardTabFromDefault, createDashboardTab, deleteDashboardTab, renameDashboardTab, repositionDashboardTab, startRenamingDashboardTab, switchDashboardTab, } from "../../../model/commands/tabs.js";
import { useDashboardDispatch, useDashboardSelector } from "../../../model/react/DashboardStoreProvider.js";
import { selectIsAddTabButtonHidden } from "../../../model/store/config/configSelectors.js";
import { selectIsInEditMode } from "../../../model/store/renderMode/renderModeSelectors.js";
import { selectActiveTabLocalIdentifier, selectTabs } from "../../../model/store/tabs/tabsSelectors.js";
import { DEFAULT_TAB_ID } from "../../../model/store/tabs/tabsState.js";
const EMPTY_TABS = [];
function createRenameAction(params) {
    const { tab, intl, dispatch } = params;
    return {
        id: "rename",
        label: intl.formatMessage({ id: "dashboard.tabs.rename" }),
        iconLeft: _jsx(UiIcon, { type: "pencil", size: 14, color: "complementary-5" }),
        isDisabled: tab.isRenaming,
        onSelect: () => dispatch(startRenamingDashboardTab(tab.localIdentifier)),
        closeOnSelect: "all",
        dataTestId: "s-tab-action-rename",
    };
}
function createMoveLeftAction(params) {
    const { index, intl, dispatch } = params;
    if (index <= 0) {
        return undefined;
    }
    return {
        id: "moveLeft",
        label: intl.formatMessage({ id: "dashboard.tabs.move.left" }),
        iconLeft: _jsx(UiIcon, { type: "arrowLeft", size: 14, color: "complementary-5" }),
        onSelect: () => {
            if (index <= 0) {
                return;
            }
            dispatch(repositionDashboardTab(index, index - 1));
        },
        closeOnSelect: false,
        dataTestId: "s-tab-action-move-left",
    };
}
function createMoveRightAction(params) {
    const { index, totalTabs, intl, dispatch } = params;
    if (index >= totalTabs - 1) {
        return undefined;
    }
    return {
        id: "moveRight",
        label: intl.formatMessage({ id: "dashboard.tabs.move.right" }),
        iconLeft: _jsx(UiIcon, { type: "arrowRight", size: 14, color: "complementary-5" }),
        onSelect: () => {
            if (index >= totalTabs - 1) {
                return;
            }
            dispatch(repositionDashboardTab(index, index + 1));
        },
        closeOnSelect: false,
        dataTestId: "s-tab-action-move-right",
    };
}
function createDeleteAction(params, isOnlyOneTab) {
    const { tab, intl, dispatch } = params;
    return {
        id: "delete",
        label: intl.formatMessage({ id: "delete" }),
        isDisabled: isOnlyOneTab,
        iconLeft: _jsx(UiIcon, { type: "trash", size: 14, color: "complementary-5" }),
        isDestructive: true,
        tooltip: isOnlyOneTab
            ? intl.formatMessage({
                id: "dashboard.tabs.delete.disabled-tooltip",
            })
            : undefined,
        tooltipWidth: 250,
        onSelect: () => dispatch(deleteDashboardTab(tab.localIdentifier)),
        dataTestId: "s-tab-action-delete",
    };
}
function buildTabActions(params, isOnlyOneTab) {
    const actions = [
        createRenameAction(params),
        createMoveLeftAction(params),
        createMoveRightAction(params),
        separatorStaticItem,
        createDeleteAction(params, isOnlyOneTab),
    ];
    return actions.filter((x) => !!x);
}
export function useDashboardTabsProps() {
    const intl = useIntl();
    const isEditMode = useDashboardSelector(selectIsInEditMode);
    const tabs = useDashboardSelector(selectTabs) ?? EMPTY_TABS;
    const activeTabLocalIdentifier = useDashboardSelector(selectActiveTabLocalIdentifier);
    const dispatch = useDashboardDispatch();
    // Generate a stable unique ID for the default tab
    const defaultTabIdRef = useRef(uuid());
    const handleTabSelect = useCallback((tab) => {
        if (tab.id !== activeTabLocalIdentifier) {
            dispatch(switchDashboardTab(tab.id));
        }
    }, [activeTabLocalIdentifier, dispatch]);
    const handleTabRename = useCallback((tab) => {
        if (isEditMode) {
            dispatch(startRenamingDashboardTab(tab.id));
        }
    }, [isEditMode, dispatch]);
    const uiTabs = useMemo(() => {
        const isOnlyOneTab = tabs.length < 2;
        const totalTabs = tabs.length;
        return (tabs.map((tab, index) => {
            const actionParams = { tab, index, totalTabs, intl, dispatch };
            return {
                id: tab.localIdentifier,
                label: tab.title || intl.formatMessage({ id: "dashboard.tabs.default.label" }), // handles also empty string
                isRenaming: tab.isRenaming,
                variant: isOnlyOneTab ? "placeholder" : "default",
                actions: isEditMode ? buildTabActions(actionParams, isOnlyOneTab) : [],
            };
        }) ?? []);
    }, [tabs, isEditMode, intl, dispatch]);
    // Use the default tab ID as activeTabLocalIdentifier if we created a default tab and no activeTabLocalIdentifier is set
    const effectiveActiveTabLocalIdentifier = useMemo(() => {
        if (isEditMode && tabs.length === 0 && !activeTabLocalIdentifier) {
            return defaultTabIdRef.current;
        }
        return activeTabLocalIdentifier;
    }, [isEditMode, tabs, activeTabLocalIdentifier]);
    return {
        activeTabLocalIdentifier: effectiveActiveTabLocalIdentifier,
        uiTabs,
        handleTabSelect,
        handleTabRename,
    };
}
const tabsBem = bemFactory("gd-dash-tabs");
/**
 * @internal
 */
export function DashboardTabs({ activeTabLocalIdentifier, uiTabs, handleTabSelect, handleTabRename, }) {
    const intl = useIntl();
    const isEditMode = useDashboardSelector(selectIsInEditMode);
    const hideAddTabButton = useDashboardSelector(selectIsAddTabButtonHidden);
    const dispatch = useDashboardDispatch();
    const ACCESSIBILITY_CONFIG = useMemo(() => ({
        role: "tablist",
        tabRole: "tab",
        ariaLabel: intl.formatMessage({ id: "dashboard.tabs.accessibility.label" }),
    }), [intl]);
    const isCreateEnabled = isEditMode && !hideAddTabButton;
    const hasDefaultTab = uiTabs.some((tab) => tab.id === DEFAULT_TAB_ID);
    const handleCreateTab = useCallback(() => {
        if (hasDefaultTab) {
            dispatch(convertDashboardTabFromDefault());
        }
        dispatch(createDashboardTab());
    }, [dispatch, hasDefaultTab]);
    const shouldHideTabs = useMemo(() => {
        if (!uiTabs || activeTabLocalIdentifier === undefined) {
            return true;
        }
        return isEditMode ? uiTabs.length < 1 : uiTabs.length <= 1;
    }, [isEditMode, uiTabs, activeTabLocalIdentifier]);
    if (shouldHideTabs) {
        return null;
    }
    return (_jsxs("div", { className: tabsBem.b({ "with-create": isCreateEnabled }), children: [
            _jsx("div", { className: tabsBem.e("list"), children: _jsx(UiTabs, { size: "large", tabs: uiTabs, onTabSelect: handleTabSelect, onTabDoubleClick: handleTabRename, selectedTabId: activeTabLocalIdentifier ?? uiTabs[0].id, accessibilityConfig: ACCESSIBILITY_CONFIG, maxLabelLength: 255, TabValue: RenamableTabValue }) }), isCreateEnabled ? (_jsx("div", { className: tabsBem.e("add-wrapper"), children: _jsx("div", { className: tabsBem.e("add"), children: _jsx(UiTooltip, { anchor: _jsx(UiIconButton, { icon: "plus", size: "large", variant: "tertiary", onClick: handleCreateTab, dataTestId: "s-tab-add-new", accessibilityConfig: {
                                ariaLabel: intl.formatMessage({
                                    id: "dashboard.tabs.accessibility.add-button-label",
                                }),
                            } }), content: intl.formatMessage({ id: "dashboard.tabs.add-button-tooltip" }), triggerBy: ["hover"], arrowPlacement: "bottom", optimalPlacement: true }) }) })) : null] }));
}
function RenamableTabValue(props) {
    const { location, tab } = props;
    const dispatch = useDashboardDispatch();
    const returnFocusId = useScopedIdOptional(tab, "tab");
    const [name, setName] = usePropState(tab.label);
    const handleRename = useCallback((newName) => {
        dispatch(renameDashboardTab(newName, tab.id));
        if (tab.id === DEFAULT_TAB_ID) {
            dispatch(convertDashboardTabFromDefault(newName));
        }
    }, [dispatch, tab.id]);
    const handleCancel = useCallback(() => {
        dispatch(cancelRenamingDashboardTab(tab.id));
    }, [dispatch, tab.id]);
    const preventPropagateKeydown = useCallback((e) => e.stopPropagation(), []);
    if (location === "allList" || !tab.isRenaming) {
        return _jsx(DefaultUiTabsTabValue, { ...props });
    }
    return (_jsx("div", { onKeyDown: preventPropagateKeydown, className: tabsBem.e("rename-wrapper"), children: _jsxs(UiFocusManager, { enableAutofocus: true, enableReturnFocusOnUnmount: { returnFocusTo: returnFocusId, focusVisible: false }, children: [
                _jsx("div", { className: tabsBem.e("rename-value"), children: _jsx(RenamingTabValue, { name: name, onChange: setName, onRename: handleRename, onCancel: handleCancel, isSubmitOnBlur: true }) }), _jsx("div", { className: tabsBem.e("rename-ghost-value"), children: _jsx(DefaultUiTabsTabValue, { ...props, 
                        // A little hack to prevent the input from jumping when empty
                        tab: { ...tab, label: name.length === 0 ? "M" : name } }) })
            ] }) }));
}
function RenamingTabValue(props) {
    const { name, isSubmitOnBlur, onChange, onCancel, onRename } = props;
    const handleChange = useCallback((e) => onChange(e.currentTarget.value), [onChange]);
    const handleSubmit = useCallback(() => onRename(name), [name, onRename]);
    const handleKeyDown = useCallback((e) => {
        if (e.key === "Enter") {
            handleSubmit();
        }
        if (e.key === "Escape") {
            onCancel();
        }
    }, [handleSubmit, onCancel]);
    // Id or name is required for an <input />.
    // We don't do anything with it, it's just here to prevent console warnings.
    const id = useId();
    return (_jsx("input", { className: tabsBem.e("rename-input"), onChange: handleChange, onBlur: isSubmitOnBlur ? handleSubmit : undefined, value: name, onKeyDown: handleKeyDown, name: id }));
}
//# sourceMappingURL=DashboardTabs.js.map