"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const material_1 = require("@mui/material");
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 react_1 = require("react");
const react_intl_1 = require("react-intl");
const Errors_1 = require("../../constants/Errors");
const PubSub_1 = require("../../constants/PubSub");
const BaseDialog_1 = tslib_1.__importDefault(require("../../shared/BaseDialog"));
const InfiniteScroll_1 = tslib_1.__importDefault(require("../../shared/InfiniteScroll"));
const widget_1 = require("../../utils/widget");
const AcceptRequestUserEventButton_1 = tslib_1.__importDefault(require("../AcceptRequestUserEventButton"));
const EventInviteButton_1 = tslib_1.__importDefault(require("../EventInviteButton"));
const InviteUserEventButton_1 = tslib_1.__importDefault(require("../InviteUserEventButton"));
const User_1 = tslib_1.__importStar(require("../User"));
const constants_1 = require("./constants");
const types_1 = require("./types");
const classes = {
    actionButton: `${constants_1.PREFIX}-action-button`,
    eventButton: `${constants_1.PREFIX}-event-button`,
    dialogRoot: `${constants_1.PREFIX}-dialog-root`,
    infiniteScroll: `${constants_1.PREFIX}-infinite-scroll`,
    endMessage: `${constants_1.PREFIX}-end-message`
};
const DialogRoot = (0, material_1.styled)(BaseDialog_1.default, {
    name: constants_1.PREFIX,
    slot: 'DialogRoot',
    overridesResolver: (_props, styles) => styles.dialogRoot
})(() => ({}));
function TabContentComponent(props) {
    // PROPS
    const { tabValue, state, dispatch, userProps, dialogProps, actionProps, handleRefresh } = props;
    // STATE
    const [openDialog, setOpenDialog] = (0, react_1.useState)(false);
    // REFS
    const updatesInvited = (0, react_1.useRef)(null);
    const updatesParticipants = (0, react_1.useRef)(null);
    // HOOKS
    const { enqueueSnackbar } = (0, notistack_1.useSnackbar)();
    // CONSTS
    const users = (0, react_1.useMemo)(() => (tabValue === types_1.TabContentEnum.REQUESTS ? actionProps === null || actionProps === void 0 ? void 0 : actionProps.users : state.results), [tabValue, actionProps, state]);
    // EFFECTS
    (0, react_1.useEffect)(() => {
        updatesInvited.current = pubsub_js_1.default.subscribe(`${PubSub_1.SCTopicType.EVENT}.${PubSub_1.SCGroupEventType.INVITE_MEMBER}`, handleInviteMember);
        updatesParticipants.current = pubsub_js_1.default.subscribe(`${PubSub_1.SCTopicType.EVENT}.${PubSub_1.SCGroupEventType.ADD_MEMBER}`, handleToggleMember);
        return () => {
            updatesInvited.current && pubsub_js_1.default.unsubscribe(updatesInvited.current);
            updatesParticipants.current && pubsub_js_1.default.unsubscribe(updatesParticipants.current);
        };
    }, []);
    // HANDLERS
    /**
     * Handles pagination
     */
    const handleNext = (0, react_1.useCallback)(() => {
        dispatch({ type: widget_1.actionWidgetTypes.LOADING_NEXT });
        api_services_1.http
            .request({
            url: state.next,
            method: api_services_1.Endpoints.UserSuggestion.method
        })
            .then((res) => {
            dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: res.data });
        })
            .catch((error) => {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
        });
    }, [state.next, state.isLoadingNext, state.initialized]);
    const handleToggleDialogOpen = (0, react_1.useCallback)(() => {
        setOpenDialog((prev) => !prev);
    }, []);
    const handleToggleMember = (0, react_1.useCallback)(() => {
        handleRefresh === null || handleRefresh === void 0 ? void 0 : handleRefresh(types_1.TabContentEnum.PARTICIPANTS);
    }, []);
    const handleInviteMember = (0, react_1.useCallback)(() => {
        handleRefresh === null || handleRefresh === void 0 ? void 0 : handleRefresh(types_1.TabContentEnum.INVITED);
    }, []);
    const getActionsComponent = (0, react_1.useCallback)((userId) => {
        if (tabValue === types_1.TabContentEnum.INVITED && actionProps) {
            const _handleInvitations = (invited) => {
                var _a, _b;
                if (invited) {
                    (_a = actionProps.setCount) === null || _a === void 0 ? void 0 : _a.call(actionProps, (prev) => prev - 1);
                }
                else {
                    (_b = actionProps.setCount) === null || _b === void 0 ? void 0 : _b.call(actionProps, (prev) => prev + 1);
                }
            };
            return (0, jsx_runtime_1.jsx)(InviteUserEventButton_1.default, { event: actionProps.scEvent, userId: userId, handleInvitations: _handleInvitations });
        }
        else if (tabValue === types_1.TabContentEnum.REQUESTS && actionProps) {
            const handleConfirm = (id) => {
                if (id) {
                    actionProps.setCount((prev) => prev - 1);
                    actionProps.setUsers((prev) => prev.filter((user) => user.id !== id));
                    enqueueSnackbar((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.acceptRequestUserEventButton.snackbar.success", defaultMessage: "ui.acceptRequestUserEventButton.snackbar.success" }), {
                        variant: 'success',
                        autoHideDuration: 3000
                    });
                }
                else {
                    enqueueSnackbar((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.common.error.action", defaultMessage: "ui.common.error.action" }), {
                        variant: 'error',
                        autoHideDuration: 3000
                    });
                }
            };
            return (0, jsx_runtime_1.jsx)(AcceptRequestUserEventButton_1.default, { event: actionProps.scEvent, userId: userId, handleConfirm: handleConfirm });
        }
        return undefined;
    }, [tabValue, actionProps]);
    if (tabValue === types_1.TabContentEnum.PARTICIPANTS && (actionProps === null || actionProps === void 0 ? void 0 : actionProps.count) === 0) {
        return ((0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "body1" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventMembersWidget.noParticipants", defaultMessage: "ui.eventMembersWidget.noParticipants" }) })));
    }
    else if (tabValue === types_1.TabContentEnum.INVITED && state.count === 0 && actionProps) {
        const date = actionProps.scEvent.end_date || actionProps.scEvent.start_date;
        const disabled = new Date(date).getTime() < new Date().getTime();
        const handleInvitations = (invited) => {
            if (invited) {
                handleRefresh === null || handleRefresh === void 0 ? void 0 : handleRefresh(tabValue);
            }
        };
        return ((0, jsx_runtime_1.jsx)(EventInviteButton_1.default, { event: actionProps.scEvent, className: classes.eventButton, handleInvitations: handleInvitations, disabled: disabled }));
    }
    else if (tabValue === types_1.TabContentEnum.REQUESTS && (actionProps === null || actionProps === void 0 ? void 0 : actionProps.count) === 0) {
        return ((0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "body1" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventMembersWidget.noOtherRequests", defaultMessage: "ui.eventMembersWidget.noOtherRequests" }) })));
    }
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(material_1.List, { children: users === null || users === void 0 ? void 0 : users.map((user) => ((0, jsx_runtime_1.jsx)(material_1.ListItem, { children: (0, jsx_runtime_1.jsx)(User_1.default, Object.assign({ elevation: 0, user: user }, userProps, { actions: getActionsComponent(user.id) })) }, user.id))) }), state.count > state.visibleItems && ((0, jsx_runtime_1.jsx)(material_1.Button, Object.assign({ onClick: handleToggleDialogOpen, className: classes.actionButton }, { children: (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "caption" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventMembersWidget.showAll", defaultMessage: "ui.eventMembersWidget.showAll" }) })) }))), openDialog && ((0, jsx_runtime_1.jsx)(DialogRoot, Object.assign({ className: classes.dialogRoot, title: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.eventMembersWidget.title", id: "ui.eventMembersWidget.title" }), onClose: handleToggleDialogOpen, open: openDialog }, dialogProps, { children: (0, jsx_runtime_1.jsx)(InfiniteScroll_1.default, Object.assign({ dataLength: state.results.length, next: handleNext, hasMoreNext: Boolean(state.next), loaderNext: (0, jsx_runtime_1.jsx)(User_1.UserSkeleton, Object.assign({ elevation: 0 }, userProps)), className: classes.infiniteScroll, endMessage: (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ className: classes.endMessage }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventMembersWidget.noMoreResults", defaultMessage: "ui.eventMembersWidget.noMoreResults" }) })) }, { children: (0, jsx_runtime_1.jsx)(material_1.List, { children: state.results.map((user) => ((0, jsx_runtime_1.jsx)(material_1.ListItem, { children: (0, jsx_runtime_1.jsx)(User_1.default, Object.assign({ elevation: 0, user: user }, userProps)) }, user.id))) }) })) })))] }));
}
exports.default = TabContentComponent;
