import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2022-2026 GoodData Corporation
import { useCallback, useEffect, useRef } from "react";
import cx from "classnames";
import { FormattedMessage } from "react-intl";
import { makeMenuKeyboardNavigation } from "../../../../@ui/@utils/keyboardNavigation.js";
import { withBubble } from "../../../../Bubble/withBubble.js";
import { ItemsWrapper, Separator } from "../../../../List/MenuList.js";
import { granularPermissionMessageLabels } from "../../../../locales.js";
import { Overlay } from "../../../../Overlay/Overlay.js";
import { useShareDialogInteraction } from "../ComponentInteractionContext.js";
import { GranularPermissionSelectItemWithBubble } from "./GranularPermissionItem.js";
const overlayAlignPoints = [{ align: "br tr" }];
const REMOVE_GRANULAR_PERMISSION_ID = "granular-permission-remove-id";
function RemoveItem({ disabled, tooltipId, onClick, }) {
    const className = cx("gd-list-item gd-menu-item", "s-granular-permission-remove", {
        "is-disabled": disabled,
    });
    const FormattedMessageWithBubble = withBubble(FormattedMessage);
    return (_jsx("div", { id: REMOVE_GRANULAR_PERMISSION_ID, role: "option", tabIndex: disabled ? -1 : 0, className: className, onClick: onClick, children: _jsx(FormattedMessageWithBubble, { id: granularPermissionMessageLabels.remove.id, showBubble: disabled, bubbleTextId: tooltipId }) }));
}
export function GranularPermissionsDropdownBody({ grantee, granteePossibilities, alignTo, selectedPermission, toggleDropdown, onChange, onDelete, handleSetSelectedPermission, mode, id, }) {
    const { permissionsChangeInteraction, permissionsRemoveInteraction } = useShareDialogInteraction();
    const dropdownRef = useRef(null);
    const selectedItemRef = useRef(null);
    useEffect(() => {
        if (selectedItemRef.current) {
            setTimeout(() => {
                selectedItemRef.current?.focus();
            }, 100);
        }
    }, []);
    const handleOnDelete = useCallback(() => {
        if (granteePossibilities.remove.enabled) {
            const changedGrantee = {
                ...grantee,
                permissions: [],
                inheritedPermissions: [],
            };
            onDelete(changedGrantee);
            permissionsRemoveInteraction(grantee, mode === "ShareGrantee", granteePossibilities.assign.effective);
            toggleDropdown();
        }
    }, [grantee, onDelete, toggleDropdown, mode, granteePossibilities, permissionsRemoveInteraction]);
    const handleOnChange = useCallback((changedGrantee) => {
        permissionsChangeInteraction(grantee, mode === "ShareGrantee", granteePossibilities.assign.effective, changedGrantee.permissions[0]);
        onChange(changedGrantee);
    }, [grantee, onChange, mode, granteePossibilities, permissionsChangeInteraction]);
    const handleKeyDown = useCallback((event) => {
        if (!dropdownRef.current)
            return;
        const items = Array.from(dropdownRef.current.querySelectorAll('[tabIndex="0"]'));
        const currentIndex = items.findIndex((item) => item === document.activeElement);
        const keyboardHandler = makeMenuKeyboardNavigation({
            onFocusPrevious: () => {
                if (currentIndex > 0) {
                    items[currentIndex - 1].focus();
                }
                else {
                    items[items.length - 1].focus();
                }
            },
            onFocusNext: () => {
                if (currentIndex < items.length - 1) {
                    items[currentIndex + 1].focus();
                }
                else {
                    items[0].focus();
                }
            },
            onFocusFirst: () => {
                items[0].focus();
            },
            onFocusLast: () => {
                items[items.length - 1].focus();
            },
            onSelect: () => {
                if (document.activeElement) {
                    const activeElement = document.activeElement;
                    if (activeElement.id === REMOVE_GRANULAR_PERMISSION_ID) {
                        handleOnDelete();
                    }
                    else {
                        const permissionId = activeElement.id;
                        if (permissionId && permissionId !== selectedPermission) {
                            const changedGrantee = {
                                ...grantee,
                                permissions: [permissionId],
                            };
                            toggleDropdown();
                            handleSetSelectedPermission(permissionId);
                            handleOnChange(changedGrantee);
                        }
                        else {
                            toggleDropdown();
                        }
                    }
                }
            },
            onClose: () => {
                toggleDropdown();
            },
            onUnhandledKeyDown: (event) => {
                event.preventDefault();
            },
        });
        keyboardHandler(event);
    }, [
        toggleDropdown,
        handleOnDelete,
        handleOnChange,
        handleSetSelectedPermission,
        grantee,
        selectedPermission,
    ]);
    return (_jsx(Overlay, { alignTo: `.${alignTo}`, alignPoints: overlayAlignPoints, className: "s-granular-permissions-overlay", closeOnMouseDrag: true, closeOnOutsideClick: true, closeOnParentScroll: true, onClose: toggleDropdown, children: _jsx("div", { id: id, ref: dropdownRef, onBlur: (e) => e.stopPropagation(), onKeyDown: handleKeyDown, role: "listbox", children: _jsxs(ItemsWrapper, { smallItemsSpacing: true, children: [granteePossibilities.assign.items.map((permissionItem) => {
                        return (!permissionItem.hidden && (_jsx(GranularPermissionSelectItemWithBubble, { grantee: grantee, permission: permissionItem, selectedPermission: selectedPermission, toggleDropdown: toggleDropdown, onChange: handleOnChange, handleSetSelectedPermission: handleSetSelectedPermission, bubbleTextId: permissionItem.tooltip, showBubble: !permissionItem.enabled, ref: permissionItem.id === selectedPermission ? selectedItemRef : undefined }, permissionItem.id)));
                    }), _jsx(Separator, {}), _jsx(RemoveItem, { disabled: !granteePossibilities.remove.enabled, onClick: handleOnDelete, tooltipId: granteePossibilities.remove.tooltip ?? "" })
                ] }) }) }, "GranularPermissionsSelect"));
}
