import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useMemo, useState } from 'react';
import { styled } from '@mui/material/styles';
import { Divider, Icon, IconButton, List, ListItem, ListItemButton, ListItemIcon, Menu, MenuItem, SwipeableDrawer, useMediaQuery, useTheme } from '@mui/material';
import { Link, SCPreferences, SCRoutes, UserUtils, useSCPreferences, useSCRouting, useSCUser } from '@selfcommunity/react-core';
import classNames from 'classnames';
import { useThemeProps } from '@mui/system';
import { FormattedMessage } from 'react-intl';
import { PreferenceService, UserService } from '@selfcommunity/api-services';
import { SCOPE_SC_UI } from '../../constants/Errors';
import { Logger } from '@selfcommunity/utils';
import { SCPreferenceName } from '@selfcommunity/types';
const PREFIX = 'SCNavigationSettingsIconButton';
const classes = {
    root: `${PREFIX}-root`,
    drawerRoot: `${PREFIX}-drawer-root`,
    menuRoot: `${PREFIX}-menu-root`,
    paper: `${PREFIX}-paper`,
    item: `${PREFIX}-item`
};
const Root = styled(IconButton, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.root
})(() => ({}));
const SwipeableDrawerRoot = styled(SwipeableDrawer, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.drawerRoot
})(() => ({}));
const MenuRoot = styled(Menu, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.menuRoot
})(() => ({}));
const PREFERENCES = [
    SCPreferences.CONFIGURATIONS_FOLLOW_ENABLED,
    SCPreferences.CONFIGURATIONS_POST_TYPE_ENABLED,
    SCPreferences.CONFIGURATIONS_DISCUSSION_TYPE_ENABLED,
    SCPreferences.ADDONS_LOYALTY_POINTS_COLLECTION,
    SCPreferences.CONFIGURATIONS_ONBOARDING_ENABLED,
    SCPreferences.CONFIGURATIONS_ONBOARDING_HIDDEN
];
/**
 * > API documentation for the Community-JS Navigation Settings Icon Button component. Learn about the available props and the CSS API.

 #### Import

 ```jsx
 import {ComposerIconButton} from '@selfcommunity/react-ui';
 ```

 #### Component Name

 The name `SNavigationSettingsIconButton` can be used when providing style overrides in the theme.


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SNavigationSettingsIconButton-root|Styles applied to the root element.|

 * @param inProps
 */
