import { ApiOutlined, DeleteOutlined, DownOutlined, EditOutlined, SettingOutlined } from '@ant-design/icons';
import { Button, Dropdown, Modal, Space, Switch } from 'antd';
import type { Agent } from '../../../api';

function formatAgentModel(raw: string | null | undefined) {
  const s = String(raw ?? '').trim();
  if (!s) return '默认模型';
  if (s.startsWith('[') || s.startsWith('{')) {
    try {
      const parsed = JSON.parse(s);
      if (Array.isArray(parsed)) {
        const names = parsed
          .map((x: any) => String(x?.name || x?.model || x?.id || '').trim())
          .filter(Boolean);
        if (names.length) return names.join(', ');
      } else if (parsed && typeof parsed === 'object') {
        const name = String((parsed as any).name || (parsed as any).model || (parsed as any).id || '').trim();
        if (name) return name;
      }
    } catch {}
  }
  return s;
}

export default function ChatHeader(props: {
  agent: Agent;
  useStream: boolean;
  setUseStream: (v: boolean) => void;
  onOpenHistory: () => void;
  onOpenParams: () => void;
  onOpenMcp: () => void;
  onManageAgent: () => void;
  onClear: () => void;
}) {
  const { agent, useStream, setUseStream, onOpenHistory, onOpenParams, onOpenMcp, onManageAgent, onClear } = props;
  const modelText = formatAgentModel(agent.model);

  return (
    <div className="chat-header">
      <div className="chat-header-agent">
        <div className="chat-header-agent-title">
          <span className="chat-header-agent-name">{agent.name}</span>
          {!!agent.description && <span className="chat-header-agent-desc">{agent.description}</span>}
        </div>
        <div className="chat-header-agent-meta">
          {modelText}
        </div>
      </div>
      <Space>
        <div className="chat-header-stream-toggle">
          <span className="chat-header-stream-label">流式输出</span>
          <Switch size="small" checked={useStream} onChange={setUseStream} />
        </div>
        <Button size="small" onClick={onOpenHistory}>
          历史对话
        </Button>
        <Dropdown
          menu={{
            items: [
              { key: 'params', label: '模型参数', icon: <SettingOutlined />, onClick: onOpenParams },
              { key: 'mcp', label: 'MCP 资源', icon: <ApiOutlined />, onClick: onOpenMcp },
              { key: 'edit', label: '管理 Agent', icon: <EditOutlined />, onClick: onManageAgent },
              { type: 'divider' as const },
              {
                key: 'clear',
                label: '清空对话',
                icon: <DeleteOutlined />,
                danger: true,
                onClick: () => {
                  Modal.confirm({ title: '清空当前会话所有消息？', onOk: onClear });
                }
              }
            ]
          }}
        >
          <Button size="small">
            更多 <DownOutlined />
          </Button>
        </Dropdown>
      </Space>
    </div>
  );
}
