import React, { useState } from 'react';
import clsx from 'clsx';
import { MessageErrorIcon } from './icons';
import { MessageBouncePrompt as DefaultMessageBouncePrompt } from '../MessageBounce';
import { MessageDeleted as DefaultMessageDeleted } from './MessageDeleted';
import { MessageOptions as DefaultMessageOptions } from './MessageOptions';
import { MessageRepliesCountButton as DefaultMessageRepliesCountButton } from './MessageRepliesCountButton';
import { MessageStatus as DefaultMessageStatus } from './MessageStatus';
import { MessageText } from './MessageText';
import { MessageTimestamp as DefaultMessageTimestamp } from './MessageTimestamp';
import { areMessageUIPropsEqual, isMessageBounced, isMessageEdited, messageHasAttachments, messageHasReactions, } from './utils';
import { Avatar as DefaultAvatar } from '../Avatar';
import { Attachment as DefaultAttachment } from '../Attachment';
import { CUSTOM_MESSAGE_TYPE } from '../../constants/messageTypes';
import { EditMessageForm as DefaultEditMessageForm, MessageInput } from '../MessageInput';
import { MML } from '../MML';
import { Modal } from '../Modal';
import { ReactionsList as DefaultReactionList, ReactionSelector as DefaultReactionSelector, } from '../Reactions';
import { MessageBounceModal } from '../MessageBounce/MessageBounceModal';
import { useComponentContext } from '../../context/ComponentContext';
import { useMessageContext } from '../../context/MessageContext';
import { useTranslationContext } from '../../context';
import { MessageEditedTimestamp } from './MessageEditedTimestamp';
const MessageSimpleWithContext = (props) => {
    const { additionalMessageInputProps, clearEditingState, editing, endOfGroup, firstOfGroup, groupedByUser, handleAction, handleOpenThread, handleRetry, highlighted, isMyMessage, isReactionEnabled, message, onUserClick, onUserHover, reactionSelectorRef, renderText, showDetailedReactions, threadList, } = props;
    const { t } = useTranslationContext('MessageSimple');
    const [isBounceDialogOpen, setIsBounceDialogOpen] = useState(false);
    const [isEditedTimestampOpen, setEditedTimestampOpen] = useState(false);
    const { Attachment = DefaultAttachment, Avatar = DefaultAvatar, EditMessageInput = DefaultEditMessageForm, MessageDeleted = DefaultMessageDeleted, MessageBouncePrompt = DefaultMessageBouncePrompt, MessageOptions = DefaultMessageOptions, MessageRepliesCountButton = DefaultMessageRepliesCountButton, MessageStatus = DefaultMessageStatus, MessageTimestamp = DefaultMessageTimestamp, ReactionSelector = DefaultReactionSelector, ReactionsList = DefaultReactionList, PinIndicator, } = useComponentContext('MessageSimple');
    const hasAttachment = messageHasAttachments(message);
    const hasReactions = messageHasReactions(message);
    if (message.customType === CUSTOM_MESSAGE_TYPE.date) {
        return null;
    }
    if (message.deleted_at || message.type === 'deleted') {
        return React.createElement(MessageDeleted, { message: message });
    }
    /** FIXME: isReactionEnabled should be removed with next major version and a proper centralized permissions logic should be put in place
     * With the current permissions implementation it would be sth like:
     * const messageActions = getMessageActions();
     * const canReact = messageActions.includes(MESSAGE_ACTIONS.react);
     */
    const canReact = isReactionEnabled;
    const canShowReactions = hasReactions;
    const showMetadata = !groupedByUser || endOfGroup;
    const showReplyCountButton = !threadList && !!message.reply_count;
    const allowRetry = message.status === 'failed' && message.errorStatusCode !== 403;
    const isBounced = isMessageBounced(message);
    const isEdited = isMessageEdited(message);
    let handleClick = undefined;
    if (allowRetry) {
        handleClick = () => handleRetry(message);
    }
    else if (isBounced) {
        handleClick = () => setIsBounceDialogOpen(true);
    }
    else if (isEdited) {
        handleClick = () => setEditedTimestampOpen((prev) => !prev);
    }
    const rootClassName = clsx('str-chat__message str-chat__message-simple', `str-chat__message--${message.type}`, `str-chat__message--${message.status}`, isMyMessage()
        ? 'str-chat__message--me str-chat__message-simple--me'
        : 'str-chat__message--other', message.text ? 'str-chat__message--has-text' : 'has-no-text', {
        'str-chat__message--has-attachment': hasAttachment,
        'str-chat__message--highlighted': highlighted,
        'str-chat__message--pinned pinned-message': message.pinned,
        'str-chat__message--with-reactions': canShowReactions,
        'str-chat__message-send-can-be-retried': message?.status === 'failed' && message?.errorStatusCode !== 403,
        'str-chat__message-with-thread-link': showReplyCountButton,
        'str-chat__virtual-message__wrapper--end': endOfGroup,
        'str-chat__virtual-message__wrapper--first': firstOfGroup,
        'str-chat__virtual-message__wrapper--group': groupedByUser,
    });
    return (React.createElement(React.Fragment, null,
        editing && (React.createElement(Modal, { className: 'str-chat__edit-message-modal', onClose: clearEditingState, open: editing },
            React.createElement(MessageInput, { clearEditingState: clearEditingState, grow: true, hideSendButton: true, Input: EditMessageInput, message: message, ...additionalMessageInputProps }))),
        isBounceDialogOpen && (React.createElement(MessageBounceModal, { MessageBouncePrompt: MessageBouncePrompt, onClose: () => setIsBounceDialogOpen(false), open: isBounceDialogOpen })),
        React.createElement("div", { className: rootClassName, key: message.id },
            PinIndicator && React.createElement(PinIndicator, null),
            message.user && (React.createElement(Avatar, { image: message.user.image, name: message.user.name || message.user.id, onClick: onUserClick, onMouseOver: onUserHover, user: message.user })),
            React.createElement("div", { className: clsx('str-chat__message-inner', {
                    'str-chat__simple-message--error-failed': allowRetry || isBounced,
                }), "data-testid": 'message-inner', onClick: handleClick, onKeyUp: handleClick },
                React.createElement(MessageOptions, null),
                React.createElement("div", { className: 'str-chat__message-reactions-host' },
                    canShowReactions && React.createElement(ReactionsList, { reverse: true }),
                    showDetailedReactions && canReact && React.createElement(ReactionSelector, { ref: reactionSelectorRef })),
                React.createElement("div", { className: 'str-chat__message-bubble' },
                    message.attachments?.length && !message.quoted_message ? (React.createElement(Attachment, { actionHandler: handleAction, attachments: message.attachments })) : null,
                    React.createElement(MessageText, { message: message, renderText: renderText }),
                    message.mml && (React.createElement(MML, { actionHandler: handleAction, align: isMyMessage() ? 'right' : 'left', source: message.mml })),
                    React.createElement(MessageErrorIcon, null))),
            showReplyCountButton && (React.createElement(MessageRepliesCountButton, { onClick: handleOpenThread, reply_count: message.reply_count })),
            showMetadata && (React.createElement("div", { className: 'str-chat__message-metadata' },
                React.createElement(MessageStatus, null),
                !isMyMessage() && !!message.user && (React.createElement("span", { className: 'str-chat__message-simple-name' }, message.user.name || message.user.id)),
                React.createElement(MessageTimestamp, { customClass: 'str-chat__message-simple-timestamp' }),
                isEdited && (React.createElement("span", { className: 'str-chat__mesage-simple-edited' }, t('Edited'))),
                isEdited && React.createElement(MessageEditedTimestamp, { calendar: true, open: isEditedTimestampOpen }))))));
};
const MemoizedMessageSimple = React.memo(MessageSimpleWithContext, areMessageUIPropsEqual);
/**
 * The default UI component that renders a message and receives functionality and logic from the MessageContext.
 */
export const MessageSimple = (props) => {
    const messageContext = useMessageContext('MessageSimple');
    return React.createElement(MemoizedMessageSimple, { ...messageContext, ...props });
};
