"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const styles_1 = require("@mui/material/styles");
const material_1 = require("@mui/material");
const react_intl_1 = require("react-intl");
const Icon_1 = tslib_1.__importDefault(require("@mui/material/Icon"));
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const system_1 = require("@mui/system");
const react_core_1 = require("@selfcommunity/react-core");
const ConfirmDialog_1 = tslib_1.__importDefault(require("../../shared/ConfirmDialog/ConfirmDialog"));
const api_services_1 = require("@selfcommunity/api-services");
const utils_1 = require("@selfcommunity/utils");
const notistack_1 = require("notistack");
const pubsub_js_1 = tslib_1.__importDefault(require("pubsub-js"));
const PubSub_1 = require("../../constants/PubSub");
const GroupForm_1 = tslib_1.__importDefault(require("../../components/GroupForm"));
const GroupActionsMenu_1 = require("../../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 = (0, styles_1.styled)(material_1.IconButton, {
    name: PREFIX,
    slot: 'Root'
})(() => ({}));
const SwipeableDrawerRoot = (0, styles_1.styled)(material_1.SwipeableDrawer, {
    name: PREFIX,
    slot: 'DrawerRoot'
})(() => ({}));
const MenuRoot = (0, styles_1.styled)(material_1.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
 */
function GroupActionsMenu(inProps) {
    var _a;
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: PREFIX
    });
    const { className, group, groupId, onDeleteConfirm, onEditSuccess } = props, rest = tslib_1.__rest(props, ["className", "group", "groupId", "onDeleteConfirm", "onEditSuccess"]);
    // STATE
    const [anchorEl, setAnchorEl] = (0, react_1.useState)(null);
    const [openConfirmDialog, setOpenConfirmDialog] = (0, react_1.useState)(false);
    const [openEdit, setOpenEdit] = (0, react_1.useState)(false);
    // HOOKS
    const theme = (0, material_1.useTheme)();
    const isMobile = (0, material_1.useMediaQuery)(theme.breakpoints.down('md'));
    const scRoutingContext = (0, react_core_1.useSCRouting)();
    const scUserContext = (0, react_core_1.useSCUser)();
    const { scGroup, setSCGroup } = (0, react_core_1.useSCFetchGroup)({ id: groupId, group });
    const isGroupAdmin = (0, react_1.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() {
        api_services_1.GroupService.deleteGroup(scGroup.id)
            .then(() => {
            onDeleteConfirm();
            handleCloseDialog();
            pubsub_js_1.default.publish(`${PubSub_1.SCTopicType.GROUP}.${PubSub_1.SCGroupEventType.DELETE}`, scGroup.id);
        })
            .catch((error) => {
            setOpenConfirmDialog(false);
            console.log(error);
        });
    }
    /**
     * Handles actions
     */
    function handleAction(action) {
        if (action === GroupActionsMenu_1.GET_GROUP_LINK) {
            (0, utils_1.copyTextToClipboard)(`${location.protocol}//${location.host}${scRoutingContext.url(react_core_1.SCRoutes.GROUP_ROUTE_NAME, scGroup)}`).then(() => {
                (0, notistack_1.enqueueSnackbar)((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.common.permanentLinkCopied", defaultMessage: "ui.common.permanentLinkCopied" }), {
                    variant: 'success',
                    autoHideDuration: 3000
                });
            });
            handleClose();
        }
        else if (action === GroupActionsMenu_1.DELETE_GROUP) {
            setOpenConfirmDialog(true);
            handleClose();
        }
    }
    /**
     *
     */
    const renderList = () => {
        return [
            (0, jsx_runtime_1.jsxs)(material_1.MenuItem, Object.assign({ className: classes.item, onClick: () => handleAction(GroupActionsMenu_1.GET_GROUP_LINK) }, { children: [(0, jsx_runtime_1.jsx)(material_1.ListItemIcon, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "link" }) }), (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.groupActionsMenu.item.link", defaultMessage: "ui.groupActionsMenu.item.link" })] }), "link"),
            isGroupAdmin &&
                scGroup.active && [
                (0, jsx_runtime_1.jsx)(material_1.Divider, {}, "divider"),
                isMobile && ((0, jsx_runtime_1.jsxs)(material_1.MenuItem, Object.assign({ className: classes.item, onClick: handleEditClick }, { children: [(0, jsx_runtime_1.jsx)(material_1.ListItemIcon, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "edit" }) }), (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.groupActionsMenu.item.edit", defaultMessage: "ui.groupActionsMenu.item.edit" })] }), "edit")),
                (0, jsx_runtime_1.jsxs)(material_1.MenuItem, Object.assign({ className: classes.item, onClick: () => handleAction(GroupActionsMenu_1.DELETE_GROUP) }, { children: [(0, jsx_runtime_1.jsx)(material_1.ListItemIcon, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "delete" }) }), (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.groupActionsMenu.item.delete", defaultMessage: "ui.groupActionsMenu.item.delete" })] }), "delete")
            ]
        ];
    };
    if (!scGroup) {
        return null;
    }
    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)(Icon_1.default, { children: "more_vert" }) })), isMobile ? ((0, jsx_runtime_1.jsx)(SwipeableDrawerRoot, Object.assign({ className: classes.drawerRoot, anchor: "bottom", open: Boolean(anchorEl), onClose: handleClose, onOpen: handleOpen, PaperProps: { className: classes.paper }, 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, PaperProps: { className: classes.paper } }, { children: renderList() }))), openConfirmDialog && ((0, jsx_runtime_1.jsx)(ConfirmDialog_1.default, { open: openConfirmDialog, title: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.groupActionsMenu.dialog.msg", defaultMessage: "ui.groupActionsMenu.dialog.msg" }), btnConfirm: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.groupActionsMenu.dialog.confirm", defaultMessage: "ui.groupActionsMenu.dialog.confirm" }), onConfirm: handleDeleteThread, onClose: handleCloseDialog })), openEdit && (0, jsx_runtime_1.jsx)(GroupForm_1.default, { onClose: handleEditClick, group: scGroup, onSuccess: handleEditSuccess })] }));
}
exports.default = GroupActionsMenu;
