import React, { useState, useEffect } from 'react';
import { Card, Table, Tag, Button, Space, Spin, App, Typography } from 'antd';
import { EyeOutlined, BookOutlined, CalendarOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useUser } from '../contexts';
import { quizAPI } from '../services/api';
import { UserLayout } from '../layouts/UserLayout';
import { formatDateTime } from '../utils/validation';

const { Title, Text } = Typography;

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

export const UserTaskPage: React.FC = () => {
  const [records, setRecords] = useState<QuizRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();
  const { message } = App.useApp();
  const { user } = useUser();

  useEffect(() => {
    if (user) {
      fetchUserRecords();
    }
  }, [user]);

  const fetchUserRecords = async () => {
    try {
      setLoading(true);
      if (!user?.id) return;
      const response = await quizAPI.getUserRecords(user.id) as any;
      setRecords(response.data);
    } catch (error) {
      message.error('获取答题记录失败');
    } finally {
      setLoading(false);
    }
  };

  const viewResult = (recordId: string) => {
    navigate(`/result/${recordId}`);
  };

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

  const columns = [
    {
      title: '操作',
      key: 'action',
      width: 80,
      render: (record: QuizRecord) => (
        <Button
          type="link"
          size="small"
          icon={<EyeOutlined />}
          onClick={() => viewResult(record.id)}
          style={{ fontSize: '12px', padding: 0 }}
        >
          查看结果
        </Button>
      )
    },
    {
      title: '任务名称',
      dataIndex: 'taskName',
      key: 'taskName',
      width: 100,
      render: (text: string) => <Text strong style={{ fontSize: '12px' }}>{text || '-'}</Text>
    },
    {
      title: '考试科目',
      dataIndex: 'subjectName',
      key: 'subjectName',
      width: 90,
      render: (text: string) => (
        <Space size={4}>
          <BookOutlined style={{ fontSize: '12px' }} className="text-mars-600" />
          <Text style={{ fontSize: '12px' }}>{text || '-'}</Text>
        </Space>
      )
    },
    {
      title: '得分',
      dataIndex: 'totalScore',
      key: 'totalScore',
      width: 60,
      render: (score: number) => <Text strong style={{ fontSize: '12px' }}>{score}分</Text>
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 60,
      render: (status: string) => (
        <Tag color={getStatusColor(status)} style={{ fontSize: '11px' }}>
          {status}
        </Tag>
      )
    },
    {
      title: '正确题数',
      key: 'correctCount',
      width: 80,
      render: (record: QuizRecord) => (
        <Text style={{ fontSize: '12px' }}>
          {record.correctCount}/{record.totalCount}
        </Text>
      ),
    },
    {
      title: '答题时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 110,
      render: (date: string) => (
        <Space size={4}>
          <CalendarOutlined style={{ fontSize: '11px' }} className="text-gray-500" />
          <Text type="secondary" style={{ fontSize: '11px' }}>
            {formatDateTime(date)}
          </Text>
        </Space>
      )
    }
  ];

  if (loading) {
    return (
      <UserLayout>
        <div className="flex justify-center items-center h-full min-h-[500px]">
          <Spin size="large" />
        </div>
      </UserLayout>
    );
  }

  return (
    <UserLayout>
      <div className="container mx-auto px-2 max-w-md">

        <Table
          columns={columns}
          dataSource={records}
          rowKey="id"
          size="small"
          pagination={{
            pageSize: 5,
            showSizeChanger: false,
            showTotal: (total) => `共 ${total} 条`,
            size: 'small'
          }}
          locale={{
            emptyText: '暂无答题记录'
          }}
          scroll={{ x: 'max-content' }}
          className="mobile-table"
          style={{
            fontSize: '12px'
          }}
          rowClassName={() => 'mobile-table-row'}
        />

        <div className="mt-4 text-center">
          <Button
            type="default"
            size="large"
            onClick={() => navigate('/subjects')}
            icon={<BookOutlined />}
            className="px-6 h-10 text-sm hover:border-mars-500 hover:text-mars-500"
          >
            返回任务选择
          </Button>
        </div>
      </div>
    </UserLayout>
  );
};
