import { useQuery } from '@tanstack/react-query';
import { Card, Row, Col, Statistic, Tag, Progress, List, Typography } from 'antd';
import {
  UserOutlined,
  MessageOutlined,
  DollarOutlined,
  RobotOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from 'recharts';
import api from '../../../../shared/utils/api';

const { Title, Text } = Typography;

// Mock数据 - 实际应该从API获取
const mockTrendData = [
  { date: '01-01', conversations: 120, users: 45 },
  { date: '01-02', conversations: 150, users: 52 },
  { date: '01-03', conversations: 180, users: 68 },
  { date: '01-04', conversations: 145, users: 55 },
  { date: '01-05', conversations: 200, users: 75 },
  { date: '01-06', conversations: 230, users: 88 },
  { date: '01-07', conversations: 210, users: 82 },
];

const mockCategoryData = [
  { name: 'QMAS', value: 35, color: '#1890ff' },
  { name: 'GEP', value: 25, color: '#52c41a' },
  { name: 'IANG', value: 20, color: '#faad14' },
  { name: 'TTPS', value: 10, color: '#722ed1' },
  { name: 'CIES', value: 7, color: '#eb2f96' },
  { name: 'TechTAS', value: 3, color: '#13c2c2' },
];

export function DashboardPage() {
  const { data: evolutionStats } = useQuery({
    queryKey: ['evolution-stats'],
    queryFn: async () => {
      const response = await api.get('/evolution/statistics');
      return response.data.data;
    },
  });

  const { data: healthReport } = useQuery({
    queryKey: ['system-health'],
    queryFn: async () => {
      const response = await api.get('/evolution/health');
      return response.data.data;
    },
  });

  const getHealthColor = (status: string) => {
    switch (status) {
      case 'healthy':
        return 'success';
      case 'warning':
        return 'warning';
      case 'critical':
        return 'error';
      default:
        return 'default';
    }
  };

  return (
    <div className="p-6">
      <Title level={4} className="mb-6">仪表盘</Title>

      {/* 核心指标 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="今日用户"
              value={156}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
            <div className="mt-2 text-gray-500 text-sm">
              较昨日 <span className="text-green-500">+12%</span>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="今日对话"
              value={428}
              prefix={<MessageOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
            <div className="mt-2 text-gray-500 text-sm">
              较昨日 <span className="text-green-500">+8%</span>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="今日收入"
              value={3580}
              prefix={<DollarOutlined />}
              suffix="元"
              valueStyle={{ color: '#faad14' }}
            />
            <div className="mt-2 text-gray-500 text-sm">
              较昨日 <span className="text-green-500">+15%</span>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="转化率"
              value={8.5}
              suffix="%"
              prefix={<RobotOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
            <div className="mt-2 text-gray-500 text-sm">
              较昨日 <span className="text-red-500">-2%</span>
            </div>
          </Card>
        </Col>
      </Row>

      {/* 趋势图表 */}
      <Row gutter={[16, 16]} className="mt-4">
        <Col xs={24} lg={16}>
          <Card title="对话趋势">
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={mockTrendData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <Tooltip />
                <Line
                  type="monotone"
                  dataKey="conversations"
                  stroke="#1890ff"
                  name="对话数"
                />
                <Line
                  type="monotone"
                  dataKey="users"
                  stroke="#52c41a"
                  name="用户数"
                />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card title="类别分布">
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={mockCategoryData}
                  dataKey="value"
                  nameKey="name"
                  cx="50%"
                  cy="50%"
                  outerRadius={80}
                  label={({ name, percent }) =>
                    `${name} ${(percent * 100).toFixed(0)}%`
                  }
                >
                  {mockCategoryData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </Card>
        </Col>
      </Row>

      {/* 系统状态 */}
      <Row gutter={[16, 16]} className="mt-4">
        <Col xs={24} lg={12}>
          <Card
            title={
              <div className="flex items-center justify-between">
                <span>系统健康</span>
                <Tag color={getHealthColor(healthReport?.overall || 'healthy')}>
                  {healthReport?.overall === 'healthy'
                    ? '健康'
                    : healthReport?.overall === 'warning'
                    ? '警告'
                    : '异常'}
                </Tag>
              </div>
            }
          >
            <List
              dataSource={healthReport?.metrics || []}
              renderItem={(item: { name: string; value: number; threshold: number; status: string }) => (
                <List.Item>
                  <div className="w-full">
                    <div className="flex justify-between mb-1">
                      <Text>{item.name}</Text>
                      <Text type="secondary">
                        {item.value} / {item.threshold}
                      </Text>
                    </div>
                    <Progress
                      percent={Math.min(100, (item.value / item.threshold) * 100)}
                      status={
                        item.status === 'good'
                          ? 'success'
                          : item.status === 'warning'
                          ? 'exception'
                          : 'active'
                      }
                      showInfo={false}
                      size="small"
                    />
                  </div>
                </List.Item>
              )}
            />
            {healthReport?.recommendations?.length > 0 && (
              <div className="mt-4 p-3 bg-yellow-50 rounded">
                <Text type="warning">建议：</Text>
                <ul className="mt-2 ml-4 text-sm text-gray-600">
                  {healthReport.recommendations.map((rec: string, i: number) => (
                    <li key={i}>{rec}</li>
                  ))}
                </ul>
              </div>
            )}
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card title="经验学习进度">
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <Statistic
                  title="总经验"
                  value={evolutionStats?.totalExperiences || 0}
                  prefix={<RobotOutlined />}
                />
              </Col>
              <Col span={12}>
                <Statistic
                  title="活跃经验"
                  value={evolutionStats?.activeExperiences || 0}
                  prefix={<CheckCircleOutlined />}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Col>
              <Col span={12}>
                <Statistic
                  title="待审核"
                  value={evolutionStats?.pendingExperiences || 0}
                  prefix={<ClockCircleOutlined />}
                  valueStyle={{ color: '#faad14' }}
                />
              </Col>
              <Col span={12}>
                <Statistic
                  title="已审核"
                  value={evolutionStats?.approvedExperiences || 0}
                  prefix={<CheckCircleOutlined />}
                />
              </Col>
            </Row>
            <div className="mt-4">
              <Text type="secondary">经验类型分布</Text>
              <div className="mt-2">
                {evolutionStats?.topExperienceTypes?.map(
                  (item: { type: string; count: number }) => (
                    <Tag key={item.type} className="mb-1">
                      {item.type}: {item.count}
                    </Tag>
                  )
                )}
              </div>
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  );
}
