import { Button, Dropdown, Space, Tag, Tooltip } from 'antd';
import type { BranchInfo, ChatMessage } from '../../../../api';
import Markdown from '../../../../components/Markdown';
import { ProductCopyIcon } from '../../../../components/icons';
import type { CopyMode } from '../../utils/copy';
import { ReasoningView, RetrievedView, ToolCallView } from './MetaViews';

export default function MessageItem(props: {
  message: ChatMessage;
  highlighted?: boolean;
  branch?: BranchInfo;
  busy?: boolean;
  onRegenerate?: (id: string) => void;
  onSwitchBranch?: (userMsgId: string, branchId: string) => void;
  onCopy?: (text: string, mode: CopyMode) => void;
}) {
  const { message, highlighted, branch, busy, onRegenerate, onSwitchBranch, onCopy } = props;
  const hasBranches = !!branch && branch.total > 1;
  const activeIdx = branch?.activeIndex ?? 0;
  const total = branch?.total ?? 1;

  const goPrev = () => {
    if (!branch || !message.parentId) return;
    const i = Math.max(0, activeIdx - 1);
    onSwitchBranch?.(message.parentId, branch.ids[i]);
  };

  const goNext = () => {
    if (!branch || !message.parentId) return;
    const i = Math.min(total - 1, activeIdx + 1);
    onSwitchBranch?.(message.parentId, branch.ids[i]);
  };

  return (
    <div
      id={'msg-' + message.id}
      style={{
        marginBottom: 12,
        padding: highlighted ? 8 : 0,
        borderRadius: highlighted ? 10 : 0,
        background: highlighted ? 'rgba(254, 243, 199, 0.6)' : 'transparent',
        transition: 'background 0.4s, padding 0.4s'
      }}
    >
      <div className={`bubble ${message.role}`}>
        {message.role === 'assistant' ? (
          <Markdown>{message.content}</Markdown>
        ) : message.content.includes('![image](') ? (
          <Markdown>{message.content}</Markdown>
        ) : (
          message.content
        )}
      </div>

      {message.role === 'assistant' && (
        <div className="monica-msg-actions" style={{ maxWidth: '78%' }}>
          {hasBranches && (
            <Space size={2}>
              <Button size="small" type="text" disabled={activeIdx === 0} onClick={goPrev}>
                ‹
              </Button>
              <span>
                {activeIdx + 1} / {total}
              </span>
              <Button size="small" type="text" disabled={activeIdx === total - 1} onClick={goNext}>
                ›
              </Button>
            </Space>
          )}
          {message.meta?.aborted && <Tag color="orange">已停止</Tag>}
          <Dropdown
            trigger={['click']}
            menu={{
              items: [
                { key: 'plain', label: '复制纯文本', onClick: () => onCopy?.(message.content, 'plain') },
                { key: 'markdown', label: '复制 Markdown', onClick: () => onCopy?.(message.content, 'markdown') }
              ]
            }}
          >
            <Tooltip title="复制">
              <span className="chat-copy-icon" aria-label="copy">
                <ProductCopyIcon />
              </span>
            </Tooltip>
          </Dropdown>
          <Tooltip title="重新生成（开新分支）">
            <Button size="small" type="text" disabled={busy} onClick={() => onRegenerate?.(message.id)}>
              🔄
            </Button>
          </Tooltip>
        </div>
      )}

      {message.role === 'assistant' && message.meta && (
        <div style={{ maxWidth: '78%' }}>
          {!!message.meta.reasoning && <ReasoningView reasoning={message.meta.reasoning} />}
          {!!message.meta.retrieved?.length && <RetrievedView retrieved={message.meta.retrieved} />}
          {!!message.meta.toolCalls?.length && <ToolCallView calls={message.meta.toolCalls} />}
        </div>
      )}
    </div>
  );
}
