"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = tslib_1.__importStar(require("react"));
const styles_1 = require("@mui/material/styles");
const material_1 = require("@mui/material");
const react_core_1 = require("@selfcommunity/react-core");
const api_services_1 = require("@selfcommunity/api-services");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const system_1 = require("@mui/system");
const react_intl_1 = require("react-intl");
const UserInfoDialog_1 = tslib_1.__importDefault(require("../UserInfoDialog"));
const ConfirmDialog_1 = tslib_1.__importDefault(require("../../shared/ConfirmDialog/ConfirmDialog"));
const notistack_1 = require("notistack");
const PREFIX = 'SCUserActionIconButton';
const classes = {
    root: `${PREFIX}-root`,
    drawerRoot: `${PREFIX}-drawer-root`,
    menuRoot: `${PREFIX}-menu-root`
};
const Root = (0, styles_1.styled)(material_1.IconButton, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.root
})(({ theme }) => ({}));
const SwipeableDrawerRoot = (0, styles_1.styled)(material_1.SwipeableDrawer, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.drawerRoot
})(({ theme }) => ({}));
const MenuRoot = (0, styles_1.styled)(material_1.Menu, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.menuRoot
})(({ theme }) => ({}));
const Transition = react_1.default.forwardRef(function Transition(props, ref) {
    return (0, jsx_runtime_1.jsx)(material_1.Slide, Object.assign({ direction: "up", ref: ref }, props));
});
/**
 * > API documentation for the Community-JS User Action Menu component. Learn about the available props and the CSS API.

 #### Import

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

 #### Component Name

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


 #### CSS

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

 * @param inProps
 */
