import { useState, useEffect } from 'react';
import { Row, Col, Statistic, Table, DatePicker, Button, App, Tabs, Select } from 'antd';
import { Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import api, { adminAPI, quizAPI } from '../../services/api';
import { formatDateTime } from '../../utils/validation';
import GlassCard from '../../components/common/GlassCard';

const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
const { Option } = Select;

interface Statistics {
  totalUsers: number;
  totalRecords: number;
  averageScore: number;
  typeStats: Array<{ type: string; total: number; correct: number; correctRate: number }>;
}

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

interface UserStats {
  userId: string;
  userName: string;
  totalRecords: number;
  averageScore: number;
  highestScore: number;
  lowestScore: number;
}

interface SubjectStats {
  subjectId: string;
  subjectName: string;
  totalRecords: number;
  averageScore: number;
  averageCorrectRate: number;
}

interface TaskStats {
  taskId: string;
  taskName: string;
  totalRecords: number;
  averageScore: number;
  completionRate: number;
}

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 StatisticsPage = () => {
  const { message } = App.useApp();
  const [statistics, setStatistics] = useState<Statistics | null>(null);
  const [records, setRecords] = useState<QuizRecord[]>([]);
  const [userStats, setUserStats] = useState<UserStats[]>([]);
  const [subjectStats, setSubjectStats] = useState<SubjectStats[]>([]);
  const [taskStats, setTaskStats] = useState<TaskStats[]>([]);
  const [loading, setLoading] = useState(false);
  const [dateRange, setDateRange] = useState<any>(null);
  const [activeTab, setActiveTab] = useState('overview');
  const [selectedSubject, setSelectedSubject] = useState<string>('');
  const [selectedTask, setSelectedTask] = useState<string>('');
  const [subjects, setSubjects] = useState<any[]>([]);
  const [tasks, setTasks] = useState<any[]>([]);

  useEffect(() => {
    fetchInitialData();
  }, []);

  const fetchInitialData = async () => {
    await Promise.all([
      fetchStatistics(),
      fetchRecords(),
      fetchUserStats(),
      fetchSubjectStats(),
      fetchTaskStats(),
      fetchSubjects(),
      fetchTasks(),
    ]);
  };

  const fetchStatistics = async () => {
    try {
      setLoading(true);
      const response = await adminAPI.getStatistics();
      setStatistics(response.data);
    } catch (error: any) {
      message.error(error.message || '获取统计数据失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchRecords = async () => {
    try {
      const response = await quizAPI.getAllRecords({ page: 1, limit: 100 }) as any;
      setRecords(response.data || []);
    } catch (error) {
      console.error('获取答题记录失败:', error);
    }
  };

  const fetchUserStats = async () => {
    try {
      const response = await adminAPI.getUserStats() as any;
      setUserStats(response.data || []);
    } catch (error) {
      console.error('获取用户统计失败:', error);
    }
  };

  const fetchSubjectStats = async () => {
    try {
      const response = await adminAPI.getSubjectStats() as any;
      setSubjectStats(response.data || []);
    } catch (error) {
      console.error('获取科目统计失败:', error);
    }
  };

  const fetchTaskStats = async () => {
    try {
      const response = await adminAPI.getTaskStats() as any;
      setTaskStats(response.data || []);
    } catch (error) {
      console.error('获取任务统计失败:', error);
    }
  };

  const fetchSubjects = async () => {
    try {
      const response = await api.get('/exam-subjects') as any;
      setSubjects(response.data || []);
    } catch (error) {
      console.error('获取科目列表失败:', error);
    }
  };

  const fetchTasks = async () => {
    try {
      const response = await api.get('/exam-tasks') as any;
      setTasks(response.data || []);
    } catch (error) {
      console.error('获取任务列表失败:', error);
    }
  };

  const handleDateRangeChange = (dates: any) => {
    setDateRange(dates);
    // 这里可以添加根据日期范围筛选数据的逻辑
  };

  const exportData = () => {
    const csvContent = [
      ['姓名', '手机号', '科目', '任务', '得分', '正确数', '总题数', '答题时间'],
      ...records.map(record => [
        record.userName,
        record.userPhone,
        record.subjectName || '',
        record.taskName || '',
        record.totalScore,
        record.correctCount,
        record.totalCount,
        formatDateTime(record.createdAt)
      ])
    ].map(row => row.join(',')).join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `答题记录_${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
    window.URL.revokeObjectURL(url);
    message.success('数据导出成功');
  };

  const scoreDistribution = [
    { range: '不及格', count: records.filter(r => r.status === '不及格').length },
    { range: '合格', count: records.filter(r => r.status === '合格').length },
    { range: '优秀', count: records.filter(r => r.status === '优秀').length },
  ].filter(item => item.count > 0);

  const overviewColumns = [
    { title: '姓名', dataIndex: 'userName', key: 'userName' },
    { title: '手机号', dataIndex: 'userPhone', key: 'userPhone' },
    { title: '科目', dataIndex: 'subjectName', key: 'subjectName' },
    { title: '任务', dataIndex: 'taskName', key: 'taskName' },
    { 
      title: '状态', 
      dataIndex: 'status', 
      key: 'status',
      render: (status: string) => {
        const color = getStatusColor(status);
        return <span className={`px-2 py-1 rounded text-xs font-medium bg-${color}-500/20 text-${color}-300`}>{status}</span>;
      },
    },
    { title: '得分', dataIndex: 'totalScore', key: 'totalScore', render: (score: number) => <span className="font-semibold text-blue-400">{score} 分</span> },
    { title: '正确率', key: 'correctRate', render: (record: QuizRecord) => {
      const rate = ((record.correctCount / record.totalCount) * 100).toFixed(1);
      return <span>{rate}%</span>;
    }},
    { title: '答题时间', dataIndex: 'createdAt', key: 'createdAt', render: (date: string) => formatDateTime(date) },
  ];

  const userStatsColumns = [
    { title: '用户姓名', dataIndex: 'userName', key: 'userName' },
    { title: '答题次数', dataIndex: 'totalRecords', key: 'totalRecords' },
    { title: '平均分', dataIndex: 'averageScore', key: 'averageScore', render: (score: number) => `${score.toFixed(1)} 分` },
    { title: '最高分', dataIndex: 'highestScore', key: 'highestScore', render: (score: number) => `${score} 分` },
    { title: '最低分', dataIndex: 'lowestScore', key: 'lowestScore', render: (score: number) => `${score} 分` },
  ];

  const subjectStatsColumns = [
    { title: '科目名称', dataIndex: 'subjectName', key: 'subjectName' },
    { title: '答题次数', dataIndex: 'totalRecords', key: 'totalRecords' },
    { title: '平均分', dataIndex: 'averageScore', key: 'averageScore', render: (score: number) => `${score.toFixed(1)} 分` },
    { title: '平均正确率', dataIndex: 'averageCorrectRate', key: 'averageCorrectRate', render: (rate: number) => `${rate.toFixed(1)}%` },
  ];

  const taskStatsColumns = [
    { title: '任务名称', dataIndex: 'taskName', key: 'taskName' },
    { title: '答题次数', dataIndex: 'totalRecords', key: 'totalRecords' },
    { title: '平均分', dataIndex: 'averageScore', key: 'averageScore', render: (score: number) => `${score.toFixed(1)} 分` },
    { title: '完成率', dataIndex: 'completionRate', key: 'completionRate', render: (rate: number) => `${rate.toFixed(1)}%` },
  ];

  return (
    <GlassCard>
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold text-white">数据统计分析</h1>
        <div className="space-x-4">
          <RangePicker onChange={handleDateRangeChange} />
          <Button type="primary" onClick={exportData}>
            导出数据
          </Button>
        </div>
      </div>

      {/* 概览统计 */}
      <Row gutter={16} className="mb-8">
        <Col span={6}>
          <div className="bg-white/5 p-4 rounded-lg">
            <Statistic
              title={<span className="text-white/70">总用户数</span>}
              value={statistics?.totalUsers || 0}
              valueStyle={{ color: '#1890ff' }}
            />
          </div>
        </Col>
        <Col span={6}>
          <div className="bg-white/5 p-4 rounded-lg">
            <Statistic
              title={<span className="text-white/70">总答题数</span>}
              value={statistics?.totalRecords || 0}
              valueStyle={{ color: '#52c41a' }}
            />
          </div>
        </Col>
        <Col span={6}>
          <div className="bg-white/5 p-4 rounded-lg">
            <Statistic
              title={<span className="text-white/70">平均分</span>}
              value={statistics?.averageScore || 0}
              precision={1}
              valueStyle={{ color: '#faad14' }}
              suffix="分"
            />
          </div>
        </Col>
        <Col span={6}>
          <div className="bg-white/5 p-4 rounded-lg">
            <Statistic
              title={<span className="text-white/70">活跃率</span>}
              value={statistics?.totalUsers ? ((statistics.totalRecords / statistics.totalUsers) * 100).toFixed(1) : 0}
              precision={1}
              valueStyle={{ color: '#f5222d' }}
              suffix="%"
            />
          </div>
        </Col>
      </Row>

      <Tabs activeKey={activeTab} onChange={setActiveTab} className="text-white">
        <TabPane tab="总体概览" key="overview">
          {/* 图表 */}
          <Row gutter={16} className="mb-8">
            <Col span={24}>
              <div className="bg-white/5 p-6 rounded-lg mb-6">
                <h3 className="text-lg font-medium text-white mb-4">分数分布</h3>
                <ResponsiveContainer width="100%" height={300}>
                  <PieChart>
                    <Pie
                      data={scoreDistribution}
                      cx="50%"
                      cy="50%"
                      labelLine={false}
                      label={({ name, percent }: any) => `${name} ${(percent * 100).toFixed(0)}%`}
                      outerRadius={80}
                      fill="#8884d8"
                      dataKey="count"
                    >
                      {scoreDistribution.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <Tooltip 
                      contentStyle={{ backgroundColor: 'rgba(0,0,0,0.8)', border: 'none', borderRadius: '8px', color: '#fff' }}
                    />
                  </PieChart>
                </ResponsiveContainer>
              </div>
            </Col>
          </Row>

          {/* 详细记录 */}
          <div className="bg-white/5 p-6 rounded-lg">
            <h3 className="text-lg font-medium text-white mb-4">答题记录明细</h3>
            <Table
              className="bg-transparent"
              columns={overviewColumns}
              dataSource={records}
              rowKey="id"
              size="small"
              loading={loading}
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条`,
                size: 'small',
              }}
            />
          </div>
        </TabPane>

        <TabPane tab="用户统计" key="users">
          <div className="bg-white/5 p-6 rounded-lg">
            <h3 className="text-lg font-medium text-white mb-4">用户答题统计</h3>
            <Table
              className="bg-transparent"
              columns={userStatsColumns}
              dataSource={userStats}
              rowKey="userId"
              size="small"
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条`,
                size: 'small',
              }}
            />
          </div>
        </TabPane>

        <TabPane tab="科目统计" key="subjects">
          <div className="bg-white/5 p-6 rounded-lg">
            <h3 className="text-lg font-medium text-white mb-4">科目答题统计</h3>
            <Table
              className="bg-transparent"
              columns={subjectStatsColumns}
              dataSource={subjectStats}
              rowKey="subjectId"
              size="small"
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条`,
                size: 'small',
              }}
            />
          </div>
        </TabPane>

        <TabPane tab="任务统计" key="tasks">
          <div className="bg-white/5 p-6 rounded-lg">
            <h3 className="text-lg font-medium text-white mb-4">考试任务统计</h3>
            <Table
              className="bg-transparent"
              columns={taskStatsColumns}
              dataSource={taskStats}
              rowKey="taskId"
              size="small"
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条`,
                size: 'small',
              }}
            />
          </div>
        </TabPane>
      </Tabs>
    </GlassCard>
  );
};

export default StatisticsPage;
