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, IconButton, List, ListItemIcon, Menu, MenuItem, SwipeableDrawer, useMediaQuery, useTheme } from '@mui/material';
import { FormattedMessage } from 'react-intl';
import Icon from '@mui/material/Icon';
import classNames from 'classnames';
import { useThemeProps } from '@mui/system';
import { SCRoutes, useSCFetchGroup, useSCRouting, useSCUser } from '@selfcommunity/react-core';
import ConfirmDialog from '../../shared/ConfirmDialog/ConfirmDialog';
import { GroupService } from '@selfcommunity/api-services';
import { copyTextToClipboard } from '@selfcommunity/utils';
import { enqueueSnackbar } from 'notistack';
import PubSub from 'pubsub-js';
import { SCGroupEventType, SCTopicType } from '../../constants/PubSub';
import GroupForm from '../../components/GroupForm';
import { DELETE_GROUP, GET_GROUP_LINK } from '../../constants/GroupActionsMenu';
const PREFIX = 'SCGroupActionsMenu';
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 GroupActionsMenu component. Learn about the available props and the CSS API.

 #### Import

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

 #### Component Name

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


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCGroupActionsMenu-root|Styles applied to the root element.|
 |drawerRoot|.SCGroupActionsMenu-drawer-root|Styles applied to the drawer root element.|
 |menuRoot|.SCGroupActionsMenu-menu-root|Styles applied to the menu root element.|
 |paper|.SCGroupActionsMenu-paper|Styles applied to the paper element.|
 |item|.SCGroupActionsMenu-item|Styles applied to the item element.|


 * @param inProps
 */
export default function GroupActionsMenu(inProps) {
    var _a;
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { className, group, groupId, onDeleteConfirm, onEditSuccess } = props, rest = __rest(props, ["className", "group", "groupId", "onDeleteConfirm", "onEditSuccess"]);
    // STATE
    const [anchorEl, setAnchorEl] = useState(null);
    const [openConfirmDialog, setOpenConfirmDialog] = useState(false);
    const [openEdit, setOpenEdit] = useState(false);
    // HOOKS
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));
    const scRoutingContext = useSCRouting();
    const scUserContext = useSCUser();
    const { scGroup, setSCGroup } = useSCFetchGroup({ id: groupId, group });
    const isGroupAdmin = useMemo(() => { var _a; return scUserContext.user && ((_a = scGroup === null || scGroup === void 0 ? void 0 : scGroup.managed_by) === null || _a === void 0 ? void 0 : _a.id) === scUserContext.user.id; }, [scUserContext.user, (_a = scGroup === null || scGroup === void 0 ? void 0 : scGroup.managed_by) === null || _a === void 0 ? void 0 : _a.id]);
    // HANDLERS
    const handleOpen = (group) => {
        setAnchorEl(group.currentTarget);
    };
    const handleClose = () => {
        setAnchorEl(null);
    };
    const handleEditClick = () => {
        setOpenEdit((o) => !o);
    };
    const handleCloseDialog = () => {
        setOpenConfirmDialog(false);
        setAnchorEl(null);
    };
    const handleEditSuccess = (data) => {
        setSCGroup(data);
        onEditSuccess && onEditSuccess(data);
    };
    /**
     * Handles thread deletion
     */
    function handleDeleteThread() {
        GroupService.deleteGroup(scGroup.id)
            .then(() => {
            onDeleteConfirm();
            handleCloseDialog();
            PubSub.publish(`${SCTopicType.GROUP}.${SCGroupEventType.DELETE}`, scGroup.id);
        })
            .catch((error) => {
            setOpenConfirmDialog(false);
            console.log(error);
        });
    }
    /**
     * Handles actions
     */
    function handleAction(action) {
        if (action === GET_GROUP_LINK) {
            copyTextToClipboard(`${location.protocol}//${location.host}${scRoutingContext.url(SCRoutes.GROUP_ROUTE_NAME, scGroup)}`).then(() => {
                enqueueSnackbar(_jsx(FormattedMessage, { id: "ui.common.permanentLinkCopied", defaultMessage: "ui.common.permanentLinkCopied" }), {
                    variant: 'success',
                    autoHideDuration: 3000
                });
            });
            handleClose();
        }
        else if (action === DELETE_GROUP) {
            setOpenConfirmDialog(true);
            handleClose();
        }
    }
    /**
     *
     */
    const renderList = () => {
        return [
            _jsxs(MenuItem, Object.assign({ className: classes.item, onClick: () => handleAction(GET_GROUP_LINK) }, { children: [_jsx(ListItemIcon, { children: _jsx(Icon, { children: "link" }) }), _jsx(FormattedMessage, { id: "ui.groupActionsMenu.item.link", defaultMessage: "ui.groupActionsMenu.item.link" })] }), "link"),
            isGroupAdmin &&
                scGroup.active && [
                _jsx(Divider, {}, "divider"),
                isMobile && (_jsxs(MenuItem, Object.assign({ className: classes.item, onClick: handleEditClick }, { children: [_jsx(ListItemIcon, { children: _jsx(Icon, { children: "edit" }) }), _jsx(FormattedMessage, { id: "ui.groupActionsMenu.item.edit", defaultMessage: "ui.groupActionsMenu.item.edit" })] }), "edit")),
                _jsxs(MenuItem, Object.assign({ className: classes.item, onClick: () => handleAction(DELETE_GROUP) }, { children: [_jsx(ListItemIcon, { children: _jsx(Icon, { children: "delete" }) }), _jsx(FormattedMessage, { id: "ui.groupActionsMenu.item.delete", defaultMessage: "ui.groupActionsMenu.item.delete" })] }), "delete")
            ]
        ];
    };
    if (!scGroup) {
        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({ 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.groupActionsMenu.dialog.msg", defaultMessage: "ui.groupActionsMenu.dialog.msg" }), btnConfirm: _jsx(FormattedMessage, { id: "ui.groupActionsMenu.dialog.confirm", defaultMessage: "ui.groupActionsMenu.dialog.confirm" }), onConfirm: handleDeleteThread, onClose: handleCloseDialog })), openEdit && _jsx(GroupForm, { onClose: handleEditClick, group: scGroup, onSuccess: handleEditSuccess })] }));
}
