import React, { useState, useEffect } from 'react';
import { Table, Card, Row, Col, Statistic, Button, App } from 'antd';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import api from '../../services/api';
import { formatDateTime } from '../../utils/validation';

interface Record {
  id: string;
  userId: string;
  userName: string;
  userPhone: string;
  totalScore: number;
  correctCount: number;
  totalCount: number;
  scorePercentage: number;
  status: '不及格' | '合格' | '优秀';
  createdAt: string;
}

const COLORS = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#13c2c2'];

const getStatusColor = (status: string) => {
  switch (status) {
    case '不及格':
      return 'red';
    case '合格':
      return 'blue';
    case '优秀':
      return 'green';
    default:
      return 'default';
  }
};

const UserRecordsPage = ({ userId }: { userId: string }) => {
  const { message } = App.useApp();
  const [records, setRecords] = useState<Record[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    size: 'small' as const,
  });

  const fetchRecords = async (page = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const res = await api.get(`/admin/users/${userId}/records?page=${page}&limit=${pageSize}`);
      setRecords(res.data.data);
      setPagination({
        current: page,
        pageSize,
        total: res.data.pagination.total,
        size: 'small' as const,
      });
    } catch (error) {
      message.error('获取答题记录失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchRecords();
  }, [userId]);

  const handleTableChange = (newPagination: any) => {
    fetchRecords(newPagination.current, newPagination.pageSize);
  };

  const handleViewDetail = (recordId: string) => {
    window.open(`/admin/quiz/records/detail/${recordId}`, '_blank');
  };

  const columns = [
    {
      title: '答题时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text: string) => formatDateTime(text, { includeSeconds: true }),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <span className={`px-2 py-1 rounded text-xs font-medium bg-${getStatusColor(status)}-100 text-${getStatusColor(status)}-800`}>
          {status}
        </span>
      ),
    },
    {
      title: '总得分',
      dataIndex: 'totalScore',
      key: 'totalScore',
      render: (score: number) => <span className="font-semibold text-blue-600">{score} 分</span>,
    },
    {
      title: '正确题数',
      dataIndex: 'correctCount',
      key: 'correctCount',
      render: (count: number, record: Record) => `${count} / ${record.totalCount}`,
    },
    {
      title: '正确率',
      key: 'correctRate',
      render: (_: any, record: Record) => {
        const rate = record.totalCount > 0 ? ((record.correctCount / record.totalCount) * 100).toFixed(1) : '0.0';
        return <span>{rate}%</span>;
      },
    },
    {
      title: <div style={{ textAlign: 'center' }}>操作</div>,
      key: 'action',
      render: (_: any, record: Record) => (
        <Button type="link" onClick={() => handleViewDetail(record.id)}>
          查看详情
        </Button>
      ),
    },
  ];

  const scoreDistribution = records.reduce((acc: any, record) => {
    const range = Math.floor(record.totalScore / 10) * 10;
    const key = `${range}-${range + 9}`;
    acc[key] = (acc[key] || 0) + 1;
    return acc;
  }, {});

  const chartData = Object.entries(scoreDistribution).map(([range, count]) => ({
    range,
    count,
  }));

  const totalRecords = records.length;
  const averageScore = totalRecords > 0 ? records.reduce((sum, r) => sum + r.totalScore, 0) / totalRecords : 0;
  const highestScore = totalRecords > 0 ? Math.max(...records.map(r => r.totalScore)) : 0;
  const lowestScore = totalRecords > 0 ? Math.min(...records.map(r => r.totalScore)) : 0;

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-800">用户答题记录</h1>
      </div>

      <Row gutter={16} className="mb-6">
        <Col span={6}>
          <Card>
            <Statistic title="总答题次数" value={totalRecords} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="平均得分" value={averageScore.toFixed(1)} suffix="分" />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="最高得分" value={highestScore} suffix="分" />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="最低得分" value={lowestScore} suffix="分" />
          </Card>
        </Col>
      </Row>

      {chartData.length > 0 && (
        <Card title="得分分布" className="mb-6">
          <ResponsiveContainer width="100%" height={300}>
            <BarChart data={chartData}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="range" />
              <YAxis />
              <Tooltip />
              <Bar dataKey="count" fill="#3b82f6" />
            </BarChart>
          </ResponsiveContainer>
        </Card>
      )}

      <Card title="答题记录">
        <Table
          columns={columns}
          dataSource={records}
          rowKey="id"
          size="small"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
        />
      </Card>
    </div>
  );
};

export default UserRecordsPage;