import { memo, useMemo } from "react";
import type { AssistantBlock } from "../../types/message";
import { renderMarkdown } from "../../utils/markdown";
import { ThinkingBlock } from "./ThinkingBlock";
import styles from "./AssistantTurnBody.module.css";

interface AssistantTurnBodyProps {
	blocks: AssistantBlock[];
	streaming?: boolean;
	showThinking?: boolean;
}

interface TextBlockContentProps {
	content: string;
	streaming: boolean;
}

const TextBlockContent = memo(function TextBlockContent({ content, streaming }: TextBlockContentProps) {
	const html = useMemo(() => (streaming ? "" : renderMarkdown(content)), [content, streaming]);

	return (
		<div className={styles.textSegment}>
			{streaming ? (
				<div className={styles.streamingPlain}>{content}</div>
			) : (
				<div
					className={`markdown-body ${styles.text}`}
					data-theme="light"
					dangerouslySetInnerHTML={{ __html: html }}
				/>
			)}
		</div>
	);
});

export const AssistantTurnBody = memo(function AssistantTurnBody({
	blocks,
	streaming = false,
	showThinking = true,
}: AssistantTurnBodyProps) {
	if (blocks.length === 0) return null;

	return (
		<div className={styles.turn}>
			{blocks.map((block, index) => {
				if (block.type === "thinking") {
					if (!showThinking) {
						return (
							<p key={`thinking-${index}`} className={styles.thinkingHidden}>
								Thinking…
							</p>
						);
					}
					return (
						<ThinkingBlock
							key={`thinking-${index}`}
							content={block.content}
							streaming={streaming}
						/>
					);
				}

				return (
					<TextBlockContent
						key={`text-${index}`}
						content={block.content}
						streaming={streaming}
					/>
				);
			})}
		</div>
	);
});