// ============================================================================
// Chatbot Main - Message
// ============================================================================
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 React 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';
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, editFormProps, isCompact } = _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", "editFormProps", "isCompact"]);
    const [messageText, setMessageText] = React.useState(content);
    React.useEffect(() => {
        setMessageText(content);
    }, [content]);
    const { beforeMainContent, afterMainContent, endContent } = extraContent || {};
    let rehypePlugins = [rehypeUnwrapImages];
    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 renderMessage = () => {
        if (isLoading) {
            return React.createElement(MessageLoading, { loadingWord: loadingWord });
        }
        if (isEditable) {
            return (React.createElement(React.Fragment, null,
                beforeMainContent && React.createElement(React.Fragment, null, beforeMainContent),
                React.createElement(MessageInput, Object.assign({ content: content, editPlaceholder: editPlaceholder, updateWord: updateWord, cancelWord: cancelWord, onEditUpdate: (event, text) => {
                        onEditUpdate && onEditUpdate(event);
                        setMessageText(text);
                    }, onEditCancel: onEditCancel }, editFormProps))));
        }
        return (React.createElement(React.Fragment, null,
            beforeMainContent && React.createElement(React.Fragment, null, beforeMainContent),
            error ? (React.createElement(ErrorMessage, Object.assign({}, error))) : (React.createElement(Markdown, { components: {
                    p: (props) => React.createElement(TextMessage, Object.assign({ component: ContentVariants.p }, props)),
                    code: (_a) => {
                        var { children } = _a, props = __rest(_a, ["children"]);
                        return (React.createElement(CodeBlockMessage, Object.assign({}, props, codeBlockProps), children));
                    },
                    h1: (props) => React.createElement(TextMessage, Object.assign({ component: ContentVariants.h1 }, props)),
                    h2: (props) => React.createElement(TextMessage, Object.assign({ component: ContentVariants.h2 }, props)),
                    h3: (props) => React.createElement(TextMessage, Object.assign({ component: ContentVariants.h3 }, props)),
                    h4: (props) => React.createElement(TextMessage, Object.assign({ component: ContentVariants.h4 }, props)),
                    h5: (props) => React.createElement(TextMessage, Object.assign({ component: ContentVariants.h5 }, props)),
                    h6: (props) => React.createElement(TextMessage, Object.assign({ component: ContentVariants.h6 }, props)),
                    blockquote: (props) => React.createElement(TextMessage, Object.assign({ component: ContentVariants.blockquote }, props)),
                    ul: (props) => React.createElement(UnorderedListMessage, Object.assign({}, props)),
                    ol: (props) => React.createElement(OrderedListMessage, Object.assign({}, props)),
                    li: (props) => React.createElement(ListItemMessage, Object.assign({}, props)),
                    table: (props) => React.createElement(TableMessage, Object.assign({}, props, tableProps)),
                    tbody: (props) => React.createElement(TbodyMessage, Object.assign({}, props)),
                    thead: (props) => React.createElement(TheadMessage, Object.assign({}, props)),
                    tr: (props) => React.createElement(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 React.createElement(TdMessage, Object.assign({}, rest));
                    },
                    th: (props) => React.createElement(ThMessage, Object.assign({}, props)),
                    img: (props) => React.createElement(ImageMessage, Object.assign({}, props)),
                    a: (props) => (React.createElement(LinkMessage, Object.assign({ href: props.href, rel: props.rel, target: props.target }, linkProps), props.children))
                }, remarkPlugins: [remarkGfm], rehypePlugins: rehypePlugins }, messageText))));
    };
    return (React.createElement("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),
        React.createElement(Avatar, Object.assign({ className: `pf-chatbot__message-avatar ${hasRoundAvatar ? 'pf-chatbot__message-avatar--round' : ''} ${avatarClassName ? avatarClassName : ''}`, src: avatar, alt: "" }, avatarProps)),
        React.createElement("div", { className: "pf-chatbot__message-contents" },
            React.createElement("div", { className: "pf-chatbot__message-meta" },
                name && (React.createElement("span", { className: "pf-chatbot__message-name" },
                    React.createElement(Truncate, { content: name }))),
                role === 'bot' && (React.createElement(Label, { variant: "outline", isCompact: true }, botWord)),
                React.createElement(Timestamp, { date: date }, timestamp)),
            React.createElement("div", { className: "pf-chatbot__message-response" },
                React.createElement("div", { className: "pf-chatbot__message-and-actions" },
                    renderMessage(),
                    afterMainContent && React.createElement(React.Fragment, null, afterMainContent),
                    !isLoading && sources && React.createElement(SourcesCard, Object.assign({}, sources, { isCompact: isCompact })),
                    quickStarts && quickStarts.quickStart && (React.createElement(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 && actions && React.createElement(ResponseActions, { actions: actions }),
                    userFeedbackForm && React.createElement(UserFeedback, Object.assign({}, userFeedbackForm, { timestamp: dateString, isCompact: isCompact })),
                    userFeedbackComplete && (React.createElement(UserFeedbackComplete, Object.assign({}, userFeedbackComplete, { timestamp: dateString, isCompact: isCompact }))),
                    !isLoading && quickResponses && (React.createElement(QuickResponse, { quickResponses: quickResponses, quickResponseContainerProps: quickResponseContainerProps, isCompact: isCompact }))),
                attachments && (React.createElement("div", { className: "pf-chatbot__message-attachments-container" }, attachments.map((attachment) => {
                    var _a;
                    return (React.createElement("div", { key: (_a = attachment.id) !== null && _a !== void 0 ? _a : attachment.name, className: "pf-chatbot__message-attachment" },
                        React.createElement(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 })));
                }))),
                !isLoading && endContent && React.createElement(React.Fragment, null, endContent)))));
};
const Message = React.forwardRef((props, ref) => (React.createElement(MessageBase, Object.assign({ innerRef: ref }, props))));
export default Message;
