import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Row, Col, Statistic, Button, Table, App, DatePicker, Select, Space, Tag } from 'antd';
import {
  TeamOutlined,
  DatabaseOutlined,
  BookOutlined,
  CalendarOutlined,
  ReloadOutlined,
  ArrowRightOutlined
} from '@ant-design/icons';
import { adminAPI, quizAPI } from '../../services/api';
import { formatDateTime, parseUtcDateTime } from '../../utils/validation';
import type { Dayjs } from 'dayjs';
import {
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Tooltip as RechartsTooltip,
  Legend,
} from 'recharts';
import GlassCard from '../../components/common/GlassCard';

interface DashboardOverview {
  totalUsers: number;
  activeSubjectCount: number;
  questionCategoryStats: Array<{ category: string; count: number }>;
  taskStatusDistribution: {
    completed: number;
    ongoing: number;
    notStarted: number;
  };
}

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

interface ActiveTaskStat {
  taskId: string;
  taskName: string;
  subjectName: string;
  totalUsers: number;
  completedUsers: number;
  completionRate: number;
  passRate: number;
  excellentRate: number;
  startAt: string;
  endAt: string;
}

interface TaskStatRow extends ActiveTaskStat {
  status: '已完成' | '进行中' | '未开始';
}

const AdminDashboardPage = () => {
  const navigate = useNavigate();
  const { message } = App.useApp();
  const [overview, setOverview] = useState<DashboardOverview | null>(null);
  const [recentRecords, setRecentRecords] = useState<RecentRecord[]>([]);
  const [taskStats, setTaskStats] = useState<TaskStatRow[]>([]);
  const [taskStatsPagination, setTaskStatsPagination] = useState({
    page: 1,
    limit: 5,
    total: 0,
  });
  const [taskStatusFilter, setTaskStatusFilter] = useState<
    '' | 'completed' | 'ongoing' | 'notStarted'
  >('');
  const [endAtRange, setEndAtRange] = useState<[Dayjs | null, Dayjs | null] | null>(null);
  const [loading, setLoading] = useState(false);

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

  const buildTaskStatsParams = (page: number, status?: string, range?: [Dayjs | null, Dayjs | null] | null) => {
    const params: any = { page, limit: 5 };

    if (status === 'completed' || status === 'ongoing' || status === 'notStarted') {
      params.status = status;
    }

    const start = range?.[0] ?? null;
    const end = range?.[1] ?? null;
    if (start) params.endAtStart = start.startOf('day').toISOString();
    if (end) params.endAtEnd = end.endOf('day').toISOString();

    return params;
  };

  const fetchDashboardData = async () => {
    try {
      setLoading(true);
      const [overviewRes, recentRecordsRes, taskStatsRes] = await Promise.all([
        adminAPI.getDashboardOverview(),
        quizAPI.getAllRecords({ page: 1, limit: 10 }),
        adminAPI.getAllTaskStats(buildTaskStatsParams(1, taskStatusFilter, endAtRange)),
      ]);

      if (overviewRes.data) setOverview(overviewRes.data);
      if (Array.isArray((recentRecordsRes as any).data)) setRecentRecords((recentRecordsRes as any).data);
      if (taskStatsRes.data) {
        setTaskStats(taskStatsRes.data.list);
        setTaskStatsPagination({
          page: 1,
          limit: 5,
          total: taskStatsRes.data.total,
        });
      }
    } catch (error) {
      console.error('Failed to fetch dashboard data:', error);
      message.error('获取仪表盘数据失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchTaskStats = async (page: number) => {
    try {
      const res = await adminAPI.getAllTaskStats(
        buildTaskStatsParams(page, taskStatusFilter, endAtRange)
      );
      if (res.data) {
        setTaskStats(res.data.list);
        setTaskStatsPagination(prev => ({ ...prev, page, total: res.data.total }));
      }
    } catch (error) {
      console.error('Failed to fetch task stats:', error);
      message.error('获取任务统计失败');
    }
  };

  const handleTaskFilterChange = () => {
    fetchTaskStats(1);
  };

  useEffect(() => {
    handleTaskFilterChange();
  }, [taskStatusFilter, endAtRange]);

  const COLORS = ['#22D3EE', '#F472B6', '#A78BFA', '#34D399', '#FBBF24', '#60A5FA'];

  const recordColumns = [
    {
      title: '用户',
      dataIndex: 'userName',
      key: 'userName',
      render: (text: string, record: RecentRecord) => (
        <Space>
          <div className="w-8 h-8 rounded-full bg-cyan-500/20 flex items-center justify-center text-cyan-400 font-bold">
            {text.charAt(0)}
          </div>
          <div>
            <div className="font-medium text-white/90">{text}</div>
            <div className="text-xs text-white/50">{record.userPhone}</div>
          </div>
        </Space>
      ),
    },
    {
      title: '考试科目',
      dataIndex: 'subjectName',
      key: 'subjectName',
      render: (text: string) => <Tag color="blue" className="bg-blue-500/20 border-blue-500/30 text-blue-300">{text || '-'}</Tag>,
    },
    {
      title: '得分',
      key: 'score',
      render: (_: any, record: RecentRecord) => (
        <span className="font-bold text-emerald-400">
          {record.totalScore} <span className="text-xs text-white/40 font-normal">/ {record.totalCount}</span>
        </span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        let color = 'default';
        let bg = 'rgba(255,255,255,0.1)';
        if (status === '优秀') { color = '#34D399'; bg = 'rgba(52, 211, 153, 0.1)'; }
        if (status === '合格') { color = '#22D3EE'; bg = 'rgba(34, 211, 238, 0.1)'; }
        if (status === '不及格') { color = '#F87171'; bg = 'rgba(248, 113, 113, 0.1)'; }
        return (
          <span style={{ color, background: bg, padding: '4px 8px', borderRadius: '4px', fontSize: '12px' }}>
            {status}
          </span>
        );
      },
    },
    {
      title: '时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text: string) => <span className="text-white/60 text-xs">{formatDateTime(text)}</span>,
    },
  ];

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center mb-2">
        <div>
          <h2 className="text-2xl font-bold text-white mb-1">仪表盘</h2>
          <p className="text-white/50 text-sm">系统运行状态概览</p>
        </div>
        <Button 
          icon={<ReloadOutlined />} 
          onClick={fetchDashboardData} 
          loading={loading}
          type="primary"
          ghost
          className="border-white/20 text-white hover:bg-white/10"
        >
          刷新数据
        </Button>
      </div>

      {/* Top Stats Cards */}
      <Row gutter={[24, 24]}>
        <Col xs={24} sm={12} lg={6}>
          <GlassCard className="hover:scale-[1.02] transition-transform duration-300">
            <Statistic
              title={<span className="text-white/60">总用户数</span>}
              value={overview?.totalUsers || 0}
              prefix={<TeamOutlined className="text-cyan-400 mr-2" />}
              valueStyle={{ color: '#fff', fontWeight: 'bold' }}
            />
          </GlassCard>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <GlassCard className="hover:scale-[1.02] transition-transform duration-300">
            <Statistic
              title={<span className="text-white/60">活跃科目</span>}
              value={overview?.activeSubjectCount || 0}
              prefix={<BookOutlined className="text-purple-400 mr-2" />}
              valueStyle={{ color: '#fff', fontWeight: 'bold' }}
            />
          </GlassCard>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <GlassCard className="hover:scale-[1.02] transition-transform duration-300">
            <Statistic
              title={<span className="text-white/60">进行中任务</span>}
              value={overview?.taskStatusDistribution?.ongoing || 0}
              prefix={<CalendarOutlined className="text-emerald-400 mr-2" />}
              valueStyle={{ color: '#fff', fontWeight: 'bold' }}
            />
          </GlassCard>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <GlassCard className="hover:scale-[1.02] transition-transform duration-300">
            <Statistic
              title={<span className="text-white/60">题库总数</span>}
              value={overview?.questionCategoryStats?.reduce((acc, curr) => acc + curr.count, 0) || 0}
              prefix={<DatabaseOutlined className="text-rose-400 mr-2" />}
              valueStyle={{ color: '#fff', fontWeight: 'bold' }}
            />
          </GlassCard>
        </Col>
      </Row>

      <Row gutter={[24, 24]}>
        {/* Recent Activity */}
        <Col xs={24} lg={16}>
          <GlassCard 
            title={<span className="text-white font-bold text-lg">最近考试记录</span>}
            extra={<Button type="link" onClick={() => navigate('/admin/statistics')} className="text-cyan-400 hover:text-cyan-300 flex items-center gap-1">查看全部 <ArrowRightOutlined /></Button>}
            className="h-full"
            bodyStyle={{ padding: 0 }}
          >
            <Table
              dataSource={recentRecords}
              columns={recordColumns}
              rowKey="id"
              pagination={false}
              loading={loading}
              size="middle"
              className="bg-transparent"
            />
          </GlassCard>
        </Col>

        {/* Distribution Chart */}
        <Col xs={24} lg={8}>
          <GlassCard title={<span className="text-white font-bold text-lg">题目分类分布</span>} className="h-full">
            <div style={{ width: '100%', height: 300 }}>
              <ResponsiveContainer>
                <PieChart>
                  <Pie
                    data={overview?.questionCategoryStats || []}
                    cx="50%"
                    cy="50%"
                    innerRadius={60}
                    outerRadius={80}
                    paddingAngle={5}
                    dataKey="count"
                    nameKey="category"
                  >
                    {(overview?.questionCategoryStats || []).map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} stroke="rgba(0,0,0,0.2)" />
                    ))}
                  </Pie>
                  <RechartsTooltip 
                    contentStyle={{ 
                      backgroundColor: 'rgba(30, 41, 59, 0.9)', 
                      borderRadius: '8px', 
                      border: '1px solid rgba(255,255,255,0.1)',
                      color: '#fff'
                    }} 
                  />
                  <Legend verticalAlign="bottom" height={36} formatter={(value) => <span style={{ color: 'rgba(255,255,255,0.7)' }}>{value}</span>} />
                </PieChart>
              </ResponsiveContainer>
            </div>
          </GlassCard>
        </Col>
      </Row>
    </div>
  );
};

export default AdminDashboardPage;
