import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Avatar, Button, CardActions, CardContent, Divider, List, ListItem, Stack, Typography, useThemeProps } from '@mui/material';
import { styled } from '@mui/system';
import { Endpoints, EventService, http } from '@selfcommunity/api-services';
import { Link, SCCache, SCRoutes, useSCFetchEvent, useSCRouting, useSCUser } from '@selfcommunity/react-core';
import { Logger } from '@selfcommunity/utils';
import { Fragment, useCallback, useEffect, useReducer, useState } from 'react';
import { defineMessages, FormattedMessage, useIntl } from 'react-intl';
import 'swiper/css';
import { SCOPE_SC_UI } from '../../constants/Errors';
import { DEFAULT_PAGINATION_OFFSET } from '../../constants/Pagination';
import BaseDialog from '../../shared/BaseDialog';
import HiddenPlaceholder from '../../shared/HiddenPlaceholder';
import InfiniteScroll from '../../shared/InfiniteScroll';
import { actionWidgetTypes, dataWidgetReducer, stateWidgetInitializer } from '../../utils/widget';
import Event, { EventSkeleton } from '../Event';
import Widget from '../Widget';
import { PREFIX } from './constants';
import Skeleton from './Skeleton';
const messages = defineMessages({
    title: {
        id: 'ui.relatedEventsWidget.title',
        defaultMessage: 'ui.relatedEventsWidget.title'
    }
});
const classes = {
    root: `${PREFIX}-root`,
    content: `${PREFIX}-content`,
    header: `${PREFIX}-header`,
    avatarWrapper: `${PREFIX}-avatar-wrapper`,
    avatar: `${PREFIX}-avatar`,
    eventWrapper: `${PREFIX}-event-wrapper`,
    event: `${PREFIX}-event`,
    actions: `${PREFIX}-actions`,
    actionButton: `${PREFIX}-action-button`,
    dialogRoot: `${PREFIX}-dialog-root`,
    infiniteScroll: `${PREFIX}-infinite-scroll`,
    endMessage: `${PREFIX}-end-message`
};
const Root = styled(Widget, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (_props, styles) => styles.root
})(() => ({}));
const DialogRoot = styled(BaseDialog, {
    name: PREFIX,
    slot: 'DialogRoot',
    overridesResolver: (_props, styles) => styles.dialogRoot
})(() => ({}));
export default function RelatedEventsWidget(inProps) {
    var _a;
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { event, eventId, eventComponentProps = { elevation: 0, square: true }, endpointQueryParams = { limit: 5, offset: DEFAULT_PAGINATION_OFFSET }, cacheStrategy, dialogProps, limit = 5 } = props, rest = __rest(props, ["event", "eventId", "eventComponentProps", "endpointQueryParams", "cacheStrategy", "dialogProps", "limit"]);
    // STATE
    const [state, dispatch] = useReducer(dataWidgetReducer, {
        isLoadingNext: false,
        next: null,
        cacheKey: SCCache.getWidgetStateCacheKey(SCCache.USER_OTHER_EVENTS_STATE_CACHE_PREFIX_KEY, eventId || event.id),
        cacheStrategy,
        visibleItems: limit
    }, stateWidgetInitializer);
    const [openDialog, setOpenDialog] = useState(false);
    // CONTEXT
    const scUserContext = useSCUser();
    const scRoutingContext = useSCRouting();
    // HOOKS
    const intl = useIntl();
    const { scEvent } = useSCFetchEvent({ id: eventId, event });
    const _initComponent = useCallback(() => {
        if (!state.initialized && !state.isLoadingNext) {
            dispatch({ type: actionWidgetTypes.LOADING_NEXT });
            EventService.getEventRelated(scEvent.id, Object.assign({ created_by: scEvent.managed_by.id }, endpointQueryParams))
                .then((payload) => {
                dispatch({ type: actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: Object.assign(Object.assign({}, payload), { initialized: true }) });
            })
                .catch((error) => {
                dispatch({ type: actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
                Logger.error(SCOPE_SC_UI, error);
            });
        }
    }, [state.isLoadingNext, state.initialized, dispatch, scEvent]);
    // EFFECTS
    useEffect(() => {
        let _t;
        if (scUserContext.user && scEvent) {
            _t = setTimeout(_initComponent);
            return () => {
                clearTimeout(_t);
            };
        }
    }, [scUserContext.user, scEvent]);
    // HANDLERS
    /**
     * Handles pagination
     */
    const handleNext = useCallback(() => {
        dispatch({ type: actionWidgetTypes.LOADING_NEXT });
        http
            .request({
            url: state.next,
            method: Endpoints.GetEventRelated.method
        })
            .then((res) => {
            dispatch({ type: actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: res.data });
        });
    }, [dispatch, state.next, state.isLoadingNext, state.initialized]);
    const handleToggleDialogOpen = useCallback(() => {
        setOpenDialog((prev) => !prev);
    }, []);
    if (!scEvent && !state.initialized) {
        return _jsx(Skeleton, {});
    }
    // RENDER
    if (!scEvent || (state === null || state === void 0 ? void 0 : state.count) === 0) {
        return _jsx(HiddenPlaceholder, {});
    }
    return (_jsxs(Root, Object.assign({ className: classes.root }, rest, { children: [_jsxs(CardContent, Object.assign({ className: classes.content }, { children: [_jsxs(Stack, Object.assign({ className: classes.header }, { children: [_jsx(Button, Object.assign({ component: Link, to: scRoutingContext.url(SCRoutes.USER_PROFILE_ROUTE_NAME, { id: (_a = scUserContext.user) === null || _a === void 0 ? void 0 : _a.id }), className: classes.avatarWrapper }, { children: _jsx(Avatar, { variant: "rounded", src: scEvent.managed_by.avatar, alt: scEvent.managed_by.username, className: classes.avatar }) })), _jsx(Typography, Object.assign({ variant: "h4" }, { children: _jsx("b", { children: intl.formatMessage(messages.title, { user: scEvent.managed_by.username }) }) }))] })), _jsx(Stack, Object.assign({ className: classes.eventWrapper }, { children: state === null || state === void 0 ? void 0 : state.results.map((_event, i, array) => (_jsxs(Fragment, { children: [_jsx(Event, Object.assign({ event: _event, eventId: _event.id }, eventComponentProps, { className: classes.event })), i < array.length - 1 && _jsx(Divider, {})] }, i))) }))] })), state.count > state.visibleItems && (_jsx(CardActions, Object.assign({ className: classes.actions }, { children: _jsx(Button, Object.assign({ onClick: handleToggleDialogOpen, className: classes.actionButton }, { children: _jsx(Typography, Object.assign({ variant: "caption" }, { children: _jsx(FormattedMessage, { id: "ui.relatedEventsWidget.showAll", defaultMessage: "ui.relatedEventsWidget.showAll" }) })) })) }))), openDialog && (_jsx(DialogRoot, Object.assign({ className: classes.dialogRoot, title: intl.formatMessage(messages.title, { user: scEvent.managed_by.username }), onClose: handleToggleDialogOpen, open: openDialog }, dialogProps, { children: _jsx(InfiniteScroll, Object.assign({ dataLength: state.results.length, next: handleNext, hasMoreNext: Boolean(state.next), loaderNext: _jsx(EventSkeleton, Object.assign({ elevation: 0 }, eventComponentProps)), className: classes.infiniteScroll, endMessage: _jsx(Typography, Object.assign({ className: classes.endMessage }, { children: _jsx(FormattedMessage, { id: "ui.relatedEventsWidget.noMoreResults", defaultMessage: "ui.eventMembersWidget.noMoreResults" }) })) }, { children: _jsx(List, { children: state.results.map((event) => (_jsx(ListItem, { children: _jsx(Event, Object.assign({ elevation: 0, event: event }, eventComponentProps)) }, event.id))) }) })) })))] })));
}
