import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useContext, useEffect, useMemo, useState } from 'react';
import { Avatar, Box, CardContent, CardHeader, CardMedia, Chip, CircularProgress, Fade, IconButton, ListItem, ListItemAvatar, ListItemText, Typography } from '@mui/material';
import { styled } from '@mui/material/styles';
import Icon from '@mui/material/Icon';
import { FormattedMessage } from 'react-intl';
import { SCOPE_SC_UI } from '../../constants/Errors';
import MarkRead from '../../shared/MarkRead';
import Widget from '../Widget';
import { SCBroadcastMessageTemplateType } from '../../types';
import classNames from 'classnames';
import { http, Endpoints } from '@selfcommunity/api-services';
import { Logger } from '@selfcommunity/utils';
import { Link, SCPreferences, SCPreferencesContext, SCRoutes, useSCRouting } from '@selfcommunity/react-core';
import { PREFIX } from './constants';
const classes = {
    root: `${PREFIX}-message-root`,
    header: `${PREFIX}-header`,
    title: `${PREFIX}-title`,
    media: `${PREFIX}-media`,
    content: `${PREFIX}-content`,
    listItemSnippet: `${PREFIX}-list-item-snippet`,
    listItemSnippetNew: `${PREFIX}-list-item-snippet-new`,
    messageIconWrap: `${PREFIX}-flag-icon-wrap`,
    messageIconSnippet: `${PREFIX}-flag-icon-snippet`
};
const Root = styled(Widget, {
    name: PREFIX,
    slot: 'MessageRoot'
})(() => ({}));
const PREFERENCES = [SCPreferences.LOGO_NAVBAR_LOGO_MOBILE, SCPreferences.TEXT_APPLICATION_NAME];
export default function Message(props) {
    // PROPS
    const { id = `message_${props.message.id}`, className, message, disableMarkRead = false, onClose = null, onRead = null, template = SCBroadcastMessageTemplateType.DETAIL } = props, rest = __rest(props, ["id", "className", "message", "disableMarkRead", "onClose", "onRead", "template"]);
    // STATE
    const [open, setOpen] = useState(message.disposed_at === null);
    const [closing, setClosing] = useState(false);
    // CONTEXT
    const scPrefernces = useContext(SCPreferencesContext);
    // ROUTING
    const scRoutingContext = useSCRouting();
    // Compute preferences
    const preferences = useMemo(() => {
        const _preferences = {};
        PREFERENCES.map((p) => (_preferences[p] = p in scPrefernces.preferences ? scPrefernces.preferences[p].value : null));
        return _preferences;
    }, [scPrefernces.preferences]);
    // HANDLERS
    /**
     * Handle dispose message
     */
    const handleClose = () => {
        setClosing(true);
        http
            .request({
            url: Endpoints.BroadcastMessagesDispose.url(),
            method: Endpoints.BroadcastMessagesDispose.method,
            data: {
                banner_ids: [message.id]
            }
        })
            .then(() => {
            setOpen(false);
            setClosing(false);
            onClose && onClose(message);
        })
            .catch((error) => {
            Logger.error(SCOPE_SC_UI, error);
        });
    };
    /**
     * Handle on read message
     * @param res
     */
    const handleOnRead = (res) => {
        if (res.status < 300) {
            onRead && onRead(message);
        }
    };
    useEffect(() => {
        setOpen(message.disposed_at === null);
    }, [message]);
    // RENDER
    const renderContent = (banner) => {
        return (_jsxs(_Fragment, { children: [_jsx(CardContent, Object.assign({ className: classes.title }, { children: _jsx(Typography, Object.assign({ variant: "h6" }, { children: banner.title })) })), banner.image && _jsx(CardMedia, { className: classes.media, component: "img", image: banner.image, alt: banner.title }), (banner.body_text || banner.link_text) && (_jsxs(CardContent, Object.assign({ className: classes.content }, { children: [banner.body_text && (_jsx(Typography, Object.assign({ variant: "body1", color: "text.secondary" }, { children: banner.body_text }))), banner.link_text && (_jsx(Typography, Object.assign({ variant: "body1", color: "text.secondary" }, { children: _jsx("a", Object.assign({ href: banner.link, target: banner.open_in_new_tab ? '_blank' : '_self' }, { children: banner.link_text })) })))] })))] }));
    };
    // Banner
    const { banner } = message;
    if (template === SCBroadcastMessageTemplateType.DETAIL || SCBroadcastMessageTemplateType.TOAST) {
        /**
         * With a fade in transition show the Card (Widget)
         * Include also MarkRead component to
         */
        return (_jsx(Root, Object.assign({ id: id, className: classNames(classes.root, className) }, rest, { children: _jsx(Fade, Object.assign({ in: open, unmountOnExit: true }, { children: _jsxs(Box, { children: [message.viewed_at === null && !disableMarkRead && (_jsx(MarkRead, { endpoint: Endpoints.BroadcastMessagesMarkRead, data: { banner_ids: [message.id] }, callback: handleOnRead })), _jsx(CardHeader, { className: classes.header, avatar: _jsx(Avatar, { alt: preferences[SCPreferences.TEXT_APPLICATION_NAME], src: preferences[SCPreferences.LOGO_NAVBAR_LOGO_MOBILE] }), action: template === SCBroadcastMessageTemplateType.DETAIL && (_jsx(IconButton, Object.assign({ "aria-label": "close", onClick: handleClose, disabled: closing }, { children: closing ? _jsx(CircularProgress, { size: 20 }) : _jsx(Icon, { children: "close" }) }))), title: _jsx(Chip, { color: "secondary", size: "small", label: _jsx(FormattedMessage, { id: "ui.broadcastMessages.message.chip", defaultMessage: "ui.broadcastMessages.message.chip" }) }) }), renderContent(banner)] }) })) })));
    }
    // SCBroadcastMessageTemplateType.SNIPPET
    return (_jsx(Root, Object.assign({ id: id, className: className }, rest, { children: _jsxs(ListItem, Object.assign({ alignItems: 'center', component: 'div', classes: {
                root: classNames(classes.listItemSnippet, classes.listItemSnippetNew)
            } }, { children: [_jsx(ListItemAvatar, Object.assign({ classes: { root: classes.messageIconWrap } }, { children: _jsx(Avatar, Object.assign({ variant: "circular", classes: { root: classes.messageIconSnippet } }, { children: _jsx(Icon, { children: "info" }) })) })), _jsx(ListItemText, { disableTypography: true, primary: _jsx(Link, Object.assign({ to: scRoutingContext.url(SCRoutes.USER_NOTIFICATIONS_ROUTE_NAME, {}) }, { children: _jsx(Typography, Object.assign({ component: "span", color: "inherit" }, { children: banner.title })) })) })] })) })));
}
