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';
import GlassCard from '../../components/common/GlassCard';

interface Answer {
  id: string;
  questionId: string;
  questionContent: string;
  questionType: string;
  userAnswer: string | string[];
  correctAnswer: string | string[];
  score: number;
  questionScore: number;
  isCorrect: boolean;
  createdAt: string;
}

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

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 RecordDetailPage = ({ recordId }: { recordId: string }) => {
  const { message } = App.useApp();
  const [record, setRecord] = useState<Record | null>(null);
  const [loading, setLoading] = useState(false);

  const fetchRecordDetail = async () => {
    setLoading(true);
    try {
      const res = await api.get(`/admin/quiz/records/detail/${recordId}`);
      setRecord(res.data);
    } catch (error) {
      message.error('获取答题记录详情失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchRecordDetail();
  }, [recordId]);

  if (!record) return null;

  const typeStats = record.answers.reduce((acc: any, answer) => {
    const type = answer.questionType;
    if (!acc[type]) {
      acc[type] = { type, total: 0, correct: 0 };
    }
    acc[type].total += 1;
    if (answer.isCorrect) {
      acc[type].correct += 1;
    }
    return acc;
  }, {});

  const typeChartData = Object.values(typeStats).map((item: any) => ({
    type: item.type,
    正确率: item.total > 0 ? ((item.correct / item.total) * 100).toFixed(1) : '0.0',
  }));

  const pieData = [
    { name: '正确', value: record.correctCount, color: '#10b981' },
    { name: '错误', value: record.totalCount - record.correctCount, color: '#ef4444' },
  ];

  const columns = [
    {
      title: '题目内容',
      dataIndex: 'questionContent',
      key: 'questionContent',
      width: '40%',
    },
    {
      title: '题型',
      dataIndex: 'questionType',
      key: 'questionType',
      width: '10%',
    },
    {
      title: '用户答案',
      dataIndex: 'userAnswer',
      key: 'userAnswer',
      width: '20%',
      render: (answer: string | string[]) => {
        if (Array.isArray(answer)) {
          return answer.join(', ');
        }
        return answer;
      },
    },
    {
      title: '正确答案',
      dataIndex: 'correctAnswer',
      key: 'correctAnswer',
      width: '20%',
      render: (answer: string | string[]) => {
        if (Array.isArray(answer)) {
          return answer.join(', ');
        }
        return answer;
      },
    },
    {
      title: '得分',
      dataIndex: 'score',
      key: 'score',
      width: '5%',
      render: (score: number, record: Answer) => (
        <span className={record.isCorrect ? 'text-emerald-400' : 'text-rose-400'}>
          {score} / {record.questionScore}
        </span>
      ),
    },
    {
      title: '结果',
      dataIndex: 'isCorrect',
      key: 'isCorrect',
      width: '5%',
      render: (isCorrect: boolean) => (
        <span className={isCorrect ? 'text-emerald-400' : 'text-rose-400'}>
          {isCorrect ? '✓' : '✗'}
        </span>
      ),
    },
  ];

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-white">答题记录详情</h1>
        <p className="text-white/60 mt-2">
          答题时间：{formatDateTime(record.createdAt, { includeSeconds: true })}
        </p>
      </div>

      <Row gutter={[16, 16]} className="mb-6">
        <Col xs={24} sm={12} md={5}>
          <GlassCard>
            <Statistic title={<span className="text-white/70">考试状态</span>} value={record.status} valueStyle={{ color: getStatusColor(record.status) === 'red' ? '#F87171' : getStatusColor(record.status) === 'green' ? '#34D399' : '#22D3EE' }} />
          </GlassCard>
        </Col>
        <Col xs={24} sm={12} md={5}>
          <GlassCard>
            <Statistic title={<span className="text-white/70">总得分</span>} value={record.totalScore} suffix="分" valueStyle={{ color: '#fff' }} />
          </GlassCard>
        </Col>
        <Col xs={24} sm={12} md={5}>
          <GlassCard>
            <Statistic title={<span className="text-white/70">正确题数</span>} value={record.correctCount} valueStyle={{ color: '#34D399' }} />
          </GlassCard>
        </Col>
        <Col xs={24} sm={12} md={5}>
          <GlassCard>
            <Statistic title={<span className="text-white/70">总题数</span>} value={record.totalCount} valueStyle={{ color: '#fff' }} />
          </GlassCard>
        </Col>
        <Col xs={24} sm={12} md={4}>
          <GlassCard>
            <Statistic
              title={<span className="text-white/70">正确率</span>}
              value={record.totalCount > 0 ? ((record.correctCount / record.totalCount) * 100).toFixed(1) : 0}
              suffix="%"
              valueStyle={{ color: '#FBBF24' }}
            />
          </GlassCard>
        </Col>
      </Row>

      <Row gutter={[16, 16]} className="mb-6">
        <Col xs={24} lg={12}>
          <GlassCard title={<span className="text-white font-bold">题型正确率</span>}>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={typeChartData}>
                <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.1)" />
                <XAxis dataKey="type" stroke="rgba(255,255,255,0.5)" />
                <YAxis stroke="rgba(255,255,255,0.5)" />
                <Tooltip 
                  contentStyle={{ backgroundColor: 'rgba(0,0,0,0.8)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px' }}
                  itemStyle={{ color: '#fff' }}
                />
                <Bar dataKey="正确率" fill="#3b82f6" />
              </BarChart>
            </ResponsiveContainer>
          </GlassCard>
        </Col>
        <Col xs={24} lg={12}>
          <GlassCard title={<span className="text-white font-bold">答题结果分布</span>}>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={pieData}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={120}
                  dataKey="value"
                  stroke="none"
                >
                  {pieData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip 
                  contentStyle={{ backgroundColor: 'rgba(0,0,0,0.8)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px' }}
                  itemStyle={{ color: '#fff' }}
                />
              </PieChart>
            </ResponsiveContainer>
            <div className="flex justify-center mt-4">
              {pieData.map((item) => (
                <div key={item.name} className="flex items-center mx-4">
                  <div
                    className="w-4 h-4 rounded mr-2"
                    style={{ backgroundColor: item.color }}
                  />
                  <span className="text-white/80">{item.name}: {item.value}</span>
                </div>
              ))}
            </div>
          </GlassCard>
        </Col>
      </Row>

      <GlassCard title={<span className="text-white font-bold">答题详情</span>}>
        <Table
          columns={columns}
          dataSource={record.answers}
          rowKey="id"
          size="small"
          loading={loading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
        />
      </GlassCard>
    </div>
  );
};

export default RecordDetailPage;
