import { jsx } from "react/jsx-runtime";
import { createContext, useCallback, useMemo, useState } from "react";
import { error } from "@tachybase/utils/client";
import { UserOutlined } from "@ant-design/icons";
import { App, Dropdown, Menu } from "antd";
import { createStyles } from "antd-style";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { useACLRoleContext, useAPIClient, useCurrentUserContext, useToken } from "../index.mjs";
import { useChangePassword } from "./ChangePassword.mjs";
import { useCurrentUserSettingsMenu } from "./CurrentUserSettingsMenuProvider.mjs";
import { useEditProfile } from "./EditProfile.mjs";
import { useLanguageSettings } from "./LanguageSettings.mjs";
import { useSwitchRole } from "./SwitchRole.mjs";
function _tagged_template_literal(strings, raw) {
    if (!raw) raw = strings.slice(0);
    return Object.freeze(Object.defineProperties(strings, {
        raw: {
            value: Object.freeze(raw)
        }
    }));
}
function _templateObject() {
    const data = _tagged_template_literal([
        "\n      display: inline-block;\n      vertical-align: top;\n      width: 46px;\n      height: var(--tb-header-height);\n      &:hover {\n        background: rgba(255, 255, 255, 0.1) !important;\n      }\n    "
    ]);
    _templateObject = function() {
        return data;
    };
    return data;
}
function _templateObject1() {
    const data = _tagged_template_literal([
        "\n      overflow: hidden;\n      display: inline-block;\n      line-height: var(--tb-header-height);\n      white-space: nowrap;\n      text-overflow: ellipsis;\n      cursor: pointer;\n      padding: 0 16px 0 16px;\n      color: ",
        ";\n    "
    ]);
    _templateObject1 = function() {
        return data;
    };
    return data;
}
const useNickname = ()=>{
    var _data_data, _data_data1, _data_data2;
    const { data } = useCurrentUserContext();
    const { token } = useToken();
    return useMemo(()=>{
        var _data_data, _data_data1, _data_data2;
        return {
            key: 'nickname',
            disabled: true,
            label: /*#__PURE__*/ jsx("span", {
                "aria-disabled": "false",
                style: {
                    cursor: 'text',
                    color: token.colorTextDescription
                },
                children: (null == data ? void 0 : null == (_data_data = data.data) ? void 0 : _data_data.nickname) || (null == data ? void 0 : null == (_data_data1 = data.data) ? void 0 : _data_data1.username) || (null == data ? void 0 : null == (_data_data2 = data.data) ? void 0 : _data_data2.email)
            })
        };
    }, [
        null == data ? void 0 : null == (_data_data = data.data) ? void 0 : _data_data.email,
        null == data ? void 0 : null == (_data_data1 = data.data) ? void 0 : _data_data1.nickname,
        null == data ? void 0 : null == (_data_data2 = data.data) ? void 0 : _data_data2.username,
        null == data ? void 0 : data.data.version,
        token.colorTextDescription
    ]);
};
const SettingsMenu = (props)=>{
    const { addMenuItem, getMenuItems } = useCurrentUserSettingsMenu();
    const { redirectUrl = '' } = props;
    const { allowAll, snippets } = useACLRoleContext();
    const appAllowed = allowAll || (null == snippets ? void 0 : snippets.includes('app'));
    const navigate = useNavigate();
    const api = useAPIClient();
    const { t } = useTranslation();
    const silenceApi = useAPIClient();
    const check = useCallback(async ()=>await new Promise((resolve)=>{
            const heartbeat = setInterval(()=>{
                silenceApi.silent().resource('app').getInfo().then((res)=>{
                    if ((null == res ? void 0 : res.status) === 200) {
                        resolve('ok');
                        clearInterval(heartbeat);
                    }
                    return res;
                }).catch((err)=>{
                    error(err);
                });
            }, 3000);
        }), [
        silenceApi
    ]);
    const nickname = useNickname();
    const editProfile = useEditProfile();
    const changePassword = useChangePassword();
    const switchRole = useSwitchRole();
    const languageSettings = useLanguageSettings();
    const { modal } = App.useApp();
    const controlApp = useMemo(()=>{
        if (!appAllowed) return [];
        return [
            {
                key: 'cache',
                label: t('Clear cache'),
                onClick: async ()=>{
                    await api.resource('app').clearCache();
                    window.location.reload();
                }
            },
            {
                key: 'reboot',
                label: t('Restart application'),
                onClick: async ()=>{
                    modal.confirm({
                        title: t('Restart application'),
                        okText: t('Restart'),
                        okButtonProps: {
                            danger: true
                        },
                        onOk: async ()=>{
                            await api.resource('app').restart();
                        }
                    });
                }
            },
            {
                key: 'divider_4',
                type: 'divider'
            }
        ];
    }, [
        api,
        appAllowed,
        check,
        modal,
        t
    ]);
    useMemo(()=>{
        const items = [
            nickname,
            {
                key: 'divider_1',
                type: 'divider'
            },
            editProfile,
            changePassword,
            {
                key: 'divider_2',
                type: 'divider'
            },
            switchRole,
            {
                key: 'divider_3',
                type: 'divider'
            },
            ...controlApp,
            {
                key: 'signout',
                label: t('Sign out'),
                onClick: async ()=>{
                    await api.auth.signOut();
                    navigate("/signin?redirect=".concat(encodeURIComponent(redirectUrl)));
                }
            }
        ];
        items.forEach((item)=>{
            if (item) addMenuItem(item);
        });
        if (languageSettings) addMenuItem(languageSettings, {
            before: 'divider_3'
        });
    }, [
        addMenuItem,
        api.auth,
        controlApp,
        editProfile,
        changePassword,
        languageSettings,
        navigate,
        redirectUrl,
        switchRole,
        t,
        nickname
    ]);
    return /*#__PURE__*/ jsx(Menu, {
        items: getMenuItems()
    });
};
const DropdownVisibleContext = /*#__PURE__*/ createContext(null);
DropdownVisibleContext.displayName = 'DropdownVisibleContext';
const useStyles = createStyles((param)=>{
    let { css, token } = param;
    return {
        dropdown: css(_templateObject()),
        button: css(_templateObject1(), token.colorTextHeaderMenu)
    };
});
const CurrentUser = ()=>{
    const [visible, setVisible] = useState(false);
    const { styles } = useStyles();
    return /*#__PURE__*/ jsx("div", {
        className: styles.dropdown,
        children: /*#__PURE__*/ jsx(DropdownVisibleContext.Provider, {
            value: {
                visible,
                setVisible
            },
            children: /*#__PURE__*/ jsx(Dropdown, {
                open: visible,
                onOpenChange: (visible)=>{
                    setVisible(visible);
                },
                dropdownRender: ()=>/*#__PURE__*/ jsx(SettingsMenu, {}),
                children: /*#__PURE__*/ jsx("span", {
                    "data-testid": "user-center-button",
                    className: styles.button,
                    children: /*#__PURE__*/ jsx(UserOutlined, {})
                })
            })
        })
    });
};
export { CurrentUser, DropdownVisibleContext, SettingsMenu };
