"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const lab_1 = require("@mui/lab");
const material_1 = require("@mui/material");
const styles_1 = require("@mui/material/styles");
const system_1 = require("@mui/system");
const react_core_1 = require("@selfcommunity/react-core");
const types_1 = require("@selfcommunity/types");
const utils_1 = require("@selfcommunity/utils");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const pubsub_js_1 = tslib_1.__importDefault(require("pubsub-js"));
const react_1 = require("react");
const react_intl_1 = require("react-intl");
const Errors_1 = require("../../constants/Errors");
const PubSub_1 = require("../../constants/PubSub");
const PREFIX = 'SCEventSubscribeButton';
const classes = {
    requestRoot: `${PREFIX}-request-root`,
    selectRoot: `${PREFIX}-select-root`,
    drawerRoot: `${PREFIX}-drawer-root`,
    menuRoot: `${PREFIX}-menu-root`,
    paper: `${PREFIX}-paper`,
    item: `${PREFIX}-item`,
    going: `${PREFIX}-going`,
    notGoing: `${PREFIX}-not-going`
};
const options = [
    {
        value: types_1.SCEventSubscriptionStatusType.GOING,
        label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventSubscribeButton.going", defaultMessage: "ui.eventSubscribeButton.going" })
    },
    {
        value: types_1.SCEventSubscriptionStatusType.NOT_GOING,
        label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventSubscribeButton.notGoing", defaultMessage: "ui.eventSubscribeButton.notGoing" })
    }
];
const RequestRoot = (0, styles_1.styled)(lab_1.LoadingButton, {
    name: PREFIX,
    slot: 'RequestRoot'
})(() => ({}));
const SelectRoot = (0, styles_1.styled)(material_1.Button, {
    name: PREFIX,
    slot: 'SelectRoot'
})(() => ({}));
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 Event Subscribe Button component. Learn about the available props and the CSS API.

 #### Import

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

 #### Component Name

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


 #### CSS

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

 * @param inProps
 */
