import { memo, useMemo } from "react";
import { deriveToolCallSummary, formatToolBodyHtml } from "../../utils/toolCall";
import { renderMarkdown } from "../../utils/markdown";
import styles from "./ToolCallBlock.module.css";

interface ToolCallBlockProps {
	content: string;
	forceOpen?: boolean;
}

function parseToolCallContent(content: string): {
	title: string;
	body: string;
	status: "pending" | "success" | "error";
} {
	const trimmed = content.trimStart();
	let status: "pending" | "success" | "error" = "pending";
	let rest = trimmed;
	if (trimmed.startsWith("✅")) {
		status = "success";
		rest = trimmed.slice(1).trimStart();
	} else if (trimmed.startsWith("❌")) {
		status = "error";
		rest = trimmed.slice(1).trimStart();
	} else if (trimmed.startsWith("🔧")) {
		status = "pending";
		rest = trimmed.slice(2).trimStart();
	}

	const lines = rest.split("\n");
	const title = lines[0]?.trim() || "tool";
	const body = lines.slice(1).join("\n").trim();
	return { title, body, status };
}

interface ToolBodyProps {
	body: string;
	fallback: string;
	hasDiff: boolean;
	status: "pending" | "success" | "error";
}

const ToolBody = memo(function ToolBody({ body, fallback, hasDiff, status }: ToolBodyProps) {
	const text = body || fallback;
	const html = useMemo(() => {
		if (!text.trim() || hasDiff || status === "pending") return "";
		return renderMarkdown(text);
	}, [text, hasDiff, status]);

	if (!text.trim()) return null;

	if (hasDiff) {
		return (
			<pre
				className={styles.diffPre}
				dangerouslySetInnerHTML={{ __html: formatToolBodyHtml(text) }}
			/>
		);
	}

	if (status === "pending") {
		return <pre className={styles.plainPre}>{text}</pre>;
	}

	return (
		<div
			className={`markdown-body ${styles.markdownBody}`}
			data-theme="light"
			dangerouslySetInnerHTML={{ __html: html }}
		/>
	);
});

export const ToolCallBlock = memo(function ToolCallBlock({ content, forceOpen }: ToolCallBlockProps) {
	const { title, body, status } = useMemo(() => parseToolCallContent(content), [content]);
	const hasDiff =
		body.includes("\n+") || body.includes("\n-") || body.startsWith("+") || body.startsWith("-");
	const statusLabel = status === "success" ? "完成" : status === "error" ? "失败" : "执行中";
	const toolName = title.split("(")[0]?.trim() || deriveToolCallSummary(content);
	const hasDetail = Boolean(body || (title.includes("(") && title !== toolName) || content !== title);

	return (
		<details className={`tool-call-block ${styles.block} ${styles[status]}`} open={forceOpen}>
			<summary className={styles.summary}>
				<span className={styles.toolName} title={title}>
					{toolName}
				</span>
				<span className={styles.status}>{statusLabel}</span>
			</summary>
			{hasDetail ? (
				<div className={styles.detail}>
					{title.includes("(") ? <div className={styles.args}>{title}</div> : null}
					<ToolBody body={body} fallback={content} hasDiff={hasDiff} status={status} />
				</div>
			) : null}
		</details>
	);
});