import { Divider, Tag } from 'antd';
import type { Agent, BranchInfo, ChatMessage } from '../../../api';
import Markdown from '../../../components/Markdown';
import type { StreamingState } from '../hooks/useChatSender';
import type { CopyMode } from '../utils/copy';
import MessageItem from './messages/MessageItem';
import { RetrievedView, ToolCallView } from './messages/MetaViews';

const isImageUrl = (url: string) => url?.startsWith('http') || url?.startsWith('/');

export default function ChatBody(props: {
  bodyRef: React.RefObject<HTMLDivElement>;
  agent: Agent;
  messages: ChatMessage[];
  branches: Record<string, BranchInfo>;
  highlightId: string | null;
  sending: boolean;
  streaming: StreamingState;
  onRegenerate: (assistantId: string) => void;
  onSwitchBranch: (userMsgId: string, branchId: string) => void;
  onCopy: (text: string, mode: CopyMode) => void;
}) {
  const { bodyRef, agent, messages, branches, highlightId, sending, streaming, onRegenerate, onSwitchBranch, onCopy } = props;

  return (
    <div ref={bodyRef} className="chat-body">
      <div className="messages-container">
        {messages.length === 0 && !streaming.active ? (
          <div style={{ textAlign: 'center', marginTop: 120 }}>
            <div
              style={{
                width: 68,
                height: 68,
                borderRadius: '50%',
                background: agent.avatar || 'var(--gradient-brand)',
                color: '#fff',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontWeight: 700,
                fontSize: 32,
                margin: '0 auto 20px',
                boxShadow: 'var(--shadow-lg)',
                overflow: 'hidden'
              }}
            >
              {isImageUrl(agent.avatar) ? <img src={agent.avatar} className="w-full h-full object-cover" alt="avatar" /> : (agent.name?.charAt(0) || '?').toUpperCase()}
            </div>
            <h2 style={{ fontSize: 28, fontWeight: 700, color: 'var(--color-text)', marginBottom: 8, letterSpacing: '-0.02em' }}>你好，今天想一起完成什么？</h2>
            <p style={{ color: 'var(--color-text-secondary)', fontSize: 15, lineHeight: 1.7 }}>{agent.description || '我是你的专属 AI 助手，随时准备为你服务。'}</p>
          </div>
        ) : (
          <>
            {messages.map((m) => (
              <MessageItem
                key={m.id}
                message={m}
                highlighted={highlightId === m.id}
                branch={m.role === 'assistant' && m.parentId ? branches[m.parentId] : undefined}
                busy={sending}
                onRegenerate={onRegenerate}
                onSwitchBranch={onSwitchBranch}
                onCopy={onCopy}
              />
            ))}

            {streaming.active && (
              <div style={{ marginBottom: 24 }}>
                <div className="bubble assistant">
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    {!!streaming.retryInfo?.message && (
                      <div style={{ padding: '8px 10px', borderRadius: 10, background: 'rgba(59, 130, 246, 0.08)', border: '1px solid rgba(59, 130, 246, 0.18)' }}>
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
                          <span style={{ fontSize: 12.5, color: 'var(--color-text)', fontWeight: 600 }}>{streaming.retryInfo.stage === 'fallback_model' ? '自动切换模型' : '自动重试'}</span>
                          {streaming.retryInfo.stage === 'fallback_model' ? (
                            <Tag color="processing" style={{ marginInlineEnd: 0 }}>
                              {String(streaming.retryInfo.fromModel || '')} → {String(streaming.retryInfo.toModel || '')}
                            </Tag>
                          ) : (
                            <Tag color="processing" style={{ marginInlineEnd: 0 }}>
                              {String(streaming.retryInfo.model || '')}
                              {streaming.retryInfo.attempt ? ` · 第${streaming.retryInfo.attempt}次` : ''}
                            </Tag>
                          )}
                        </div>
                        <div style={{ marginTop: 4, fontSize: 12.5, color: 'var(--color-text-secondary)', lineHeight: 1.55 }}>{String(streaming.retryInfo.message)}</div>
                        {!!streaming.retryInfo.reason && (
                          <div style={{ marginTop: 4, fontSize: 12, color: 'var(--color-text-tertiary)', lineHeight: 1.5 }}>{String(streaming.retryInfo.reason)}</div>
                        )}
                      </div>
                    )}
                    <div>
                      <div style={{ fontSize: 12, color: 'var(--color-text-tertiary)', marginBottom: 4 }}>推理过程</div>
                      {streaming.reasoningText ? <Markdown>{streaming.reasoningText + '▍'}</Markdown> : <span style={{ color: 'var(--color-text-tertiary)' }}>等待推理…</span>}
                    </div>
                    <Divider style={{ margin: '6px 0' }} />
                    <div>
                      <div style={{ fontSize: 12, color: 'var(--color-text-tertiary)', marginBottom: 4 }}>正式回答</div>
                      {streaming.answerText ? <Markdown>{streaming.answerText + '▍'}</Markdown> : <span style={{ color: 'var(--color-text-tertiary)' }}>等待输出…</span>}
                    </div>
                  </div>
                </div>
                {(streaming.retrieved.length > 0 || streaming.toolCalls.length > 0) && (
                  <div style={{ maxWidth: '85%' }}>
                    {streaming.retrieved.length > 0 && <RetrievedView retrieved={streaming.retrieved} />}
                    {streaming.toolCalls.length > 0 && <ToolCallView calls={streaming.toolCalls} liveStyle />}
                  </div>
                )}
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}