function UserActionIconButton(inProps) {
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: PREFIX
    });
    const { className = null, userId = null, user = null, items = [] } = props, rest = tslib_1.__rest(props, ["className", "userId", "user", "items"]);
    // CONTEXT
    const scUserContext = (0, react_core_1.useSCUser)();
    const scContext = (0, react_core_1.useSCContext)();
    // STATE
    const [anchorEl, setAnchorEl] = (0, react_1.useState)(null);
    const [infoOpen, setInfoOpen] = (0, react_1.useState)(false);
    const [isHiddenLoading, setHiddenLoading] = (0, react_1.useState)(false);
    const [hidden, setHidden] = (0, react_1.useState)(null);
    const [openHideDialog, setOpenHideDialog] = (0, react_1.useState)(false);
    // HOOKS
    const { scUser } = (0, react_core_1.useSCFetchUser)({ id: userId, user });
    const theme = (0, material_1.useTheme)();
    const isMobile = (0, material_1.useMediaQuery)(theme.breakpoints.down('md'));
    const { enqueueSnackbar } = (0, notistack_1.useSnackbar)();
    // HANDLERS
    const handleOpen = (event) => {
        setAnchorEl(event.currentTarget);
    };
    const handleClose = () => {
        setAnchorEl(null);
    };
    const handleInfoOpen = () => {
        setInfoOpen(true);
        setAnchorEl(null);
    };
    const handleInfoClose = () => {
        setInfoOpen(false);
    };
    const handleHideToggle = () => {
        setHiddenLoading(true);
        scUserContext.managers.blockedUsers
            .block(scUser)
            .then((blocked) => {
            setHidden(blocked);
        })
            .then(() => setHiddenLoading(false))
            .catch(() => {
            enqueueSnackbar((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.common.action.notPermitted", defaultMessage: "ui.common.action.notPermitted" }), {
                variant: 'warning',
                autoHideDuration: 7000
            });
            setHiddenLoading(false);
            handleHide();
        });
    };
    const handleHide = (0, react_1.useMemo)(() => () => {
        setOpenHideDialog((prev) => !prev);
        handleClose();
    }, [setOpenHideDialog, handleClose]);
    // MEMO
    const isMe = scUserContext.user && scUser.id === scUserContext.user.id;
    const roles = (0, react_1.useMemo)(() => scUserContext.user && (scUserContext === null || scUserContext === void 0 ? void 0 : scUserContext.user.role), [scUserContext.user]);
    const canModerate = (0, react_1.useMemo)(() => roles && (roles.includes('admin') || roles.includes('moderator')) && !isMe, [roles, isMe]);
    /**
     * Fetches platform url
     */
    function fetchPlatform(query) {
        api_services_1.http
            .request({
            url: api_services_1.Endpoints.Platform.url(),
            method: api_services_1.Endpoints.Platform.method,
            params: {
                next: query
            }
        })
            .then((res) => {
            handleClose();
            const platformUrl = res.data.platform_url;
            window.open(platformUrl, '_blank').focus();
        })
            .catch((error) => {
            console.log(error);
        });
    }
    // EFFECTS
    (0, react_1.useEffect)(() => {
        if (anchorEl && hidden === null && scUser) {
            setHidden(scUserContext.managers.blockedUsers.isBlocked(scUser));
        }
    }, [anchorEl, scUser]);
    // RENDER
    if (!scUserContext.user) {
        return null;
    }
    const renderList = () => {
        if (isMobile) {
            return [
                ...items.map((item, index) => ((0, jsx_runtime_1.jsx)(material_1.ListItem, { children: (0, jsx_runtime_1.jsx)(material_1.ListItemButton, Object.assign({ component: react_core_1.Link, to: item.to }, { children: (0, jsx_runtime_1.jsx)(material_1.ListItemText, { primary: item.label }) })) }, index))),
                (0, jsx_runtime_1.jsx)(material_1.ListItem, { children: (0, jsx_runtime_1.jsx)(material_1.ListItemButton, Object.assign({ onClick: handleInfoOpen }, { children: (0, jsx_runtime_1.jsx)(material_1.ListItemText, { primary: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.userActionIconButton.information", id: "ui.userActionIconButton.information" }) }) })) }, "info"),
                ...(isMe
                    ? []
                    : [
                        (0, jsx_runtime_1.jsx)(material_1.Divider, {}, "divider"),
                        (0, jsx_runtime_1.jsx)(material_1.ListItem, { children: (0, jsx_runtime_1.jsx)(material_1.ListItemButton, Object.assign({ onClick: handleHideToggle, disabled: isHiddenLoading || scUser.community_badge || (!hidden && react_core_1.UserUtils.isStaff(scUser)) }, { children: (0, jsx_runtime_1.jsx)(material_1.ListItemText, { primary: hidden ? ((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.userActionIconButton.show", id: "ui.userActionIconButton.show" })) : ((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.userActionIconButton.hide", id: "ui.userActionIconButton.hide" })) }) })) }, "hide"),
                        ...(canModerate
                            ? [
                                (0, jsx_runtime_1.jsx)(material_1.Divider, {}, "divider_moderate"),
                                (0, jsx_runtime_1.jsx)(material_1.ListItem, { children: (0, jsx_runtime_1.jsx)(material_1.ListItemButton, Object.assign({ component: react_core_1.Link, onClick: () => fetchPlatform(`/moderation/user/?username=${scUser.username}`) }, { children: (0, jsx_runtime_1.jsx)(material_1.ListItemText, { primary: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.userActionIconButton.moderate", id: "ui.userActionIconButton.moderate" }) }) })) }, "moderate")
                            ]
                            : [])
                    ])
            ];
        }
        else {
            return [
                ...items.map((item, index) => ((0, jsx_runtime_1.jsx)(material_1.MenuItem, Object.assign({ component: react_core_1.Link, to: item.to, onClick: handleClose }, { children: item.label }), index))),
                (0, jsx_runtime_1.jsx)(material_1.MenuItem, Object.assign({ onClick: handleInfoOpen }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.userActionIconButton.information", id: "ui.userActionIconButton.information" }) }), "info"),
                ...(isMe
                    ? []
                    : [
                        (0, jsx_runtime_1.jsx)(material_1.Divider, {}, "divider"),
                        (0, jsx_runtime_1.jsx)(material_1.MenuItem, Object.assign({ onClick: handleHide, disabled: isHiddenLoading || scUser.community_badge }, { children: hidden ? ((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.userActionIconButton.show", id: "ui.userActionIconButton.show" })) : ((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.userActionIconButton.hide", id: "ui.userActionIconButton.hide" })) }), "hide"),
                        ...(canModerate
                            ? [
                                (0, jsx_runtime_1.jsx)(material_1.Divider, {}, "divider_moderate"),
                                (0, jsx_runtime_1.jsx)(material_1.MenuItem, Object.assign({ component: react_core_1.Link, onClick: () => fetchPlatform(`/moderation/user/?username=${scUser.username}`) }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.userActionIconButton.moderate", id: "ui.userActionIconButton.moderate" }) }), "moderate")
                            ]
                            : [])
                    ])
            ];
        }
    };
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(Root, Object.assign({ className: (0, classnames_1.default)(classes.root, className) }, rest, { onClick: handleOpen }, { children: (0, jsx_runtime_1.jsx)(material_1.Icon, { children: "more_vert" }) })), isMobile ? ((0, jsx_runtime_1.jsx)(SwipeableDrawerRoot, Object.assign({ className: classes.drawerRoot, anchor: "bottom", open: Boolean(anchorEl), onClose: handleClose, onOpen: handleOpen, disableSwipeToOpen: true }, { children: (0, jsx_runtime_1.jsx)(material_1.List, { children: renderList() }) }))) : ((0, jsx_runtime_1.jsx)(MenuRoot, Object.assign({ className: classes.menuRoot, anchorEl: anchorEl, open: Boolean(anchorEl), onClose: handleClose }, { children: renderList() }))), (0, jsx_runtime_1.jsx)(UserInfoDialog_1.default, { userId: userId, user: scUser, open: infoOpen, onClose: handleInfoClose }), openHideDialog && ((0, jsx_runtime_1.jsx)(ConfirmDialog_1.default, { open: openHideDialog, isUpdating: isHiddenLoading, TransitionComponent: Transition, keepMounted: true, title: hidden ? ((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.userActionIconButton.show", id: "ui.userActionIconButton.show" })) : ((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.userActionIconButton.hide", id: "ui.userActionIconButton.hide" })), content: hidden ? ((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.userActionIconButton.dialogShowAction", id: "ui.userActionIconButton.dialogShowAction" })) : ((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.userActionIconButton.dialogHideAction", id: "ui.userActionIconButton.dialogHideAction" })), onConfirm: handleHideToggle, onClose: () => setOpenHideDialog(false) }))] }));
}
exports.default = UserActionIconButton;
