import React from 'react';
import { ThoughtChain } from '@ant-design/x';

interface ToolCall {
  id: string;
  name: string;
  input: string;
  output?: string;
  isError?: boolean;
}

interface ToolChainProps {
  tools: ToolCall[];
}

const ToolChain: React.FC<ToolChainProps> = ({ tools }) => {
  const items = tools.map((tool) => {
    const hasResult = tool.output !== undefined;
    let status: 'loading' | 'success' | 'error' = 'loading';
    if (hasResult) {
      status = tool.isError ? 'error' : 'success';
    }

    return {
      key: tool.id,
      status,
      title: tool.name,
      description: hasResult ? (tool.isError ? '执行出错' : '执行完成') : '执行中...',
      collapsible: true,
      content: (
        <div style={{ fontSize: 13 }}>
          {tool.input && (
            <div style={{ marginBottom: 8 }}>
              <div style={{ fontWeight: 500, marginBottom: 4 }}>输入</div>
              <pre style={{
                margin: 0,
                padding: 8,
                borderRadius: 6,
                background: 'rgba(0,0,0,0.04)',
                overflow: 'auto',
                maxHeight: 200,
                fontSize: 12,
              }}>
                {tryFormatJSON(tool.input)}
              </pre>
            </div>
          )}
          {tool.output !== undefined && (
            <div>
              <div style={{ fontWeight: 500, marginBottom: 4 }}>
                {tool.isError ? '错误' : '输出'}
              </div>
              <pre style={{
                margin: 0,
                padding: 8,
                borderRadius: 6,
                background: tool.isError ? 'rgba(255,0,0,0.04)' : 'rgba(0,0,0,0.04)',
                overflow: 'auto',
                maxHeight: 300,
                fontSize: 12,
              }}>
                {tool.output}
              </pre>
            </div>
          )}
        </div>
      ),
    };
  });

  if (items.length === 0) return null;

  return <ThoughtChain items={items} />;
};

function tryFormatJSON(str: string): string {
  try {
    return JSON.stringify(JSON.parse(str), null, 2);
  } catch {
    return str;
  }
}

export default ToolChain;
export type { ToolCall };
