import React, { useMemo } from "react";
import useRenderTracker from "../../../hooks/useRenderTracker";
import MarkdownBlock from "../Blocks/MarkdownBlock";
import CodeBlock from "../Blocks/CodeBlock";
import { ParsedBlock, parseMarkdownAndCode } from "../../../utils/parseMarkdownAndCode";
import type { FinalizedThinkingSummary } from "../../../types/chatStream";
import AssistantThinkingSummary from "./AssistantThinkingSummary";
import AssistantAvatar from "./AssistantAvatar";


interface StaticAssistantMessageProps {
    content: string;
    status?: 'complete' | 'interrupted';
    thinkingSummary?: FinalizedThinkingSummary;
}

const StaticAssistantMessage: React.FC<StaticAssistantMessageProps> = ({ content, status, thinkingSummary }) => {

    useRenderTracker('StaticAssistantMessage', { content, status, thinkingSummary });

    const displayContent = (
      status === 'interrupted' && content.trim().length > 0
        ? `[Interrupted by user before completion]\n\n${content}`
        : content
    );

    const blocks: ParsedBlock[] = useMemo(() => parseMarkdownAndCode(displayContent), [displayContent]);

    const renderedBlocks = useMemo(() => (
        <>
            {blocks.map((block) => {
                if (block.type === 'markdown') {
                    return <MarkdownBlock key={`${block.startIndex}-${block.endIndex}`} content={block.content} />;
                }
                if (block.type === 'code') {
                    return <CodeBlock key={`${block.startIndex}-${block.endIndex}`} content={block.content} language={block.language} />;
                }
                return null;
            })}
        </>
    ), [blocks]);


    return (
        <div className="chat-output assistant-message group my-6 flex max-w-full items-start gap-3 text-app-text">
          <AssistantAvatar />
          <div className="min-w-0 flex-1 overflow-hidden">
            {thinkingSummary && (
              <AssistantThinkingSummary
                label={`Worked for ${Math.max(1, Math.round(thinkingSummary.durationMs / 1000))}s`}
                timeline={thinkingSummary.timeline}
              />
            )}
            <div className="chat-content max-w-none">
              {renderedBlocks}
            </div>
            {status === 'interrupted' && (
              <div className="mt-2 text-xs font-medium text-app-muted">
                Stopped
              </div>
            )}
          </div>
        </div>
    );
}

export default React.memo(StaticAssistantMessage);