export default function NavigationSettingsIconButton(inProps) {
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { className = null, items = [] } = props, rest = __rest(props, ["className", "items"]);
    // STATE
    const [anchorEl, setAnchorEl] = useState(null);
    // CONTEXT
    const scUserContext = useSCUser();
    // MEMO
    const isAdmin = useMemo(() => UserUtils.isAdmin(scUserContext.user), [scUserContext.user]);
    const isCommunityCreator = useMemo(() => UserUtils.isCommunityCreator(scUserContext.user), [scUserContext.user]);
    const isModerator = useMemo(() => UserUtils.isModerator(scUserContext.user), [scUserContext.user]);
    // HOOKS
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));
    const scRoutingContext = useSCRouting();
    // PREFERENCES
    const scPreferences = useSCPreferences();
    const preferences = useMemo(() => {
        const _preferences = {};
        PREFERENCES.map((p) => (_preferences[p] = p in scPreferences.preferences ? scPreferences.preferences[p].value : null));
        return _preferences;
    }, [scPreferences.preferences]);
    // HANDLERS
    const handleOpen = (event) => {
        setAnchorEl(event.currentTarget);
    };
    const handleClose = () => {
        setAnchorEl(null);
    };
    /**
     * Fetches platform url
     * @param query
     */
    const fetchPlatform = (query) => {
        UserService.getCurrentUserPlatform(query).then((res) => {
            const platformUrl = res.platform_url;
            window.open(platformUrl, '_blank').focus();
        });
    };
    /**
     * Handles preferences update
     */
    const handlePreferencesUpdate = () => {
        PreferenceService.getAllPreferences().then((preferences) => {
            const prefs = preferences['results'].reduce((obj, p) => (Object.assign(Object.assign({}, obj), { [`${p.section}.${p.name}`]: p })), {});
            scPreferences.setPreferences(prefs);
        });
    };
    /**
     * Updates onBoarding dynamic preference
     */
    const showOnBoarding = () => {
        PreferenceService.updatePreferences({ [`${SCPreferenceName.ONBOARDING_HIDDEN}`]: false })
            .then(() => {
            handlePreferencesUpdate();
        })
            .catch((e) => {
            Logger.error(SCOPE_SC_UI, e);
        });
    };
    const handleLogout = () => {
        scUserContext.logout();
    };
    const renderList = () => {
        if (isMobile) {
            return [
                _jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsx(ListItemButton, Object.assign({ component: Link, to: scRoutingContext.url(SCRoutes.USER_PROFILE_ROUTE_NAME, scUserContext.user) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.profile", defaultMessage: "ui.navigationSettingsIconButton.profile" }) })) }), "profile"),
                preferences[SCPreferences.CONFIGURATIONS_FOLLOW_ENABLED] && (_jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsx(ListItemButton, Object.assign({ component: Link, to: scRoutingContext.url(SCRoutes.USER_PROFILE_FOLLOWINGS_ROUTE_NAME, scUserContext.user) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.followings", defaultMessage: "ui.navigationSettingsIconButton.followings" }) })) }), "followings")),
                preferences[SCPreferences.CONFIGURATIONS_FOLLOW_ENABLED] && (_jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsx(ListItemButton, Object.assign({ component: Link, to: scRoutingContext.url(SCRoutes.USER_PROFILE_FOLLOWERS_ROUTE_NAME, scUserContext.user) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.followers", defaultMessage: "ui.navigationSettingsIconButton.followers" }) })) }), "followers")),
                !preferences[SCPreferences.CONFIGURATIONS_FOLLOW_ENABLED] && (_jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsx(ListItemButton, Object.assign({ component: Link, to: scRoutingContext.url(SCRoutes.USER_PROFILE_CONNECTIONS_ROUTE_NAME, scUserContext.user) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.connections", defaultMessage: "ui.navigationSettingsIconButton.connections" }) })) }), "connections")),
                preferences[SCPreferences.ADDONS_LOYALTY_POINTS_COLLECTION] && (_jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsx(ListItemButton, Object.assign({ component: Link, to: scRoutingContext.url(SCRoutes.LOYALTY_ROUTE_NAME, {}) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.loyalty", defaultMessage: "ui.navigationSettingsIconButton.loyalty" }) })) }), "loyaltyProgram")),
                preferences[SCPreferences.CONFIGURATIONS_POST_TYPE_ENABLED] && (_jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsx(ListItemButton, Object.assign({ component: Link, to: scRoutingContext.url(SCRoutes.USER_PROFILE_FOLLOWED_POSTS_ROUTE_NAME, scUserContext.user) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.postsFollowed", defaultMessage: "ui.navigationSettingsIconButton.postsFollowed" }) })) }), "followedPosts")),
                preferences[SCPreferences.CONFIGURATIONS_DISCUSSION_TYPE_ENABLED] && (_jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsx(ListItemButton, Object.assign({ component: Link, to: scRoutingContext.url(SCRoutes.USER_PROFILE_FOLLOWED_DISCUSSIONS_ROUTE_NAME, scUserContext.user) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.discussionsFollowed", defaultMessage: "ui.navigationSettingsIconButton.discussionsFollowed" }) })) }), "followedDiscussions")),
                _jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsx(ListItemButton, Object.assign({ component: Link, to: scRoutingContext.url(SCRoutes.USER_PRIVATE_MESSAGES_ROUTE_NAME, {}) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.privateMessages", defaultMessage: "ui.navigationSettingsIconButton.privateMessages" }) })) }), "privateMessages"),
                ...items.map((item, index) => (_jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsx(ListItemButton, Object.assign({ component: Link, to: item.href }, { children: item.label })) }), `custom_item_${index}`))),
                ...(isAdmin
                    ? [
                        _jsx(Divider, {}, "admin_divider"),
                        isCommunityCreator &&
                            preferences[SCPreferences.CONFIGURATIONS_ONBOARDING_ENABLED] &&
                            preferences[SCPreferences.CONFIGURATIONS_ONBOARDING_HIDDEN] && (_jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsxs(ListItemButton, Object.assign({ onClick: showOnBoarding }, { children: [_jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.onboarding", defaultMessage: "ui.navigationSettingsIconButton.onboarding" }), _jsx(ListItemIcon, { children: _jsx(Icon, { children: "magic_wand" }) })] })) }), "onboarding")),
                        _jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsx(ListItemButton, Object.assign({ onClick: () => fetchPlatform('') }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.platform", defaultMessage: "ui.navigationSettingsIconButton.platform" }) })) }), "platform")
                    ]
                    : []),
                ...(isModerator || isAdmin
                    ? [
                        _jsx(Divider, {}, "moderation_divider"),
                        _jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsx(ListItemButton, Object.assign({ onClick: () => fetchPlatform('/moderation/flags/') }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.moderation", defaultMessage: "ui.navigationSettingsIconButton.moderation" }) })) }), "moderation")
                    ]
                    : []),
                _jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsx(ListItemButton, Object.assign({ component: Link, to: scRoutingContext.url(SCRoutes.USER_PROFILE_SETTINGS_ROUTE_NAME, scUserContext.user) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.settings", defaultMessage: "ui.navigationSettingsIconButton.settings" }) })) }), "settings"),
                _jsx(Divider, {}, "divider"),
                _jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsx(ListItemButton, Object.assign({ onClick: handleLogout }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.logout", defaultMessage: "ui.navigationSettingsIconButton.logout" }) })) }), "logout")
            ];
        }
        else {
            return [
                _jsx(MenuItem, Object.assign({ className: classes.item, component: Link, to: scRoutingContext.url(SCRoutes.USER_PROFILE_ROUTE_NAME, scUserContext.user) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.profile", defaultMessage: "ui.navigationSettingsIconButton.profile" }) }), "profile"),
                preferences[SCPreferences.CONFIGURATIONS_FOLLOW_ENABLED] && (_jsx(MenuItem, Object.assign({ className: classes.item, component: Link, to: scRoutingContext.url(SCRoutes.USER_PROFILE_FOLLOWINGS_ROUTE_NAME, scUserContext.user) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.followings", defaultMessage: "ui.navigationSettingsIconButton.followings" }) }), "followings")),
                preferences[SCPreferences.CONFIGURATIONS_FOLLOW_ENABLED] && (_jsx(MenuItem, Object.assign({ className: classes.item, component: Link, to: scRoutingContext.url(SCRoutes.USER_PROFILE_FOLLOWERS_ROUTE_NAME, scUserContext.user) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.followers", defaultMessage: "ui.navigationSettingsIconButton.followers" }) }), "followers")),
                !preferences[SCPreferences.CONFIGURATIONS_FOLLOW_ENABLED] && (_jsx(MenuItem, Object.assign({ className: classes.item, component: Link, to: scRoutingContext.url(SCRoutes.USER_PROFILE_CONNECTIONS_ROUTE_NAME, scUserContext.user) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.connections", defaultMessage: "ui.navigationSettingsIconButton.connections" }) }), "connections")),
                preferences[SCPreferences.ADDONS_LOYALTY_POINTS_COLLECTION] && (_jsx(MenuItem, Object.assign({ className: classes.item, component: Link, to: scRoutingContext.url(SCRoutes.LOYALTY_ROUTE_NAME, {}) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.loyalty", defaultMessage: "ui.navigationSettingsIconButton.loyalty" }) }), "loyaltyProgram")),
                preferences[SCPreferences.CONFIGURATIONS_POST_TYPE_ENABLED] && (_jsx(MenuItem, Object.assign({ className: classes.item, component: Link, to: scRoutingContext.url(SCRoutes.USER_PROFILE_FOLLOWED_POSTS_ROUTE_NAME, scUserContext.user) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.postsFollowed", defaultMessage: "ui.navigationSettingsIconButton.postsFollowed" }) }), "followedPosts")),
                preferences[SCPreferences.CONFIGURATIONS_DISCUSSION_TYPE_ENABLED] && (_jsx(MenuItem, Object.assign({ className: classes.item, component: Link, to: scRoutingContext.url(SCRoutes.USER_PROFILE_FOLLOWED_DISCUSSIONS_ROUTE_NAME, scUserContext.user) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.discussionsFollowed", defaultMessage: "ui.navigationSettingsIconButton.discussionsFollowed" }) }), "followedDiscussions")),
                _jsx(MenuItem, Object.assign({ className: classes.item, component: Link, to: scRoutingContext.url(SCRoutes.USER_PRIVATE_MESSAGES_ROUTE_NAME, {}) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.privateMessages", defaultMessage: "ui.navigationSettingsIconButton.privateMessages" }) }), "privateMessages"),
                ...items.map((item, index) => (_jsx(MenuItem, Object.assign({ className: classes.item, component: Link, to: item.href }, { children: item.label }), `custom_item_${index}`))),
                ...(isAdmin
                    ? [
                        _jsx(Divider, {}, "platform_divider"),
                        isCommunityCreator &&
                            preferences[SCPreferences.CONFIGURATIONS_ONBOARDING_ENABLED] &&
                            preferences[SCPreferences.CONFIGURATIONS_ONBOARDING_HIDDEN] && (_jsxs(MenuItem, Object.assign({ className: classes.item, onClick: showOnBoarding }, { children: [_jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.onboarding", defaultMessage: "ui.navigationSettingsIconButton.onboarding" }), _jsx(ListItemIcon, { children: _jsx(Icon, { children: "magic_wand" }) })] }), "onboarding")),
                        _jsx(MenuItem, Object.assign({ className: classes.item, onClick: () => fetchPlatform('') }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.platform", defaultMessage: "ui.navigationSettingsIconButton.platform" }) }), "platform")
                    ]
                    : []),
                ...(isModerator || isAdmin
                    ? [
                        _jsx(Divider, {}, "moderation_divider"),
                        _jsx(MenuItem, Object.assign({ className: classes.item, onClick: () => fetchPlatform('/moderation/flags/') }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.moderation", defaultMessage: "ui.navigationSettingsIconButton.moderation" }) }), "moderation")
                    ]
                    : []),
                _jsx(MenuItem, Object.assign({ className: classes.item, component: Link, to: scRoutingContext.url(SCRoutes.USER_PROFILE_SETTINGS_ROUTE_NAME, scUserContext.user) }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.settings", defaultMessage: "ui.navigationSettingsIconButton.settings" }) }), "settings"),
                _jsx(Divider, {}, "divider"),
                _jsx(MenuItem, Object.assign({ className: classes.item, onClick: handleLogout }, { children: _jsx(FormattedMessage, { id: "ui.navigationSettingsIconButton.logout", defaultMessage: "ui.navigationSettingsIconButton.logout" }) }), "logout")
            ];
        }
    };
    // RENDER
    if (!scUserContext.user) {
        return null;
    }
    return (_jsxs(_Fragment, { children: [_jsx(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { onClick: handleOpen }, { children: _jsx(Icon, { children: "more_vert" }) })), isMobile ? (_jsx(SwipeableDrawerRoot, Object.assign({ onClick: () => setAnchorEl(null), className: classes.drawerRoot, anchor: "bottom", open: Boolean(anchorEl), onClose: handleClose, onOpen: handleOpen, PaperProps: { className: classes.paper }, disableSwipeToOpen: true }, { children: _jsx(List, { children: renderList() }) }))) : (_jsx(MenuRoot, Object.assign({ onClick: () => setAnchorEl(null), className: classes.menuRoot, anchorEl: anchorEl, open: Boolean(anchorEl), onClose: handleClose, PaperProps: { className: classes.paper } }, { children: renderList() })))] }));
}