function EventSubscribeButton(inProps) {
    var _a;
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: PREFIX
    });
    const { className, eventId, event, user, onSubscribe } = props, rest = tslib_1.__rest(props, ["className", "eventId", "event", "user", "onSubscribe"]);
    // STATE
    const [status, setStatus] = (0, react_1.useState)(undefined);
    const [loading, setLoading] = (0, react_1.useState)(false);
    const [anchorEl, setAnchorEl] = (0, react_1.useState)(null);
    const open = Boolean(anchorEl);
    // CONTEXT
    const scContext = (0, react_core_1.useSCContext)();
    const scUserContext = (0, react_core_1.useSCUser)();
    const scEventsManager = scUserContext.managers.events;
    const theme = (0, material_1.useTheme)();
    const isMobile = (0, material_1.useMediaQuery)(theme.breakpoints.down('md'));
    // CONST
    const authUserId = scUserContext.user ? scUserContext.user.id : null;
    const { scEvent, setSCEvent } = (0, react_core_1.useSCFetchEvent)({
        id: eventId,
        event,
        cacheStrategy: authUserId ? utils_1.CacheStrategies.CACHE_FIRST : utils_1.CacheStrategies.STALE_WHILE_REVALIDATE
    });
    const isEventAdmin = (0, react_1.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]);
    // HANDLERS
    const handleOpen = (0, react_1.useCallback)((event) => {
        setAnchorEl(event.currentTarget);
    }, [setAnchorEl]);
    const handleClose = (0, react_1.useCallback)(() => {
        setAnchorEl(null);
    }, [setAnchorEl]);
    (0, react_1.useEffect)(() => {
        /**
         * Call scEventsManager.subscriptionStatus inside an effect
         * to avoid warning rendering child during update parent state
         */
        if (authUserId) {
            setStatus(scEventsManager === null || scEventsManager === void 0 ? void 0 : scEventsManager.subscriptionStatus(scEvent));
        }
    }, [authUserId, scEventsManager === null || scEventsManager === void 0 ? void 0 : scEventsManager.subscriptionStatus, scEvent]);
    const toggleEventAttendance = (0, react_1.useCallback)((eventStatus) => {
        setLoading(true);
        const isGoing = eventStatus === types_1.SCEventSubscriptionStatusType.GOING ||
            !(scEvent === null || scEvent === void 0 ? void 0 : scEvent.subscription_status) ||
            (scEvent === null || scEvent === void 0 ? void 0 : scEvent.subscription_status) === types_1.SCEventSubscriptionStatusType.INVITED;
        const toggleAction = isGoing ? scEventsManager.toggleEventAttendance(scEvent) : scEventsManager.toggleEventNonattendance(scEvent);
        toggleAction
            .then((data) => {
            onSubscribe ? onSubscribe(data) : setSCEvent(data);
            setLoading(false);
            pubsub_js_1.default.publish(`${PubSub_1.SCTopicType.EVENT}.${PubSub_1.SCGroupEventType.MEMBERS}`);
        })
            .catch((e) => {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, e);
        });
    }, [scEvent, scEventsManager, onSubscribe, setLoading]);
    const handleToggleAction = (0, react_1.useCallback)((event) => {
        setAnchorEl(null);
        if (!scUserContext.user) {
            scContext.settings.handleAnonymousAction();
        }
        else if (status !== undefined) {
            toggleEventAttendance(event.target.value);
        }
    }, [scUserContext.user, status, scContext.settings]);
    function renderMenuItems() {
        return ((0, jsx_runtime_1.jsx)(material_1.Box, { children: options.map((option) => ((0, jsx_runtime_1.jsx)(material_1.MenuItem, Object.assign({ className: classes.item, disabled: loading }, { children: (0, jsx_runtime_1.jsx)(material_1.FormControlLabel, { label: option.label, control: loading ? ((0, jsx_runtime_1.jsx)(material_1.CircularProgress, { color: "primary", size: 20 })) : ((0, jsx_runtime_1.jsx)(material_1.Checkbox, { size: "small", checked: status === option.value, value: option.value, onChange: handleToggleAction, name: `${option.value}-option`, inputProps: { 'aria-label': `${option.label}` } })), labelPlacement: "start" }) }), option.value))) }));
    }
    /**
     * Get current translated status
     */
    const getStatus = (0, react_1.useMemo)(() => {
        let _status;
        switch (status) {
            case types_1.SCEventSubscriptionStatusType.REQUESTED:
                _status = (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.eventSubscribeButton.waitingApproval", id: "ui.eventSubscribeButton.waitingApproval" });
                break;
            case types_1.SCEventSubscriptionStatusType.GOING:
                _status = (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.eventSubscribeButton.going", id: "ui.eventSubscribeButton.going" });
                break;
            case types_1.SCEventSubscriptionStatusType.INVITED:
                _status = (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.eventSubscribeButton.accept", id: "ui.eventSubscribeButton.accept" });
                break;
            case types_1.SCEventSubscriptionStatusType.NOT_GOING:
                _status = (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.eventSubscribeButton.notGoing", id: "ui.eventSubscribeButton.notGoing" });
                break;
            default:
                (scEvent === null || scEvent === void 0 ? void 0 : scEvent.privacy) === types_1.SCEventPrivacyType.PUBLIC || status === types_1.SCEventSubscriptionStatusType.SUBSCRIBED
                    ? (_status = (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.eventSubscribeButton.label", id: "ui.eventSubscribeButton.label" }))
                    : (_status = ((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.eventSubscribeButton.requestParticipation", id: "ui.eventSubscribeButton.requestParticipation" })));
                break;
        }
        return _status;
    }, [status, scEvent]);
    if (!scEvent || (isEventAdmin && (user === null || user === void 0 ? void 0 : user.id) === scUserContext.user.id) || (isEventAdmin && !(user === null || user === void 0 ? void 0 : user.id))) {
        return null;
    }
    return ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: (scEvent === null || scEvent === void 0 ? void 0 : scEvent.privacy) === types_1.SCEventPrivacyType.PRIVATE && (!status || status === types_1.SCEventSubscriptionStatusType.REQUESTED) ? ((0, jsx_runtime_1.jsx)(RequestRoot, Object.assign({ className: (0, classnames_1.default)(classes.requestRoot, className), variant: "outlined", size: "small", loading: scUserContext.user ? scEventsManager.isLoading(scEvent) : null, onClick: handleToggleAction }, rest, { children: getStatus }))) : ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(SelectRoot, Object.assign({ className: (0, classnames_1.default)(classes.selectRoot, className, { [classes.going]: status && status === types_1.SCEventSubscriptionStatusType.GOING }, { [classes.notGoing]: status && status === types_1.SCEventSubscriptionStatusType.NOT_GOING }), onClick: handleOpen, endIcon: (0, jsx_runtime_1.jsx)(material_1.Icon, { children: open ? 'expand_less' : 'expand_more' }), startIcon: status &&
                        status !== types_1.SCEventSubscriptionStatusType.SUBSCRIBED && ((0, jsx_runtime_1.jsx)(material_1.Icon, { children: status === types_1.SCEventSubscriptionStatusType.GOING ? 'circle_checked' : 'circle_closed' })) }, rest, { children: getStatus })), isMobile ? ((0, jsx_runtime_1.jsx)(SwipeableDrawerRoot, Object.assign({ className: classes.drawerRoot, PaperProps: { className: classes.paper }, open: open, onClose: handleClose, onOpen: handleOpen, anchor: "bottom", disableSwipeToOpen: true }, { children: renderMenuItems() }))) : ((0, jsx_runtime_1.jsx)(MenuRoot, Object.assign({ className: classes.menuRoot, anchorEl: anchorEl, open: open, onClose: handleClose }, { children: renderMenuItems() })))] })) }));
}
exports.default = EventSubscribeButton;
