import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Button, CardActions, CardContent, Divider, List, ListItem, Stack, Typography, useThemeProps } from '@mui/material';
import { styled } from '@mui/system';
import { Endpoints, http, UserApiClient } from '@selfcommunity/api-services';
import { SCCache, SCPreferences, useSCFetchUser, useSCPreferences, useSCUser } from '@selfcommunity/react-core';
import { SCCommunitySubscriptionTier } from '@selfcommunity/types';
import { isInteger, Logger } from '@selfcommunity/utils';
import { Fragment, useCallback, useEffect, useMemo, 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 Widget from '../Widget';
import { PREFIX } from './constants';
import Skeleton from './Skeleton';
import LiveStream, { LiveStreamSkeleton } from '../LiveStream';
const messages = defineMessages({
    title: {
        id: 'ui.userLiveStreamWidget.title',
        defaultMessage: 'ui.userLiveStreamWidget.title'
    }
});
const classes = {
    root: `${PREFIX}-root`,
    content: `${PREFIX}-content`,
    header: `${PREFIX}-header`,
    avatarWrapper: `${PREFIX}-avatar-wrapper`,
    avatar: `${PREFIX}-avatar`,
    liveWrapper: `${PREFIX}-live-wrapper`,
    live: `${PREFIX}-live`,
    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 UserLiveStreamWidget(inProps) {
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { userId, user, liveStreamComponentProps = { elevation: 0, square: true }, endpointQueryParams = { limit: 5, offset: DEFAULT_PAGINATION_OFFSET }, cacheStrategy, dialogProps, limit = 5 } = props, rest = __rest(props, ["userId", "user", "liveStreamComponentProps", "endpointQueryParams", "cacheStrategy", "dialogProps", "limit"]);
    // STATE
    const [state, dispatch] = useReducer(dataWidgetReducer, {
        isLoadingNext: false,
        next: null,
        cacheKey: SCCache.getWidgetStateCacheKey(SCCache.USER_LIVE_STREAM_CACHE_PREFIX_KEY, isInteger(userId) ? userId : user.id),
        cacheStrategy,
        visibleItems: limit
    }, stateWidgetInitializer);
    const [openDialog, setOpenDialog] = useState(false);
    // CONTEXT
    const scUserContext = useSCUser();
    const scPreferencesContext = useSCPreferences();
    const { scUser } = useSCFetchUser({ id: userId, user });
    // HOOKS
    const intl = useIntl();
    // MEMO
    const liveStreamEnabled = useMemo(() => SCPreferences.CONFIGURATIONS_LIVE_STREAM_ENABLED in scPreferencesContext.preferences &&
        scPreferencesContext.preferences[SCPreferences.CONFIGURATIONS_LIVE_STREAM_ENABLED].value, [scPreferencesContext.preferences]);
    const isFreeTrialTier = useMemo(() => scPreferencesContext.preferences &&
        SCPreferences.CONFIGURATIONS_SUBSCRIPTION_TIER in scPreferencesContext.preferences &&
        scPreferencesContext.preferences[SCPreferences.CONFIGURATIONS_SUBSCRIPTION_TIER].value &&
        scPreferencesContext.preferences[SCPreferences.CONFIGURATIONS_SUBSCRIPTION_TIER].value === SCCommunitySubscriptionTier.FREE_TRIAL, [scPreferencesContext.preferences]);
    const _initComponent = useCallback(() => {
        if (!state.initialized && !state.isLoadingNext) {
            dispatch({ type: actionWidgetTypes.LOADING_NEXT });
            UserApiClient.getUserLiveStream(scUser.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);
            });
        }
    }, [scUser, state.isLoadingNext, state.initialized, dispatch]);
    // EFFECTS
    useEffect(() => {
        let _t;
        if (scUserContext.user && scUser && liveStreamEnabled) {
            _t = setTimeout(_initComponent);
            return () => {
                clearTimeout(_t);
            };
        }
    }, [scUserContext.user, scUser, liveStreamEnabled]);
    // HANDLERS
    /**
     * Handles pagination
     */
    const handleNext = useCallback(() => {
        dispatch({ type: actionWidgetTypes.LOADING_NEXT });
        http
            .request({
            url: state.next,
            method: Endpoints.GetLiveStream.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 (!scUser && !state.initialized) {
        return _jsx(Skeleton, {});
    }
    if (!scUser || (state === null || state === void 0 ? void 0 : state.count) === 0 || !liveStreamEnabled || isFreeTrialTier) {
        return _jsx(HiddenPlaceholder, {});
    }
    return (_jsxs(Root, Object.assign({ className: classes.root }, rest, { children: [_jsxs(CardContent, Object.assign({ className: classes.content }, { children: [_jsx(Typography, Object.assign({ variant: "h4" }, { children: _jsx("b", { children: intl.formatMessage(messages.title, { user: scUser.username }) }) })), _jsx(Stack, Object.assign({ className: classes.liveWrapper }, { children: state === null || state === void 0 ? void 0 : state.results.map((_live, i, array) => (_jsxs(Fragment, { children: [_jsx(LiveStream, Object.assign({ liveStream: _live }, liveStreamComponentProps, { className: classes.live })), 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.userLiveStreamWidget.showAll", defaultMessage: "ui.userLiveStreamWidget.showAll" }) })) })) }))), openDialog && (_jsx(DialogRoot, Object.assign({ className: classes.dialogRoot, title: intl.formatMessage(messages.title, { user: scUser.username }), onClose: handleToggleDialogOpen, open: openDialog }, dialogProps, { children: _jsx(InfiniteScroll, Object.assign({ dataLength: state.results.length, next: handleNext, hasMoreNext: Boolean(state.next), loaderNext: _jsx(LiveStreamSkeleton, Object.assign({ elevation: 0 }, liveStreamComponentProps)), className: classes.infiniteScroll, endMessage: _jsx(Typography, Object.assign({ className: classes.endMessage }, { children: _jsx(FormattedMessage, { id: "ui.userLiveStreamWidget.noMoreResults", defaultMessage: "ui.userLiveStreamWidget.noMoreResults" }) })) }, { children: _jsx(List, { children: state.results.map((live) => (_jsx(ListItem, { children: _jsx(LiveStream, Object.assign({ elevation: 0, liveStream: live }, liveStreamComponentProps)) }, live.id))) }) })) })))] })));
}
