import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, Row, Col, Statistic, Button, Table, message, DatePicker, Select, Space } from 'antd';
import {
  TeamOutlined,
  DatabaseOutlined,
  BookOutlined,
  CalendarOutlined,
  ReloadOutlined,
} 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,
  Label,
} from 'recharts';

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 [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 [overviewResponse, recordsResponse, taskStatsResponse] =
        await Promise.all([
          adminAPI.getDashboardOverview(),
          fetchRecentRecords(),
          adminAPI.getAllTaskStats(buildTaskStatsParams(1, taskStatusFilter, endAtRange)),
        ]);

      setOverview(overviewResponse.data);
      setRecentRecords(recordsResponse);
      setTaskStats((taskStatsResponse as any).data || []);
      if ((taskStatsResponse as any).pagination) {
        setTaskStatsPagination({
          page: (taskStatsResponse as any).pagination.page,
          limit: (taskStatsResponse as any).pagination.limit,
          total: (taskStatsResponse as any).pagination.total,
        });
      }
    } catch (error: any) {
      message.error(error.message || '获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchTaskStats = async (
    page: number,
    next: { status?: '' | 'completed' | 'ongoing' | 'notStarted'; range?: [Dayjs | null, Dayjs | null] | null } = {},
  ) => {
    try {
      setLoading(true);
      const status = next.status ?? taskStatusFilter;
      const range = next.range ?? endAtRange;
      const response = (await adminAPI.getAllTaskStats(buildTaskStatsParams(page, status, range))) as any;
      setTaskStats(response.data || []);
      if (response.pagination) {
        setTaskStatsPagination({
          page: response.pagination.page,
          limit: response.pagination.limit,
          total: response.pagination.total,
        });
      }
    } catch (error: any) {
      message.error(error.message || '获取考试任务统计失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchRecentRecords = async () => {
    const response = await quizAPI.getAllRecords({ page: 1, limit: 10 }) as any;
    return response.data || [];
  };

  const totalQuestions =
    overview?.questionCategoryStats?.reduce((sum, item) => sum + (Number(item.count) || 0), 0) || 0;

  const totalTasks = overview
    ? Number(overview.taskStatusDistribution.completed || 0) +
      Number(overview.taskStatusDistribution.ongoing || 0) +
      Number(overview.taskStatusDistribution.notStarted || 0)
    : 0;

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

  const columns = [
    {
      title: '姓名',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '手机号',
      dataIndex: 'userPhone',
      key: 'userPhone',
    },
    {
      title: '得分',
      dataIndex: 'totalScore',
      key: 'totalScore',
      render: (score: number) => <span className="font-semibold text-mars-600">{score} 分</span>,
    },
    {
      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}-100 text-${color}-800`}>{status}</span>;
      },
    },
    {
      title: '正确率',
      key: 'correctRate',
      render: (_: any, record: RecentRecord) => {
        const rate = record.totalCount > 0 
          ? ((record.correctCount / record.totalCount) * 100).toFixed(1)
          : '0.0';
        return <span>{rate}%</span>;
      },
    },
    {
      title: '考试科目',
      dataIndex: 'subjectName',
      key: 'subjectName',
      render: (subjectName?: string) => subjectName || '',
    },
    {
      title: '考试人数',
      dataIndex: 'examCount',
      key: 'examCount',
      render: (examCount?: number) => examCount || '',
    },
    {
      title: '答题时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => formatDateTime(date),
    },
  ];

  const taskStatsColumns = [
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
    },
    {
      title: '任务名称',
      dataIndex: 'taskName',
      key: 'taskName',
    },
    {
      title: '科目',
      dataIndex: 'subjectName',
      key: 'subjectName',
    },
    {
      title: '指定考试人数',
      dataIndex: 'totalUsers',
      key: 'totalUsers',
    },
    {
      title: '考试进度',
      key: 'progress',
      render: (_: any, record: ActiveTaskStat) => {
        const now = new Date();
        const start = parseUtcDateTime(record.startAt) ?? new Date(record.startAt);
        const end = parseUtcDateTime(record.endAt) ?? new Date(record.endAt);

        const totalDuration = end.getTime() - start.getTime();
        const elapsedDuration = now.getTime() - start.getTime();
        const progress =
          totalDuration > 0
            ? Math.max(0, Math.min(100, Math.round((elapsedDuration / totalDuration) * 100)))
            : 0;

        return (
          <div className="flex items-center">
            <div className="w-32 h-4 bg-gray-200 rounded-full mr-2 overflow-hidden">
              <div
                className="h-full bg-mars-500 rounded-full transition-all duration-300"
                style={{ width: `${progress}%` }}
              ></div>
            </div>
            <span className="font-semibold text-mars-600">{progress}%</span>
          </div>
        );
      },
    },
    {
      title: '考试人数统计',
      key: 'statistics',
      render: (_: any, record: ActiveTaskStat) => {
        const total = record.totalUsers;
        const completed = record.completedUsers;

        const passedTotal = Math.round(completed * (record.passRate / 100));
        const excellentTotal = Math.round(completed * (record.excellentRate / 100));

        const incomplete = total - completed;
        const failed = completed - passedTotal;
        const passedOnly = passedTotal - excellentTotal;
        const excellent = excellentTotal;

        const pieData = [
          { name: '优秀', value: excellent, color: '#008C8C' },
          { name: '合格', value: passedOnly, color: '#00A3A3' },
          { name: '不及格', value: failed, color: '#ff4d4f' },
          { name: '未完成', value: incomplete, color: '#f0f0f0' },
        ];

        const filteredData = pieData.filter((item) => item.value > 0);
        const completionRate = total > 0 ? Math.round((completed / total) * 100) : 0;

        return (
          <div className="w-full h-20">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={filteredData}
                  cx="50%"
                  cy="50%"
                  innerRadius={25}
                  outerRadius={35}
                  paddingAngle={2}
                  dataKey="value"
                >
                  {filteredData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} stroke="none" />
                  ))}
                  <Label
                    value={`${completionRate}%`}
                    position="center"
                    className="text-sm font-bold fill-gray-700"
                  />
                </Pie>
                <RechartsTooltip
                  formatter={(value: any) => [`${value} 人`, '数量']}
                  contentStyle={{
                    borderRadius: '8px',
                    border: 'none',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                    fontSize: '12px',
                    padding: '8px',
                  }}
                />
                <Legend
                  layout="vertical"
                  verticalAlign="middle"
                  align="right"
                  iconType="circle"
                  iconSize={8}
                  wrapperStyle={{ fontSize: '12px' }}
                  formatter={(value: string, entry: any) => (
                    <span className="text-xs text-gray-600 ml-1">
                      {value} {entry.payload.value}
                    </span>
                  )}
                />
              </PieChart>
            </ResponsiveContainer>
          </div>
        );
      },
    },
  ];

  return (
    <div>
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold text-gray-800">管理仪表盘</h1>
        <Button 
          type="primary" 
          icon={<ReloadOutlined />}
          onClick={fetchDashboardData}
          loading={loading}
          className="bg-mars-500 hover:bg-mars-600"
        >
          刷新数据
        </Button>
      </div>

      {/* 统计卡片 */}
      <Row gutter={16} className="mb-8">
        <Col span={6}>
          <Card
            className="shadow-sm hover:shadow-md transition-shadow cursor-pointer"
            onClick={() => navigate('/admin/users')}
            styles={{ body: { padding: 16 } }}
          >
            <Statistic
              title="总用户数"
              value={overview?.totalUsers || 0}
              prefix={<TeamOutlined className="text-mars-400" />}
              valueStyle={{ color: '#008C8C' }}
            />
          </Card>
        </Col>

        <Col span={6}>
          <Card
            className="shadow-sm hover:shadow-md transition-shadow cursor-pointer"
            onClick={() => navigate('/admin/question-bank')}
            styles={{ body: { padding: 16 } }}
          >
            <Statistic
              title="题库统计"
              value={totalQuestions}
              prefix={<DatabaseOutlined className="text-mars-400" />}
              valueStyle={{ color: '#008C8C' }}
              suffix="题"
            />
          </Card>
        </Col>

        <Col span={6}>
          <Card
            className="shadow-sm hover:shadow-md transition-shadow cursor-pointer"
            onClick={() => navigate('/admin/subjects')}
            styles={{ body: { padding: 16 } }}
          >
            <Statistic
              title="考试科目"
              value={overview?.activeSubjectCount || 0}
              prefix={<BookOutlined className="text-mars-400" />}
              valueStyle={{ color: '#008C8C' }}
              suffix="个"
            />
          </Card>
        </Col>

        <Col span={6}>
          <Card
            className="shadow-sm hover:shadow-md transition-shadow cursor-pointer"
            onClick={() => navigate('/admin/exam-tasks')}
            styles={{ body: { padding: 16 } }}
          >
            <Statistic
              title="考试任务"
              value={totalTasks}
              prefix={<CalendarOutlined className="text-mars-400" />}
              valueStyle={{ color: '#008C8C' }}
              suffix="个"
            />
          </Card>
        </Col>
      </Row>

      <Card
        title="考试任务统计"
        className="mb-8 shadow-sm"
        extra={
          <Space>
            <Select
              style={{ width: 140 }}
              value={taskStatusFilter}
              onChange={(value) => {
                setTaskStatusFilter(value);
                fetchTaskStats(1, { status: value });
              }}
              options={[
                { value: '', label: '全部状态' },
                { value: 'completed', label: '已完成' },
                { value: 'ongoing', label: '进行中' },
                { value: 'notStarted', label: '未开始' },
              ]}
            />
            <DatePicker.RangePicker
              value={endAtRange}
              placeholder={['结束时间开始', '结束时间结束']}
              format="YYYY-MM-DD"
              onChange={(value) => {
                setEndAtRange(value);
                fetchTaskStats(1, { range: value });
              }}
              allowClear
            />
          </Space>
        }
      >
        <Table
          columns={taskStatsColumns}
          dataSource={taskStats}
          rowKey="taskId"
          loading={loading}
          size="small"
          pagination={{
            current: taskStatsPagination.page,
            pageSize: 5,
            total: taskStatsPagination.total,
            showSizeChanger: false,
            onChange: (page) => fetchTaskStats(page),
            size: 'small',
          }}
        />
      </Card>

      {/* 最近答题记录 */}
      <Card title="最近答题记录" className="shadow-sm">
        <Table
          columns={columns}
          dataSource={recentRecords}
          rowKey="id"
          loading={loading}
          pagination={false}
          size="small"
        />
      </Card>
    </div>
  );
};

export default AdminDashboardPage;
