var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
// ============================================================================
// Chatbot Main - Message
// ============================================================================
import { forwardRef, useEffect, useState } from 'react';
import Markdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Avatar, ContentVariants, Label, Timestamp, Truncate } from '@patternfly/react-core';
import MessageLoading from './MessageLoading';
import CodeBlockMessage from './CodeBlockMessage/CodeBlockMessage';
import TextMessage from './TextMessage/TextMessage';
import FileDetailsLabel from '../FileDetailsLabel/FileDetailsLabel';
import ResponseActions from '../ResponseActions/ResponseActions';
import SourcesCard from '../SourcesCard';
import ListItemMessage from './ListMessage/ListItemMessage';
import UnorderedListMessage from './ListMessage/UnorderedListMessage';
import OrderedListMessage from './ListMessage/OrderedListMessage';
import QuickStartTile from './QuickStarts/QuickStartTile';
import QuickResponse from './QuickResponse/QuickResponse';
import UserFeedback from './UserFeedback/UserFeedback';
import UserFeedbackComplete from './UserFeedback/UserFeedbackComplete';
import TableMessage from './TableMessage/TableMessage';
import TrMessage from './TableMessage/TrMessage';
import TdMessage from './TableMessage/TdMessage';
import TbodyMessage from './TableMessage/TbodyMessage';
import TheadMessage from './TableMessage/TheadMessage';
import ThMessage from './TableMessage/ThMessage';
import ImageMessage from './ImageMessage/ImageMessage';
import rehypeUnwrapImages from 'rehype-unwrap-images';
import rehypeExternalLinks from 'rehype-external-links';
import rehypeSanitize from 'rehype-sanitize';
import LinkMessage from './LinkMessage/LinkMessage';
import ErrorMessage from './ErrorMessage/ErrorMessage';
import MessageInput from './MessageInput';
import { rehypeMoveImagesOutOfParagraphs } from './Plugins/rehypeMoveImagesOutOfParagraphs';
export const MessageBase = (_a) => {
    var { role, content, extraContent, name, avatar, timestamp, isLoading, actions, sources, botWord = 'AI', loadingWord = 'Loading message', codeBlockProps, quickResponses, quickResponseContainerProps = { numLabels: 5 }, attachments, hasRoundAvatar = true, avatarProps, quickStarts, userFeedbackForm, userFeedbackComplete, isLiveRegion = true, innerRef, tableProps, openLinkInNewTab = true, additionalRehypePlugins = [], linkProps, error, isEditable, editPlaceholder = 'Edit prompt message...', updateWord = 'Update', cancelWord = 'Cancel', onEditUpdate, onEditCancel, inputRef, editFormProps, isCompact, isMarkdownDisabled, reactMarkdownProps } = _a, props = __rest(_a, ["role", "content", "extraContent", "name", "avatar", "timestamp", "isLoading", "actions", "sources", "botWord", "loadingWord", "codeBlockProps", "quickResponses", "quickResponseContainerProps", "attachments", "hasRoundAvatar", "avatarProps", "quickStarts", "userFeedbackForm", "userFeedbackComplete", "isLiveRegion", "innerRef", "tableProps", "openLinkInNewTab", "additionalRehypePlugins", "linkProps", "error", "isEditable", "editPlaceholder", "updateWord", "cancelWord", "onEditUpdate", "onEditCancel", "inputRef", "editFormProps", "isCompact", "isMarkdownDisabled", "reactMarkdownProps"]);
    const [messageText, setMessageText] = useState(content);
    useEffect(() => {
        setMessageText(content);
    }, [content]);
    const { beforeMainContent, afterMainContent, endContent } = extraContent || {};
    let rehypePlugins = [rehypeUnwrapImages, rehypeMoveImagesOutOfParagraphs];
    if (openLinkInNewTab) {
        rehypePlugins = rehypePlugins.concat([[rehypeExternalLinks, { target: '_blank' }, rehypeSanitize]]);
    }
    if (additionalRehypePlugins) {
        rehypePlugins.push(...additionalRehypePlugins);
    }
    let avatarClassName;
    if (avatarProps && 'className' in avatarProps) {
        const { className } = avatarProps, rest = __rest(avatarProps, ["className"]);
        avatarClassName = className;
        avatarProps = Object.assign({}, rest);
    }
    // Keep timestamps consistent between Timestamp component and aria-label
    const date = new Date();
    const dateString = timestamp !== null && timestamp !== void 0 ? timestamp : `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
    const handleMarkdown = () => {
        if (isMarkdownDisabled) {
            return (_jsx(TextMessage, Object.assign({ component: ContentVariants.p }, props, { children: messageText })));
        }
        return (_jsx(Markdown, Object.assign({ components: {
                p: (props) => _jsx(TextMessage, Object.assign({ component: ContentVariants.p }, props)),
                code: (_a) => {
                    var { children } = _a, props = __rest(_a, ["children"]);
                    return (_jsx(CodeBlockMessage, Object.assign({}, props, codeBlockProps, { children: children })));
                },
                h1: (props) => _jsx(TextMessage, Object.assign({ component: ContentVariants.h1 }, props)),
                h2: (props) => _jsx(TextMessage, Object.assign({ component: ContentVariants.h2 }, props)),
                h3: (props) => _jsx(TextMessage, Object.assign({ component: ContentVariants.h3 }, props)),
                h4: (props) => _jsx(TextMessage, Object.assign({ component: ContentVariants.h4 }, props)),
                h5: (props) => _jsx(TextMessage, Object.assign({ component: ContentVariants.h5 }, props)),
                h6: (props) => _jsx(TextMessage, Object.assign({ component: ContentVariants.h6 }, props)),
                blockquote: (props) => _jsx(TextMessage, Object.assign({ component: ContentVariants.blockquote }, props)),
                ul: (props) => _jsx(UnorderedListMessage, Object.assign({}, props)),
                ol: (props) => _jsx(OrderedListMessage, Object.assign({}, props)),
                li: (props) => _jsx(ListItemMessage, Object.assign({}, props)),
                table: (props) => _jsx(TableMessage, Object.assign({}, props, tableProps)),
                tbody: (props) => _jsx(TbodyMessage, Object.assign({}, props)),
                thead: (props) => _jsx(TheadMessage, Object.assign({}, props)),
                tr: (props) => _jsx(TrMessage, Object.assign({}, props)),
                td: (props) => {
                    // Conflicts with Td type
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { width } = props, rest = __rest(props, ["width"]);
                    return _jsx(TdMessage, Object.assign({}, rest));
                },
                th: (props) => _jsx(ThMessage, Object.assign({}, props)),
                img: (props) => _jsx(ImageMessage, Object.assign({}, props)),
                a: (props) => (_jsx(LinkMessage, Object.assign({ href: props.href, rel: props.rel, target: props.target }, linkProps, { children: props.children })))
            }, remarkPlugins: [remarkGfm], rehypePlugins: rehypePlugins }, reactMarkdownProps, { children: messageText })));
    };
    const renderMessage = () => {
        if (isLoading) {
            return _jsx(MessageLoading, { loadingWord: loadingWord });
        }
        if (isEditable) {
            return (_jsxs(_Fragment, { children: [beforeMainContent && _jsx(_Fragment, { children: beforeMainContent }), _jsx(MessageInput, Object.assign({ content: messageText, editPlaceholder: editPlaceholder, updateWord: updateWord, cancelWord: cancelWord, onEditUpdate: (event, value) => {
                            onEditUpdate && onEditUpdate(event);
                            setMessageText(value);
                        }, onEditCancel: onEditCancel, inputRef: inputRef }, editFormProps))] }));
        }
        return (_jsxs(_Fragment, { children: [beforeMainContent && _jsx(_Fragment, { children: beforeMainContent }), error ? _jsx(ErrorMessage, Object.assign({}, error)) : handleMarkdown()] }));
    };
    return (_jsxs("section", Object.assign({ "aria-label": `Message from ${role} - ${dateString}`, className: `pf-chatbot__message pf-chatbot__message--${role}`, "aria-live": isLiveRegion ? 'polite' : undefined, "aria-atomic": isLiveRegion ? false : undefined, ref: innerRef }, props, { children: [_jsx(Avatar, Object.assign({ className: `pf-chatbot__message-avatar ${hasRoundAvatar ? 'pf-chatbot__message-avatar--round' : ''} ${avatarClassName ? avatarClassName : ''}`, src: avatar, alt: "" }, avatarProps)), _jsxs("div", { className: "pf-chatbot__message-contents", children: [_jsxs("div", { className: "pf-chatbot__message-meta", children: [name && (_jsx("span", { className: "pf-chatbot__message-name", children: _jsx(Truncate, { content: name }) })), role === 'bot' && (_jsx(Label, { variant: "outline", isCompact: true, children: botWord })), _jsx(Timestamp, { date: date, children: timestamp })] }), _jsxs("div", { className: "pf-chatbot__message-response", children: [_jsxs("div", { className: "pf-chatbot__message-and-actions", children: [renderMessage(), afterMainContent && _jsx(_Fragment, { children: afterMainContent }), !isLoading && sources && _jsx(SourcesCard, Object.assign({}, sources, { isCompact: isCompact })), quickStarts && quickStarts.quickStart && (_jsx(QuickStartTile, { quickStart: quickStarts.quickStart, onSelectQuickStart: quickStarts.onSelectQuickStart, minuteWord: quickStarts.minuteWord, minuteWordPlural: quickStarts.minuteWordPlural, prerequisiteWord: quickStarts.prerequisiteWord, prerequisiteWordPlural: quickStarts.prerequisiteWordPlural, quickStartButtonAriaLabel: quickStarts.quickStartButtonAriaLabel, isCompact: isCompact })), !isLoading && !isEditable && actions && _jsx(ResponseActions, { actions: actions }), userFeedbackForm && _jsx(UserFeedback, Object.assign({}, userFeedbackForm, { timestamp: dateString, isCompact: isCompact })), userFeedbackComplete && (_jsx(UserFeedbackComplete, Object.assign({}, userFeedbackComplete, { timestamp: dateString, isCompact: isCompact }))), !isLoading && quickResponses && (_jsx(QuickResponse, { quickResponses: quickResponses, quickResponseContainerProps: quickResponseContainerProps, isCompact: isCompact }))] }), attachments && (_jsx("div", { className: "pf-chatbot__message-attachments-container", children: attachments.map((attachment) => {
                                    var _a;
                                    return (_jsx("div", { className: "pf-chatbot__message-attachment", children: _jsx(FileDetailsLabel, { fileName: attachment.name, fileId: attachment.id, onClose: attachment.onClose, onClick: attachment.onClick, isLoading: attachment.isLoading, closeButtonAriaLabel: attachment.closeButtonAriaLabel, languageTestId: attachment.languageTestId, spinnerTestId: attachment.spinnerTestId }) }, (_a = attachment.id) !== null && _a !== void 0 ? _a : attachment.name));
                                }) })), !isLoading && endContent && _jsx(_Fragment, { children: endContent })] })] })] })));
};
const Message = forwardRef((props, ref) => (_jsx(MessageBase, Object.assign({ innerRef: ref }, props))));
export default Message;
