import React from 'react';
import { observer } from 'mobx-react';
import { AssistantMessage, CHUNK_TYPE, Citation } from './types';
import { TbInfoCircleFilled } from 'react-icons/tb';

interface MessageComponentProps {
    message: AssistantMessage;
    index: number;
    onFollowUpClick: (question: string) => void;
    onCitationClick: (citation: Citation) => void;
    updateMessageCitations: (index: number, citations: Citation[]) => void;
}

const MessageComponent: React.FC<MessageComponentProps> = function ({ message, index, onFollowUpClick, onCitationClick, updateMessageCitations }) {
    const LinkRenderer = ({ children }: { children: React.ReactNode }) => {
        const text = children as string;
        const citationRegex = /<citation chunk_id="([^"]*)" type="([^"]*)">([^<]*)<\/citation>/g;
        const parts = [];
        let lastIndex = 0;
        let match;
        const citations: Citation[] = [];

        while ((match = citationRegex.exec(text)) !== null) {
            const [fullMatch, chunkId, type, content] = match;
            const citation: Citation = { chunk_id: chunkId, type: type as CHUNK_TYPE, text: content };
            citations.push(citation);

            parts.push(text.slice(lastIndex, match.index));
            parts.push(
                <a
                    key={chunkId}
                    href="#"
                    onClick={e => {
                        e.preventDefault();
                        onCitationClick(citation);
                    }}
                    style={{
                        color: 'lightblue',
                        verticalAlign: 'super',
                        fontSize: 'smaller',
                    }}>
                    <TbInfoCircleFilled />
                </a>
            );
            lastIndex = match.index + fullMatch.length;
        }

        parts.push(text.slice(lastIndex));

        // Update the message's citations in the ChatBox's history
        updateMessageCitations(index, citations);

        return <>{parts}</>;
    };

    return (
        <div className={`message ${message.role}`}>
            <div>
                <LinkRenderer>{message.text}</LinkRenderer>
            </div>
            {message.follow_up_questions && message.follow_up_questions.length > 0 && (
                <div className="follow-up-questions">
                    <h4>Follow-up Questions:</h4>
                    {message.follow_up_questions.map((question, idx) => (
                        <button key={idx} className="follow-up-button" onClick={() => onFollowUpClick(question)}>
                            {question}
                        </button>
                    ))}
                </div>
            )}
        </div>
    );
};

export default observer(MessageComponent);
