import { __rest } from "tslib";
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
import { styled } from '@mui/material/styles';
import { SwipeableDrawer, MenuItem, IconButton, Menu, useTheme, useMediaQuery, List, ListItem } from '@mui/material';
import { FormattedMessage } from 'react-intl';
import Icon from '@mui/material/Icon';
import classNames from 'classnames';
import { useThemeProps } from '@mui/system';
import { Link, SCRoutes, useSCRouting, useSCUser } from '@selfcommunity/react-core';
import ConfirmDialog from '../../shared/ConfirmDialog/ConfirmDialog';
import { GroupService } from '@selfcommunity/api-services';
import { SCGroupEventType, SCTopicType } from '../../constants/PubSub';
import PubSub from 'pubsub-js';
const PREFIX = 'SCGroupSettingsIconButton';
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'
})(() => ({}));
const SwipeableDrawerRoot = styled(SwipeableDrawer, {
    name: PREFIX,
    slot: 'DrawerRoot'
})(() => ({}));
const MenuRoot = styled(Menu, {
    name: PREFIX,
    slot: 'MenuRoot'
})(() => ({}));
/**
 * > API documentation for the Community-JS GroupSettingsIconButton component. Learn about the available props and the CSS API.

 #### Import

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

 #### Component Name

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


 #### CSS

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

 * @param inProps
 */
export default function GroupSettingsIconButton(inProps) {
    var _a;
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { className = null, group, user, onRemoveSuccess } = props, rest = __rest(props, ["className", "group", "user", "onRemoveSuccess"]);
    // STATE
    const [anchorEl, setAnchorEl] = useState(null);
    const [openConfirmDialog, setOpenConfirmDialog] = useState(false);
    // HOOKS
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));
    const scRoutingContext = useSCRouting();
    // CONTEXT
    const scUserContext = useSCUser();
    // HANDLERS
    const handleOpen = (event) => {
        setAnchorEl(event.currentTarget);
    };
    const handleClose = () => {
        setAnchorEl(null);
    };
    const handleOpenDialog = () => {
        setOpenConfirmDialog(true);
        setAnchorEl(null);
    };
    const handleCloseDialog = () => {
        setOpenConfirmDialog(false);
        setAnchorEl(null);
    };
    /**
     * Notify UI when a user is removed from a group
     * @param group
     * @param user
     */
    function notifyChanges(group, user) {
        if (group && user) {
            PubSub.publish(`${SCTopicType.GROUP}.${SCGroupEventType.REMOVE_MEMBER}`, { group, user });
        }
    }
    /**
     * Handles thread deletion
     */
    function handleRemoveUser() {
        GroupService.removeUserFromGroup(group.id, user.id)
            .then(() => {
            notifyChanges(group, user);
            onRemoveSuccess && onRemoveSuccess();
            handleCloseDialog();
        })
            .catch((error) => {
            setOpenConfirmDialog(false);
            console.log(error);
        });
    }
    if (((_a = scUserContext === null || scUserContext === void 0 ? void 0 : scUserContext.user) === null || _a === void 0 ? void 0 : _a.id) === (user === null || user === void 0 ? void 0 : user.id)) {
        return null;
    }
    /**
     *
     */
    const renderList = () => {
        if (isMobile) {
            return [
                _jsx(ListItem, Object.assign({ className: classes.item, component: Link, to: scRoutingContext.url(SCRoutes.USER_PRIVATE_MESSAGES_ROUTE_NAME, user) }, { children: _jsx(FormattedMessage, { id: "ui.groupSettingsIconButton.item.message", defaultMessage: "ui.groupSettingsIconButton.item.message" }) }), "message"),
                _jsx(ListItem, Object.assign({ className: classes.item, onClick: handleOpenDialog }, { children: _jsx(FormattedMessage, { id: "ui.groupSettingsIconButton.item.remove", defaultMessage: "ui.groupSettingsIconButton.item.remove" }) }), "delete")
            ];
        }
        else {
            return [
                _jsx(MenuItem, Object.assign({ className: classes.item, component: Link, to: scRoutingContext.url(SCRoutes.USER_PRIVATE_MESSAGES_ROUTE_NAME, user) }, { children: _jsx(FormattedMessage, { id: "ui.groupSettingsIconButton.item.message", defaultMessage: "ui.groupSettingsIconButton.item.message" }) }), "message"),
                _jsx(MenuItem, Object.assign({ className: classes.item, onClick: handleOpenDialog }, { children: _jsx(FormattedMessage, { id: "ui.groupSettingsIconButton.item.remove", defaultMessage: "ui.groupSettingsIconButton.item.remove" }) }), "delete")
            ];
        }
    };
    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({ 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({ className: classes.menuRoot, anchorEl: anchorEl, open: Boolean(anchorEl), onClose: handleClose, PaperProps: { className: classes.paper } }, { children: renderList() }))), openConfirmDialog && (_jsx(ConfirmDialog, { open: openConfirmDialog, title: _jsx(FormattedMessage, { id: "ui.groupSettingsIconButton.dialog.msg", defaultMessage: "ui.groupSettingsIconButton.dialog.msg", values: {
                        // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
                        // @ts-ignore
                        b: (...chunks) => _jsx("strong", { children: chunks }),
                        user: user.username,
                        group: group.name
                    } }), btnConfirm: _jsx(FormattedMessage, { id: "ui.groupSettingsIconButton.dialog.confirm", defaultMessage: "ui.groupSettingsIconButton.dialog.confirm" }), onConfirm: handleRemoveUser, onClose: handleCloseDialog }))] }));
}
