"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 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 BaseDialog_1 = tslib_1.__importDefault(require("../../shared/BaseDialog"));
const HiddenPlaceholder_1 = tslib_1.__importDefault(require("../../shared/HiddenPlaceholder"));
const InfiniteScroll_1 = tslib_1.__importDefault(require("../../shared/InfiniteScroll"));
const widget_1 = require("../../utils/widget");
const Event_1 = tslib_1.__importStar(require("../Event"));
const Widget_1 = tslib_1.__importDefault(require("../Widget"));
const constants_1 = require("./constants");
const Skeleton_1 = tslib_1.__importDefault(require("./Skeleton"));
const messages = (0, react_intl_1.defineMessages)({
    title: {
        id: 'ui.relatedEventsWidget.title',
        defaultMessage: 'ui.relatedEventsWidget.title'
    }
});
const classes = {
    root: `${constants_1.PREFIX}-root`,
    content: `${constants_1.PREFIX}-content`,
    header: `${constants_1.PREFIX}-header`,
    avatarWrapper: `${constants_1.PREFIX}-avatar-wrapper`,
    avatar: `${constants_1.PREFIX}-avatar`,
    eventWrapper: `${constants_1.PREFIX}-event-wrapper`,
    event: `${constants_1.PREFIX}-event`,
    actions: `${constants_1.PREFIX}-actions`,
    actionButton: `${constants_1.PREFIX}-action-button`,
    dialogRoot: `${constants_1.PREFIX}-dialog-root`,
    infiniteScroll: `${constants_1.PREFIX}-infinite-scroll`,
    endMessage: `${constants_1.PREFIX}-end-message`
};
const Root = (0, system_1.styled)(Widget_1.default, {
    name: constants_1.PREFIX,
    slot: 'Root',
    overridesResolver: (_props, styles) => styles.root
})(() => ({}));
const DialogRoot = (0, system_1.styled)(BaseDialog_1.default, {
    name: constants_1.PREFIX,
    slot: 'DialogRoot',
    overridesResolver: (_props, styles) => styles.dialogRoot
})(() => ({}));
function RelatedEventsWidget(inProps) {
    var _a;
    // PROPS
    const props = (0, material_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    const { event, eventId, eventComponentProps = { elevation: 0, square: true }, endpointQueryParams = { limit: 5, offset: Pagination_1.DEFAULT_PAGINATION_OFFSET }, cacheStrategy, dialogProps, limit = 5 } = props, rest = tslib_1.__rest(props, ["event", "eventId", "eventComponentProps", "endpointQueryParams", "cacheStrategy", "dialogProps", "limit"]);
    // STATE
    const [state, dispatch] = (0, react_1.useReducer)(widget_1.dataWidgetReducer, {
        isLoadingNext: false,
        next: null,
        cacheKey: react_core_1.SCCache.getWidgetStateCacheKey(react_core_1.SCCache.USER_OTHER_EVENTS_STATE_CACHE_PREFIX_KEY, eventId || event.id),
        cacheStrategy,
        visibleItems: limit
    }, widget_1.stateWidgetInitializer);
    const [openDialog, setOpenDialog] = (0, react_1.useState)(false);
    // CONTEXT
    const scUserContext = (0, react_core_1.useSCUser)();
    const scRoutingContext = (0, react_core_1.useSCRouting)();
    // HOOKS
    const intl = (0, react_intl_1.useIntl)();
    const { scEvent } = (0, react_core_1.useSCFetchEvent)({ id: eventId, event });
    const _initComponent = (0, react_1.useCallback)(() => {
        if (!state.initialized && !state.isLoadingNext) {
            dispatch({ type: widget_1.actionWidgetTypes.LOADING_NEXT });
            api_services_1.EventService.getEventRelated(scEvent.id, Object.assign({ created_by: scEvent.managed_by.id }, endpointQueryParams))
                .then((payload) => {
                dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: Object.assign(Object.assign({}, payload), { initialized: true }) });
            })
                .catch((error) => {
                dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
                utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
            });
        }
    }, [state.isLoadingNext, state.initialized, dispatch, scEvent]);
    // EFFECTS
    (0, react_1.useEffect)(() => {
        let _t;
        if (scUserContext.user && scEvent) {
            _t = setTimeout(_initComponent);
            return () => {
                clearTimeout(_t);
            };
        }
    }, [scUserContext.user, scEvent]);
    // 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.GetEventRelated.method
        })
            .then((res) => {
            dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: res.data });
        });
    }, [dispatch, state.next, state.isLoadingNext, state.initialized]);
    const handleToggleDialogOpen = (0, react_1.useCallback)(() => {
        setOpenDialog((prev) => !prev);
    }, []);
    if (!scEvent && !state.initialized) {
        return (0, jsx_runtime_1.jsx)(Skeleton_1.default, {});
    }
    // RENDER
    if (!scEvent || (state === null || state === void 0 ? void 0 : state.count) === 0) {
        return (0, jsx_runtime_1.jsx)(HiddenPlaceholder_1.default, {});
    }
    return ((0, jsx_runtime_1.jsxs)(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.jsxs)(material_1.Stack, Object.assign({ className: classes.header }, { children: [(0, jsx_runtime_1.jsx)(material_1.Button, Object.assign({ component: react_core_1.Link, to: scRoutingContext.url(react_core_1.SCRoutes.USER_PROFILE_ROUTE_NAME, { id: (_a = scUserContext.user) === null || _a === void 0 ? void 0 : _a.id }), className: classes.avatarWrapper }, { children: (0, jsx_runtime_1.jsx)(material_1.Avatar, { variant: "rounded", src: scEvent.managed_by.avatar, alt: scEvent.managed_by.username, className: classes.avatar }) })), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h4" }, { children: (0, jsx_runtime_1.jsx)("b", { children: intl.formatMessage(messages.title, { user: scEvent.managed_by.username }) }) }))] })), (0, jsx_runtime_1.jsx)(material_1.Stack, Object.assign({ className: classes.eventWrapper }, { children: state === null || state === void 0 ? void 0 : state.results.map((_event, i, array) => ((0, jsx_runtime_1.jsxs)(react_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(Event_1.default, Object.assign({ event: _event, eventId: _event.id }, eventComponentProps, { className: classes.event })), i < array.length - 1 && (0, jsx_runtime_1.jsx)(material_1.Divider, {})] }, i))) }))] })), state.count > state.visibleItems && ((0, jsx_runtime_1.jsx)(material_1.CardActions, Object.assign({ className: classes.actions }, { children: (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.relatedEventsWidget.showAll", defaultMessage: "ui.relatedEventsWidget.showAll" }) })) })) }))), openDialog && ((0, jsx_runtime_1.jsx)(DialogRoot, Object.assign({ className: classes.dialogRoot, title: intl.formatMessage(messages.title, { user: scEvent.managed_by.username }), 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)(Event_1.EventSkeleton, Object.assign({ elevation: 0 }, eventComponentProps)), 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.relatedEventsWidget.noMoreResults", defaultMessage: "ui.eventMembersWidget.noMoreResults" }) })) }, { children: (0, jsx_runtime_1.jsx)(material_1.List, { children: state.results.map((event) => ((0, jsx_runtime_1.jsx)(material_1.ListItem, { children: (0, jsx_runtime_1.jsx)(Event_1.default, Object.assign({ elevation: 0, event: event }, eventComponentProps)) }, event.id))) }) })) })))] })));
}
exports.default = RelatedEventsWidget;
