import { useState } from 'react';
import {
  Card,
  Table,
  Tag,
  Space,
  Button,
  Row,
  Col,
  Statistic,
  Typography,
  Badge,
  Popconfirm,
  Tooltip,
  Alert,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  PlusOutlined,
  ReloadOutlined,
  EditOutlined,
  DeleteOutlined,
  ApiOutlined,
  LinkOutlined,
  DisconnectOutlined,
  ExperimentOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import {
  useMcpOverview,
  useMcpServers,
  useMcpServer,
  useDeleteMcpServer,
  useConnectMcpServer,
  useDisconnectMcpServer,
  useTestMcpServer,
  type McpServerDto,
  type McpConnectionState,
} from '../../application/useMcp';
import { ServerFormDrawer } from '../components/ServerFormDrawer';
import { ServerDetailDrawer } from '../components/ServerDetailDrawer';

const { Title, Text } = Typography;

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 McpPage() {
  const [formOpen, setFormOpen] = useState(false);
  const [detailOpen, setDetailOpen] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [viewingId, setViewingId] = useState<string | null>(null);

  const { data: overview, isLoading: loadingOverview } = useMcpOverview();
  const { data: servers, isLoading: loadingServers, refetch } = useMcpServers();
  const { data: viewingServer } = useMcpServer(viewingId, !!viewingId);

  const deleteMutation = useDeleteMcpServer();
  const connectMutation = useConnectMcpServer();
  const disconnectMutation = useDisconnectMcpServer();
  const testMutation = useTestMcpServer();

  const columns: ColumnsType<McpServerDto> = [
    {
      title: '服务器',
      dataIndex: 'name',
      key: 'name',
      render: (name: string, record: McpServerDto) => (
        <Space direction="vertical" size={0}>
          <strong>{name}</strong>
          <Text type="secondary" style={{ fontSize: 12 }}>ID: {record.serverId}</Text>
        </Space>
      ),
    },
    {
      title: '传输',
      dataIndex: 'transport',
      key: 'transport',
      width: 90,
      render: (t: string) => <Tag>{t.toUpperCase()}</Tag>,
    },
    {
      title: '状态',
      dataIndex: 'connectionState',
      key: 'connectionState',
      width: 120,
      render: (state: McpConnectionState, record: McpServerDto) => (
        <Space direction="vertical" size={0}>
          <Badge status={STATE_BADGE[state]} text={STATE_LABEL[state]} />
          {state === 'error' && record.lastError && (
            <Tooltip title={record.lastError}>
              <Text type="danger" style={{ fontSize: 11 }}>
                {record.lastError.substring(0, 30)}...
              </Text>
            </Tooltip>
          )}
        </Space>
      ),
    },
    {
      title: '工具数',
      dataIndex: 'toolCount',
      key: 'toolCount',
      width: 80,
      align: 'center',
      render: (count: number) => <strong>{count}</strong>,
    },
    {
      title: '启用',
      dataIndex: 'enabled',
      key: 'enabled',
      width: 80,
      align: 'center',
      render: (enabled: boolean) => (
        <Tag color={enabled ? 'green' : 'default'}>{enabled ? '是' : '否'}</Tag>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 150,
      render: (date: string) => dayjs(date).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'actions',
      width: 260,
      render: (_: unknown, record: McpServerDto) => (
        <Space size="small">
          <Tooltip title="详情">
            <Button size="small" icon={<EyeOutlined />} onClick={() => { setViewingId(record.id); setDetailOpen(true); }} />
          </Tooltip>

          {record.connectionState === 'connected' ? (
            <Tooltip title="断开">
              <Button size="small" icon={<DisconnectOutlined />} onClick={() => disconnectMutation.mutate(record.id)} loading={disconnectMutation.isPending} />
            </Tooltip>
          ) : (
            <Tooltip title="连接">
              <Button size="small" type="primary" ghost icon={<LinkOutlined />} onClick={() => connectMutation.mutate(record.id)} loading={connectMutation.isPending} />
            </Tooltip>
          )}

          <Tooltip title="测试连接">
            <Button size="small" icon={<ExperimentOutlined />} onClick={() => testMutation.mutate(record.id)} loading={testMutation.isPending} />
          </Tooltip>

          <Tooltip title="编辑">
            <Button size="small" icon={<EditOutlined />} onClick={() => { setEditingId(record.id); setFormOpen(true); }} />
          </Tooltip>

          <Popconfirm
            title="删除 MCP Server"
            description="确认删除？将立即断开连接。"
            onConfirm={() => deleteMutation.mutate(record.id)}
            okText="删除"
            cancelText="取消"
            okButtonProps={{ danger: true }}
          >
            <Tooltip title="删除">
              <Button size="small" danger icon={<DeleteOutlined />} loading={deleteMutation.isPending} />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="p-6">
      <div className="mb-6 flex justify-between items-center">
        <Title level={3} style={{ margin: 0 }}>MCP 服务器管理</Title>
        <Space>
          <Button icon={<ReloadOutlined />} onClick={() => refetch()} loading={loadingServers}>
            刷新
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => { setEditingId(null); setFormOpen(true); }}>
            添加服务器
          </Button>
        </Space>
      </div>

      <Alert
        message="Model Context Protocol (MCP) 服务器管理"
        description="管理为 AI Agent 提供工具和资源的 MCP 服务器。支持 stdio（本地进程）和 SSE（HTTP 流式）两种传输协议。"
        type="info"
        showIcon
        className="mb-6"
      />

      {/* Overview */}
      <Row gutter={16} className="mb-6">
        <Col span={6}>
          <Card><Statistic title="服务器总数" value={overview?.totalServers || 0} prefix={<ApiOutlined />} loading={loadingOverview} /></Card>
        </Col>
        <Col span={6}>
          <Card><Statistic title="已连接" value={overview?.connectedCount || 0} valueStyle={{ color: '#3f8600' }} prefix={<LinkOutlined />} loading={loadingOverview} /></Card>
        </Col>
        <Col span={6}>
          <Card><Statistic title="错误" value={overview?.errorCount || 0} valueStyle={overview?.errorCount ? { color: '#cf1322' } : undefined} loading={loadingOverview} /></Card>
        </Col>
        <Col span={6}>
          <Card><Statistic title="工具总数" value={overview?.totalTools || 0} loading={loadingOverview} /></Card>
        </Col>
      </Row>

      {/* Server Table */}
      <Card>
        <Table
          columns={columns}
          dataSource={servers}
          rowKey="id"
          loading={loadingServers}
          pagination={{ pageSize: 20, showSizeChanger: true, showTotal: (total) => `共 ${total} 个服务器` }}
        />
      </Card>

      {/* Drawers */}
      <ServerFormDrawer
        open={formOpen}
        editingServerId={editingId}
        onClose={() => { setFormOpen(false); setEditingId(null); }}
      />
      <ServerDetailDrawer
        open={detailOpen}
        server={viewingServer || null}
        onClose={() => { setDetailOpen(false); setViewingId(null); }}
      />
    </div>
  );
}
