import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { Divider, IconButton, List, ListItemIcon, Menu, MenuItem, SwipeableDrawer, useMediaQuery, useTheme } from '@mui/material';
import Icon from '@mui/material/Icon';
import { styled } from '@mui/material/styles';
import { useThemeProps } from '@mui/system';
import { EventService } from '@selfcommunity/api-services';
import { SCRoutes, useSCFetchEvent, useSCRouting, useSCUser } from '@selfcommunity/react-core';
import { copyTextToClipboard } from '@selfcommunity/utils';
import classNames from 'classnames';
import { enqueueSnackbar } from 'notistack';
import PubSub from 'pubsub-js';
import { useMemo, useState } from 'react';
import { FormattedMessage } from 'react-intl';
import EventForm from '../../components/EventForm';
import { ADD_EVENT_TO_CALENDAR, CANCEL_EVENT, GET_EVENT_LINK } from '../../constants/EventActionsMenu';
import { SCGroupEventType, SCTopicType } from '../../constants/PubSub';
import ConfirmDialog from '../../shared/ConfirmDialog/ConfirmDialog';
import { checkEventFinished } from '../../utils/events';
const PREFIX = 'SCEventActionsMenu';
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 EventActionsMenu component. Learn about the available props and the CSS API.

 #### Import

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

 #### Component Name

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


 #### CSS

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


 * @param inProps
 */
export default function EventActionsMenu(inProps) {
    var _a;
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { className, event, eventId, onDeleteConfirm, onEditSuccess } = props, rest = __rest(props, ["className", "event", "eventId", "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 { scEvent, setSCEvent } = useSCFetchEvent({ id: eventId, event });
    const isEventAdmin = useMemo(() => { var _a; return scUserContext.user && ((_a = scEvent === null || scEvent === void 0 ? void 0 : scEvent.managed_by) === null || _a === void 0 ? void 0 : _a.id) === scUserContext.user.id; }, [scUserContext.user, (_a = scEvent === null || scEvent === void 0 ? void 0 : scEvent.managed_by) === null || _a === void 0 ? void 0 : _a.id]);
    const isEventFinished = useMemo(() => checkEventFinished(scEvent), [scEvent]);
    // HANDLERS
    const handleOpen = (event) => {
        setAnchorEl(event.currentTarget);
    };
    const handleClose = () => {
        setAnchorEl(null);
    };
    const handleEditClick = () => {
        setOpenEdit((o) => !o);
    };
    const handleCloseDialog = () => {
        setOpenConfirmDialog(false);
        setAnchorEl(null);
    };
    const handleEditSuccess = (data) => {
        setSCEvent(data);
        onEditSuccess && onEditSuccess(data);
    };
    /**
     * Handles thread deletion
     */
    function handleDeleteThread() {
        EventService.deleteEvent(scEvent.id)
            .then(() => {
            onDeleteConfirm();
            handleCloseDialog();
            PubSub.publish(`${SCTopicType.EVENT}.${SCGroupEventType.DELETE}`, scEvent.id);
        })
            .catch((error) => {
            setOpenConfirmDialog(false);
            console.log(error);
        });
    }
    const createGoogleCalendarLink = (event) => {
        const baseUrl = 'https://www.google.com/calendar/render?action=TEMPLATE';
        return `${baseUrl}&text=${encodeURIComponent(event.name)}&details=${encodeURIComponent(event.description)}&location=${encodeURIComponent(event.geolocation)}&dates=${event.start_date}/${event.end_date}`;
    };
    /**
     * Handles actions
     */
    function handleAction(action) {
        if (action === GET_EVENT_LINK) {
            copyTextToClipboard(`${location.protocol}//${location.host}${scRoutingContext.url(SCRoutes.EVENT_ROUTE_NAME, scEvent)}`).then(() => {
                enqueueSnackbar(_jsx(FormattedMessage, { id: "ui.common.permanentLinkCopied", defaultMessage: "ui.common.permanentLinkCopied" }), {
                    variant: 'success',
                    autoHideDuration: 3000
                });
            });
            handleClose();
        }
        else if (action === ADD_EVENT_TO_CALENDAR) {
            window.open(createGoogleCalendarLink(scEvent), '_blank', 'noopener,noreferrer');
            handleClose();
        }
        else if (action === CANCEL_EVENT) {
            setOpenConfirmDialog(true);
            handleClose();
        }
    }
    /**
     *
     */
    const renderList = () => {
        return [
            _jsxs(MenuItem, Object.assign({ className: classes.item, onClick: () => handleAction(GET_EVENT_LINK) }, { children: [_jsx(ListItemIcon, { children: _jsx(Icon, { children: "link" }) }), _jsx(FormattedMessage, { id: "ui.shared.eventActionsMenu.item.link", defaultMessage: "ui.shared.eventActionsMenu.item.link" })] }), "link"),
            !isEventFinished && (_jsxs(MenuItem, Object.assign({ className: classes.item, onClick: () => handleAction(ADD_EVENT_TO_CALENDAR) }, { children: [_jsx(ListItemIcon, { children: _jsx(Icon, { children: "CalendarIcon" }) }), _jsx(FormattedMessage, { id: "ui.shared.eventActionsMenu.item.calendar", defaultMessage: "ui.shared.eventActionsMenu.item.calendar" })] }), "calendar")),
            isEventAdmin &&
                !isEventFinished && [
                _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.shared.eventActionsMenu.item.edit", defaultMessage: "ui.shared.eventActionsMenu.item.edit" })] }), "edit")),
                _jsxs(MenuItem, Object.assign({ className: classes.item, onClick: () => handleAction(CANCEL_EVENT) }, { children: [_jsx(ListItemIcon, { children: _jsx(Icon, { children: "close" }) }), _jsx(FormattedMessage, { id: "ui.shared.eventActionsMenu.item.cancel", defaultMessage: "ui.shared.eventActionsMenu.item.cancel" })] }), "cancel")
            ]
        ];
    };
    if (!scEvent) {
        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.shared.eventActionsMenu.dialog.msg", defaultMessage: "ui.shared.eventActionsMenu.dialog.msg" }), btnConfirm: _jsx(FormattedMessage, { id: "ui.shared.eventActionsMenu.dialog.confirm", defaultMessage: "ui.shared.eventActionsMenu.dialog.confirm" }), onConfirm: handleDeleteThread, onClose: handleCloseDialog })), openEdit && _jsx(EventForm, { onClose: handleEditClick, event: scEvent, onSuccess: handleEditSuccess })] }));
}
