"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 system_1 = require("@mui/system");
const api_services_1 = require("@selfcommunity/api-services");
const react_core_1 = require("@selfcommunity/react-core");
const utils_1 = require("@selfcommunity/utils");
const react_1 = require("react");
const react_intl_1 = require("react-intl");
require("swiper/css");
const Errors_1 = require("../../constants/Errors");
const Pagination_1 = require("../../constants/Pagination");
const widget_1 = require("../../utils/widget");
const Widget_1 = tslib_1.__importDefault(require("../Widget"));
const constants_1 = require("./constants");
const Skeleton_1 = tslib_1.__importDefault(require("./Skeleton"));
const TabContentComponent_1 = tslib_1.__importDefault(require("./TabContentComponent"));
const types_1 = require("./types");
const classes = {
    root: `${constants_1.PREFIX}-root`,
    content: `${constants_1.PREFIX}-content`,
    title: `${constants_1.PREFIX}-title`,
    tabsWrapper: `${constants_1.PREFIX}-tabs-wrapper`,
    tabLabelWrapper: `${constants_1.PREFIX}-tab-label-wrapper`,
    tabPanel: `${constants_1.PREFIX}-tab-panel`
};
const Root = (0, system_1.styled)(Widget_1.default, {
    name: constants_1.PREFIX,
    slot: 'Root',
    overridesResolver: (_props, styles) => styles.root
})(() => ({}));
function EventMembersWidget(inProps) {
    // PROPS
    const props = (0, material_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    const { event, eventId, userProps = {}, endpointQueryParams = { limit: 5, offset: Pagination_1.DEFAULT_PAGINATION_OFFSET }, cacheStrategy, dialogProps, limit = 5 } = props, rest = tslib_1.__rest(props, ["event", "eventId", "userProps", "endpointQueryParams", "cacheStrategy", "dialogProps", "limit"]);
    // STATE
    const [participants, dispatchParticipants] = (0, react_1.useReducer)(widget_1.dataWidgetReducer, {
        isLoadingNext: false,
        next: null,
        cacheKey: react_core_1.SCCache.getWidgetStateCacheKey(react_core_1.SCCache.USER_PARTECIPANTS_EVENTS_STATE_CACHE_PREFIX_KEY, eventId || event.id),
        cacheStrategy,
        visibleItems: limit
    }, widget_1.stateWidgetInitializer);
    const [invited, dispatchInvited] = (0, react_1.useReducer)(widget_1.dataWidgetReducer, {
        isLoadingNext: false,
        next: null,
        cacheKey: react_core_1.SCCache.getWidgetStateCacheKey(react_core_1.SCCache.USER_INVITED_EVENTS_STATE_CACHE_PREFIX_KEY, eventId || event.id),
        cacheStrategy,
        visibleItems: limit
    }, widget_1.stateWidgetInitializer);
    const [requests, dispatchRequests] = (0, react_1.useReducer)(widget_1.dataWidgetReducer, {
        isLoadingNext: false,
        next: null,
        cacheKey: react_core_1.SCCache.getWidgetStateCacheKey(react_core_1.SCCache.USER_REQUESTS_EVENTS_STATE_CACHE_PREFIX_KEY, eventId || event.id),
        cacheStrategy,
        visibleItems: limit
    }, widget_1.stateWidgetInitializer);
    const [participantsCount, setParticipantsCount] = (0, react_1.useState)(participants.count);
    const [invitedCount, setInvitedCount] = (0, react_1.useState)(invited.count);
    const [requestsCount, setRequestsCount] = (0, react_1.useState)(requests.count);
    const [requestsUsers, setRequestsUsers] = (0, react_1.useState)(requests.results);
    const [tabValue, setTabValue] = (0, react_1.useState)(types_1.TabContentEnum.PARTICIPANTS);
    const [refresh, setRefresh] = (0, react_1.useState)(null);
    // CONTEXT
    const scUserContext = (0, react_core_1.useSCUser)();
    // HOOKS
    const { scEvent } = (0, react_core_1.useSCFetchEvent)({ id: eventId, event });
    // CONSTS
    const hasAllow = (0, react_1.useMemo)(() => { var _a; return ((_a = scUserContext.user) === null || _a === void 0 ? void 0 : _a.id) === (scEvent === null || scEvent === void 0 ? void 0 : scEvent.managed_by.id); }, [scUserContext, scEvent]);
    const title = (0, react_1.useMemo)(() => {
        switch (tabValue) {
            case types_1.TabContentEnum.REQUESTS:
                return 'ui.eventMembersWidget.requests';
            case types_1.TabContentEnum.INVITED:
                return 'ui.eventMembersWidget.invited';
            case types_1.TabContentEnum.PARTICIPANTS:
            default:
                return 'ui.eventMembersWidget.participants';
        }
    }, [tabValue]);
    // CALLBACKS
    const _initParticipants = (0, react_1.useCallback)(() => {
        if (!participants.initialized && !participants.isLoadingNext) {
            dispatchParticipants({ type: widget_1.actionWidgetTypes.LOADING_NEXT });
            api_services_1.EventService.getUsersGoingToEvent(scEvent.id, Object.assign({}, endpointQueryParams))
                .then((payload) => {
                dispatchParticipants({ type: widget_1.actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: Object.assign(Object.assign({}, payload), { initialized: true }) });
                setParticipantsCount(payload.count);
            })
                .catch((error) => {
                dispatchParticipants({ type: widget_1.actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
                utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
            });
        }
    }, [participants.isLoadingNext, participants.initialized, scEvent, dispatchParticipants, setParticipantsCount]);
    const _initInvited = (0, react_1.useCallback)(() => {
        if (!invited.initialized && !invited.isLoadingNext && hasAllow) {
            dispatchInvited({ type: widget_1.actionWidgetTypes.LOADING_NEXT });
            api_services_1.EventService.getEventInvitedUsers(scEvent.id, Object.assign({}, endpointQueryParams))
                .then((payload) => {
                dispatchInvited({ type: widget_1.actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: Object.assign(Object.assign({}, payload), { initialized: true }) });
                setInvitedCount(payload.count);
            })
                .catch((error) => {
                dispatchInvited({ type: widget_1.actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
                utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
            });
        }
    }, [invited.isLoadingNext, invited.initialized, scEvent, dispatchInvited, setInvitedCount]);
    const _initRequests = (0, react_1.useCallback)(() => {
        if (!requests.initialized && !requests.isLoadingNext && hasAllow) {
            dispatchRequests({ type: widget_1.actionWidgetTypes.LOADING_NEXT });
            api_services_1.EventService.getEventWaitingApprovalSubscribers(scEvent.id, Object.assign({}, endpointQueryParams))
                .then((payload) => {
                dispatchRequests({ type: widget_1.actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: Object.assign(Object.assign({}, payload), { initialized: true }) });
                setRequestsCount(payload.count);
                setRequestsUsers(payload.results);
            })
                .catch((error) => {
                dispatchRequests({ type: widget_1.actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
                utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
            });
        }
    }, [requests.isLoadingNext, requests.initialized, scEvent, dispatchRequests, setRequestsCount, setRequestsUsers]);
    // EFFECTS
    (0, react_1.useEffect)(() => {
        let _t;
        if (scUserContext.user && scEvent) {
            _t = setTimeout(() => {
                if (refresh === types_1.TabContentEnum.PARTICIPANTS) {
                    _initParticipants();
                    setRefresh(null);
                }
                else if (refresh === types_1.TabContentEnum.INVITED) {
                    _initInvited();
                    setRefresh(null);
                }
                else {
                    _initParticipants();
                    _initInvited();
                    _initRequests();
                }
            });
            return () => {
                clearTimeout(_t);
            };
        }
    }, [scUserContext.user, scEvent, refresh]);
    (0, react_1.useEffect)(() => {
        if (participants.initialized && scEvent && Boolean((eventId !== undefined && scEvent.id !== eventId) || (event && scEvent.id !== event.id))) {
            dispatchParticipants({ type: widget_1.actionWidgetTypes.RESET, payload: {} });
            dispatchRequests({ type: widget_1.actionWidgetTypes.RESET, payload: {} });
            dispatchInvited({ type: widget_1.actionWidgetTypes.RESET, payload: {} });
        }
    }, [participants.initialized, scEvent, eventId, event]);
    // HANDLERS
    const handleTabChange = (0, react_1.useCallback)((_evt, newTabValue) => {
        setTabValue(newTabValue);
    }, []);
    const handleRefresh = (0, react_1.useCallback)((_tabValue) => {
        if (_tabValue === types_1.TabContentEnum.PARTICIPANTS) {
            dispatchParticipants({ type: widget_1.actionWidgetTypes.RESET });
        }
        else if (_tabValue === types_1.TabContentEnum.INVITED) {
            dispatchInvited({ type: widget_1.actionWidgetTypes.RESET });
        }
        setRefresh(_tabValue);
    }, []);
    if (!scEvent ||
        !participants.initialized ||
        (scEvent && ((eventId !== undefined && scEvent.id !== eventId) || (event && scEvent.id !== event.id))) ||
        (tabValue === types_1.TabContentEnum.PARTICIPANTS && participants.isLoadingNext && !participants.initialized)) {
        return (0, jsx_runtime_1.jsx)(Skeleton_1.default, {});
    }
    return ((0, jsx_runtime_1.jsx)(Root, Object.assign({ className: classes.root }, rest, { children: (0, jsx_runtime_1.jsxs)(material_1.CardContent, Object.assign({ className: classes.content }, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h5", className: classes.title }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: title, defaultMessage: title }) })), (0, jsx_runtime_1.jsxs)(lab_1.TabContext, Object.assign({ value: tabValue }, { children: [(0, jsx_runtime_1.jsxs)(lab_1.TabList, Object.assign({ className: classes.tabsWrapper, onChange: handleTabChange, textColor: "primary", indicatorColor: "primary", variant: "fullWidth" }, { children: [(0, jsx_runtime_1.jsx)(material_1.Tab, { label: (0, jsx_runtime_1.jsxs)(material_1.Stack, Object.assign({ className: classes.tabLabelWrapper }, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h3" }, { children: participantsCount })), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "subtitle2" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventMembersWidget.participants", defaultMessage: "ui.eventMembersWidget.participants" }) }))] })), value: types_1.TabContentEnum.PARTICIPANTS }), hasAllow && ((0, jsx_runtime_1.jsx)(material_1.Tab, { label: (0, jsx_runtime_1.jsxs)(material_1.Stack, Object.assign({ className: classes.tabLabelWrapper }, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h3" }, { children: invitedCount })), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "subtitle2" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventMembersWidget.invited", defaultMessage: "ui.eventMembersWidget.invited" }) }))] })), value: types_1.TabContentEnum.INVITED })), hasAllow && ((0, jsx_runtime_1.jsx)(material_1.Tab, { label: (0, jsx_runtime_1.jsxs)(material_1.Stack, Object.assign({ className: classes.tabLabelWrapper }, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h3" }, { children: requestsCount })), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "subtitle2" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventMembersWidget.requests", defaultMessage: "ui.eventMembersWidget.requests" }) }))] })), value: types_1.TabContentEnum.REQUESTS }))] })), (0, jsx_runtime_1.jsx)(lab_1.TabPanel, Object.assign({ value: types_1.TabContentEnum.PARTICIPANTS, className: classes.tabPanel }, { children: (0, jsx_runtime_1.jsx)(TabContentComponent_1.default, { tabValue: types_1.TabContentEnum.PARTICIPANTS, state: participants, dispatch: dispatchParticipants, userProps: userProps, dialogProps: dialogProps, handleRefresh: handleRefresh }) })), hasAllow && ((0, jsx_runtime_1.jsx)(lab_1.TabPanel, Object.assign({ value: types_1.TabContentEnum.INVITED, className: classes.tabPanel }, { children: (0, jsx_runtime_1.jsx)(TabContentComponent_1.default, { tabValue: types_1.TabContentEnum.INVITED, state: invited, dispatch: dispatchInvited, userProps: userProps, dialogProps: dialogProps, actionProps: {
                                    scEvent,
                                    setCount: setInvitedCount
                                }, handleRefresh: handleRefresh }) }))), hasAllow && ((0, jsx_runtime_1.jsx)(lab_1.TabPanel, Object.assign({ value: types_1.TabContentEnum.REQUESTS, className: classes.tabPanel }, { children: (0, jsx_runtime_1.jsx)(TabContentComponent_1.default, { tabValue: types_1.TabContentEnum.REQUESTS, state: requests, dispatch: dispatchRequests, userProps: userProps, dialogProps: dialogProps, actionProps: {
                                    scEvent,
                                    count: requestsCount,
                                    setCount: setRequestsCount,
                                    users: requestsUsers,
                                    setUsers: setRequestsUsers
                                }, handleRefresh: handleRefresh }) })))] }))] })) })));
}
exports.default = EventMembersWidget;
