import {
  Drawer,
  Descriptions,
  Badge,
  Tag,
  Typography,
  Space,
  Card,
  List,
  Collapse,
  Alert,
  Spin,
  Empty,
} from 'antd';
import { ApiOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import type { McpServerDetailDto, McpConnectionState } from '../../application/useMcp';

const { Text } = Typography;

interface ServerDetailDrawerProps {
  open: boolean;
  server: McpServerDetailDto | null;
  onClose: () => void;
}

const STATE_BADGE: Record<McpConnectionState, 'success' | 'processing' | 'default' | 'error'> = {
  connected: 'success',
  connecting: 'processing',
  disconnected: 'default',
  error: 'error',
};

const STATE_LABEL: Record<McpConnectionState, string> = {
  connected: '已连接',
  connecting: '连接中',
  disconnected: '未连接',
  error: '错误',
};

export function ServerDetailDrawer({ open, server, onClose }: ServerDetailDrawerProps) {
  if (!server && open) {
    return (
      <Drawer title="服务器详情" width={680} open={open} onClose={onClose}>
        <div className="flex justify-center items-center h-64"><Spin size="large" /></div>
      </Drawer>
    );
  }

  if (!server) return null;

  const toolItems = (server.tools || []).map(tool => ({
    key: tool.name,
    label: (
      <Space>
        <ApiOutlined />
        <strong>{tool.originalName}</strong>
        {tool.isConcurrencySafe && <Tag color="blue" style={{ fontSize: 11 }}>并发安全</Tag>}
      </Space>
    ),
    children: (
      <Descriptions column={1} size="small" bordered>
        <Descriptions.Item label="完整名称">{tool.name}</Descriptions.Item>
        <Descriptions.Item label="描述">{tool.description}</Descriptions.Item>
        <Descriptions.Item label="输入 Schema">
          <pre style={{ fontSize: 11, maxHeight: 300, overflow: 'auto', margin: 0 }}>
            {JSON.stringify(tool.input_schema, null, 2)}
          </pre>
        </Descriptions.Item>
      </Descriptions>
    ),
  }));

  return (
    <Drawer title="服务器详情" width={680} open={open} onClose={onClose}>
      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        {/* Basic Info */}
        <Card title="基本信息" size="small">
          <Descriptions column={1} bordered size="small">
            <Descriptions.Item label="Server ID">{server.serverId}</Descriptions.Item>
            <Descriptions.Item label="名称">{server.name}</Descriptions.Item>
            <Descriptions.Item label="描述">{server.description || <Text type="secondary">无</Text>}</Descriptions.Item>
            <Descriptions.Item label="传输"><Tag>{server.transport.toUpperCase()}</Tag></Descriptions.Item>
            <Descriptions.Item label="状态">
              <Badge status={STATE_BADGE[server.connectionState]} text={STATE_LABEL[server.connectionState]} />
            </Descriptions.Item>
            <Descriptions.Item label="启用">
              {server.enabled
                ? <Tag color="green" icon={<CheckCircleOutlined />}>是</Tag>
                : <Tag icon={<CloseCircleOutlined />}>否</Tag>
              }
            </Descriptions.Item>
            <Descriptions.Item label="发现工具数"><strong>{server.toolCount}</strong></Descriptions.Item>
            <Descriptions.Item label="创建时间">{dayjs(server.createdAt).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
            <Descriptions.Item label="更新时间">{dayjs(server.updatedAt).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
            {server.connectedAt && (
              <Descriptions.Item label="连接时间">{dayjs(server.connectedAt).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
            )}
          </Descriptions>
        </Card>

        {/* Transport Config */}
        <Card title="传输配置" size="small">
          {server.transport === 'stdio' ? (
            <Descriptions column={1} bordered size="small">
              <Descriptions.Item label="命令">{server.command}</Descriptions.Item>
              <Descriptions.Item label="参数">
                {server.args && server.args.length > 0
                  ? <List size="small" dataSource={server.args} renderItem={(arg: string) => <List.Item>{arg}</List.Item>} />
                  : <Text type="secondary">无</Text>
                }
              </Descriptions.Item>
              <Descriptions.Item label="环境变量">
                {server.env && Object.keys(server.env).length > 0
                  ? <pre style={{ fontSize: 12, margin: 0 }}>{JSON.stringify(server.env, null, 2)}</pre>
                  : <Text type="secondary">无</Text>
                }
              </Descriptions.Item>
            </Descriptions>
          ) : (
            <Descriptions column={1} bordered size="small">
              <Descriptions.Item label="URL">{server.url}</Descriptions.Item>
            </Descriptions>
          )}
        </Card>

        {/* Settings */}
        <Card title="设置" size="small">
          <Descriptions column={1} bordered size="small">
            <Descriptions.Item label="工具并发安全">{server.toolsConcurrencySafe ? '是' : '否'}</Descriptions.Item>
            <Descriptions.Item label="连接超时">{server.connectTimeoutMs}ms</Descriptions.Item>
            <Descriptions.Item label="工具执行超时">{server.toolTimeoutMs}ms</Descriptions.Item>
          </Descriptions>
        </Card>

        {/* Error */}
        {server.lastError && (
          <Alert message="最近错误" description={server.lastError} type="error" showIcon />
        )}

        {/* Tools */}
        <Card title={`已发现工具 (${server.tools?.length || 0})`} size="small">
          {toolItems.length > 0 ? (
            <Collapse accordion items={toolItems} />
          ) : (
            <Empty description="未发现工具（服务器可能未连接）" image={Empty.PRESENTED_IMAGE_SIMPLE} />
          )}
        </Card>
      </Space>
    </Drawer>
  );
}
