import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Space, App, Popconfirm, Modal, Form, InputNumber, Card, Progress, Row, Col, Tag, Radio, Segmented } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import api from '../../services/api';
import { getCategoryColorHex } from '../../lib/categoryColors';
import { parseUtcDateTime } from '../../utils/validation';
import GlassCard from '../../components/common/GlassCard';

interface Question {
  id: string;
  content: string;
  type: string;
  options?: string[];
  answer: string | string[];
  analysis?: string;
  score: number;
  category: string;
}

interface QuizPreview {
  questions: Question[];
  totalScore: number;
  timeLimit: number;
}

interface ExamSubject {
  id: string;
  name: string;
  totalScore: number;
  timeLimitMinutes: number;
  typeRatios: Record<string, number>;
  categoryRatios: Record<string, number>;
  createdAt: string;
}

interface QuestionCategory {
  id: string;
  name: string;
}

const ExamSubjectPage = () => {
  const { message } = App.useApp();
  const [subjects, setSubjects] = useState<ExamSubject[]>([]);
  const [categories, setCategories] = useState<QuestionCategory[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingSubject, setEditingSubject] = useState<ExamSubject | null>(null);
  const [form] = Form.useForm();
  // 浏览考题相关状态
  const [previewVisible, setPreviewVisible] = useState(false);
  const [quizPreview, setQuizPreview] = useState<QuizPreview | null>(null);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [currentSubject, setCurrentSubject] = useState<ExamSubject | null>(null);
  // 引入状态管理来跟踪实时的比例配置
  const [configMode, setConfigMode] = useState<'ratio' | 'count'>('count');
  const [typeRatios, setTypeRatios] = useState<Record<string, number>>({
    single: 40,
    multiple: 30,
    judgment: 20,
    text: 10
  });
  const [categoryRatios, setCategoryRatios] = useState<Record<string, number>>({
    
  });

  const sumValues = (valuesMap: Record<string, number>) => Object.values(valuesMap).reduce((a, b) => a + b, 0);

  const isRatioMode = (valuesMap: Record<string, number>) => {
    const values = Object.values(valuesMap);
    if (values.length === 0) return false;
    if (values.some((v) => typeof v !== 'number' || Number.isNaN(v) || v < 0)) return false;
    if (values.some((v) => v > 100)) return false;
    const sum = values.reduce((a, b) => a + b, 0);
    return Math.abs(sum - 100) <= 0.01;
  };

  const ensureRatioSum100 = (valuesMap: Record<string, number>) => {
    const entries = Object.entries(valuesMap);
    if (entries.length === 0) return valuesMap;
    const result: Record<string, number> = {};
    for (const [k, v] of entries) result[k] = Math.max(0, Math.min(100, Math.round((Number(v) || 0) * 100) / 100));
    const keys = Object.keys(result);
    const lastKey = keys[keys.length - 1];
    const sumWithoutLast = keys.slice(0, -1).reduce((s, k) => s + (result[k] ?? 0), 0);
    result[lastKey] = Math.max(0, Math.min(100, Math.round((100 - sumWithoutLast) * 100) / 100));
    return result;
  };

  const convertCountsToRatios = (valuesMap: Record<string, number>) => {
    const entries = Object.entries(valuesMap);
    if (entries.length === 0) return valuesMap;
    const total = entries.reduce((s, [, v]) => s + Math.max(0, Number(v) || 0), 0);
    if (total <= 0) return ensureRatioSum100(Object.fromEntries(entries.map(([k]) => [k, 0])) as any);
    const ratios: Record<string, number> = {};
    for (const [k, v] of entries) {
      ratios[k] = Math.round(((Math.max(0, Number(v) || 0) / total) * 100) * 100) / 100;
    }
    return ensureRatioSum100(ratios);
  };

  const convertRatiosToCounts = (valuesMap: Record<string, number>) => {
    const result: Record<string, number> = {};
    for (const [k, v] of Object.entries(valuesMap)) {
      result[k] = Math.max(0, Math.round(Number(v) || 0));
    }
    return result;
  };

  // 题型配置
  const questionTypes = [
    { key: 'single', label: '单选题', color: '#52c41a' },
    { key: 'multiple', label: '多选题', color: '#faad14' },
    { key: 'judgment', label: '判断题', color: '#ff4d4f' },
    { key: 'text', label: '文字题', color: '#1890ff' },
  ];

  const fetchSubjects = async () => {
    setLoading(true);
    try {
      const [subjectsRes, categoriesRes] = await Promise.all([
        api.get('/admin/subjects'),
        api.get('/question-categories')
      ]);
      setSubjects(subjectsRes.data);
      setCategories(categoriesRes.data);
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

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

  const handleCreate = () => {
    if (categories.length === 0) {
      message.warning('题目类别加载中，请稍后再试');
      return;
    }
    setEditingSubject(null);
    form.resetFields();
    // 设置默认值
    const defaultTypeRatios = { single: 4, multiple: 3, judgment: 2, text: 1 };
    const total = sumValues(defaultTypeRatios);
    const preferredCategory =
      categories.find((c) => c.name !== '通用')?.name ?? categories[0]?.name;
    const defaultCategoryRatios: Record<string, number> = preferredCategory
      ? { [preferredCategory]: total }
      : {};
    
    // 初始化状态
    setConfigMode('count');
    setTypeRatios(defaultTypeRatios);
    setCategoryRatios(defaultCategoryRatios);
    
    form.setFieldsValue({
      typeRatios: defaultTypeRatios,
      categoryRatios: defaultCategoryRatios,
      totalScore: 100,
      timeLimitMinutes: 60,
    });
    setModalVisible(true);
  };

  const handleEdit = (subject: ExamSubject) => {
    setEditingSubject(subject);
    
    // 初始化状态，确保所有类别都有比重值
    const initialTypeRatios = subject.typeRatios || { single: 40, multiple: 30, judgment: 20, text: 10 };
    
    // 初始化类别比重，确保所有类别都有值
    const initialCategoryRatios: Record<string, number> = subject.categoryRatios || {};
    
    // 确保状态与表单值正确同步
    const inferredMode = isRatioMode(initialTypeRatios) && isRatioMode(initialCategoryRatios) ? 'ratio' : 'count';
    setConfigMode(inferredMode);
    setTypeRatios(initialTypeRatios);
    setCategoryRatios(initialCategoryRatios);
    
    form.setFieldsValue({
      name: subject.name,
      totalScore: subject.totalScore,
      timeLimitMinutes: subject.timeLimitMinutes,
      typeRatios: initialTypeRatios,
      categoryRatios: initialCategoryRatios,
    });
    setModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/admin/subjects/${id}`);
      message.success('删除成功');
      fetchSubjects();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleModalOk = async () => {
    try {
      const typeTotal = sumValues(typeRatios);
      const categoryTotal = sumValues(categoryRatios);

      if (configMode === 'ratio') {
        console.log('题型比重总和(状态):', typeTotal);
        if (Math.abs(typeTotal - 100) > 0.01) {
          message.error('题型比重总和必须为100%');
          return;
        }

        console.log('类别比重总和(状态):', categoryTotal);
        if (Math.abs(categoryTotal - 100) > 0.01) {
          message.error('题目类别比重总和必须为100%');
          return;
        }
      } else {
        const typeValues = Object.values(typeRatios);
        const categoryValues = Object.values(categoryRatios);
        if (typeValues.length === 0 || categoryValues.length === 0) {
          message.error('题型数量与题目类别数量不能为空');
          return;
        }
        if (typeValues.some((v) => typeof v !== 'number' || Number.isNaN(v) || v < 0 || !Number.isInteger(v))) {
          message.error('题型数量必须为非负整数');
          return;
        }
        if (categoryValues.some((v) => typeof v !== 'number' || Number.isNaN(v) || v < 0 || !Number.isInteger(v))) {
          message.error('题目类别数量必须为非负整数');
          return;
        }
        if (!typeValues.some((v) => v > 0) || !categoryValues.some((v) => v > 0)) {
          message.error('题型数量与题目类别数量至少需要一个大于0的配置');
          return;
        }
        if (typeTotal !== categoryTotal) {
          message.error('题型数量总和必须等于题目类别数量总和');
          return;
        }
      }

      // 然后才获取表单值，确保表单验证通过
      const values = await form.validateFields();
      
      // 确保表单值与状态同步
      values.typeRatios = typeRatios;
      values.categoryRatios = categoryRatios;
      
      console.log('最终提交的表单值:', values);
      
      if (editingSubject) {
        await api.put(`/admin/subjects/${editingSubject.id}`, values);
        message.success('更新成功');
      } else {
        await api.post('/admin/subjects', values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchSubjects();
    } catch (error) {
      message.error('操作失败');
      console.error('操作失败:', error);
    }
  };

  const handleConfigModeChange = (nextMode: 'ratio' | 'count') => {
    if (nextMode === configMode) return;

    let nextTypeRatios = typeRatios;
    let nextCategoryRatios = categoryRatios;
    if (nextMode === 'count') {
      nextTypeRatios = convertRatiosToCounts(typeRatios);
      nextCategoryRatios = convertRatiosToCounts(categoryRatios);
    } else {
      nextTypeRatios = convertCountsToRatios(typeRatios);
      nextCategoryRatios = convertCountsToRatios(categoryRatios);
    }

    setConfigMode(nextMode);
    setTypeRatios(nextTypeRatios);
    setCategoryRatios(nextCategoryRatios);
    form.setFieldsValue({ typeRatios: nextTypeRatios, categoryRatios: nextCategoryRatios });
  };

  const handleTypeRatioChange = (type: string, value: number) => {
    const newRatios = { ...typeRatios, [type]: value };
    setTypeRatios(newRatios);
    form.setFieldsValue({ typeRatios: newRatios });
  };

  const handleCategoryRatioChange = (category: string, value: number) => {
    const newRatios = { ...categoryRatios, [category]: value };
    console.log('修改类别比重:', category, value, '新的类别比重:', newRatios);
    console.log('类别比重总和:', Object.values(newRatios).reduce((sum: number, val) => sum + val, 0));
    setCategoryRatios(newRatios);
    form.setFieldsValue({ categoryRatios: newRatios });
  };

  // 浏览考题处理函数
  const handleBrowseQuestions = async (subject: ExamSubject) => {
    try {
      setPreviewLoading(true);
      setCurrentSubject(subject);
      
      // 调用生成试卷API获取随机题目
      const response = await api.post('/quiz/generate', {
        userId: 'admin-preview', // 使用临时用户ID
        subjectId: subject.id
      });
      
      setQuizPreview(response.data);
      setPreviewVisible(true);
    } catch (error) {
      message.error('生成预览题目失败');
      console.error('生成预览题目失败:', error);
    } finally {
      setPreviewLoading(false);
    }
  };

  const columns = [
    {
      title: '科目名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '总分',
      dataIndex: 'totalScore',
      key: 'totalScore',
      render: (score: number) => `${score} 分`,
    },
    {
      title: '答题时间',
      dataIndex: 'timeLimitMinutes',
      key: 'timeLimitMinutes',
      render: (minutes: number) => `${minutes} 分钟`,
    },
    {title: '题型分布',
      dataIndex: 'typeRatios',
      key: 'typeRatios',
      render: (ratios: Record<string, number>) => {
        const ratioMode = isRatioMode(ratios || {});
        const total = sumValues(ratios || {});
        return (
          <div className="p-3 bg-white/5 rounded-lg border border-white/10 shadow-sm">
            <div className="w-full bg-white/10 rounded-full h-4 flex mb-3 overflow-hidden">
              {ratios && Object.entries(ratios).map(([type, value]) => {
                const typeConfig = questionTypes.find(t => t.key === type);
                const widthPercent = ratioMode ? value : (total > 0 ? (value / total) * 100 : 0);
                return (
                  <div
                    key={type}
                    className="h-full"
                    style={{
                      width: `${widthPercent}%`,
                      backgroundColor: typeConfig?.color || '#1890ff'
                    }}
                  ></div>
                );
              })}
            </div>
            <div className="space-y-1">
              {ratios && Object.entries(ratios).map(([type, value]) => {
                const typeConfig = questionTypes.find(t => t.key === type);
                const percent = ratioMode ? value : (total > 0 ? Math.round((value / total) * 1000) / 10 : 0);
                return (
                  <div key={type} className="flex items-center text-sm">
                    <span
                      className="inline-block w-3 h-3 mr-2 rounded-full"
                      style={{ backgroundColor: typeConfig?.color || '#1890ff' }}
                    ></span>
                    <span className="flex-1 text-white/70">{typeConfig?.label || type}</span>
                    <span className="font-medium text-white/90">{ratioMode ? `${value}%` : `${value}题（${percent}%）`}</span>
                  </div>
                );
              })}
            </div>
          </div>
        );
      },
    },
    {title: '题目类别分布',
      dataIndex: 'categoryRatios',
      key: 'categoryRatios',
      render: (ratios: Record<string, number>) => {
        const ratioMode = isRatioMode(ratios || {});
        const knownCategories = new Set(categories.map((c) => c.name));
        const entries = ratios
          ? Object.entries(ratios).filter(([k]) => knownCategories.size === 0 || knownCategories.has(k))
          : [];
        const total = entries.reduce((s, [, v]) => s + (Number(v) || 0), 0);
        return (
          <div className="p-3 bg-white/5 rounded-lg border border-white/10 shadow-sm">
            <div className="w-full bg-white/10 rounded-full h-4 flex mb-3 overflow-hidden">
              {entries.map(([category, value]) => (
                <div 
                  key={category} 
                  className="h-full" 
                  style={{ 
                    width: `${ratioMode ? value : (total > 0 ? (value / total) * 100 : 0)}%`,
                    backgroundColor: getCategoryColorHex(category)
                  }}
                ></div>
              ))}
            </div>
            <div className="space-y-1">
              {entries.map(([category, value]) => {
                const percent = ratioMode ? value : (total > 0 ? Math.round((value / total) * 1000) / 10 : 0);
                return (
                  <div key={category} className="flex items-center text-sm">
                    <span
                      className="inline-block w-3 h-3 mr-2 rounded-full"
                      style={{ backgroundColor: getCategoryColorHex(category) }}
                    ></span>
                    <span className="flex-1 text-white/70">{category}</span>
                    <span className="font-medium text-white/90">{ratioMode ? `${value}%` : `${value}题（${percent}%）`}</span>
                  </div>
                );
              })}
            </div>
          </div>
        );
      },
    },
    {title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text: string) => {
        const date = parseUtcDateTime(text) ?? new Date(text);
        if (Number.isNaN(date.getTime())) return text;
        return (
          <div>
            <div>{date.toLocaleDateString()}</div>
            <div className="text-sm text-white/40">{date.toLocaleTimeString()}</div>
          </div>
        );
      },
    },
    {title: '操作',
      key: 'action',
      width: 100,
      align: 'left' as const,
      render: (_: any, record: ExamSubject) => (
        <div className="space-y-2">
          <Button
            type="text"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="text"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleBrowseQuestions(record)}
          >
            浏览考题
          </Button>
          <Popconfirm
            title="确定删除该科目吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="text" danger size="small" icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  return (
    <GlassCard>
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold text-white">考试科目管理</h1>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
          新增科目
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={subjects}
        rowKey="id"
        size="small"
        loading={loading}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
          size: 'small',
        }}
      />

      {/* 编辑/新增科目模态框 */}
      <Modal
        title={editingSubject ? '编辑科目' : '新增科目'}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        width={800}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="科目名称"
            rules={[{ required: true, message: '请输入科目名称' }]}
          >
            <Input placeholder="请输入科目名称" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="totalScore"
                label="试卷总分"
                rules={[{ required: true, message: '请输入试卷总分' }]}
              >
                <InputNumber 
                  min={1} 
                  max={200} 
                  placeholder="请输入总分" 
                  style={{ width: '100%' }} 
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="timeLimitMinutes"
                label="答题时间（分钟）"
                rules={[{ required: true, message: '请输入答题时间' }]}
              >
                <InputNumber 
                  min={1} 
                  max={180} 
                  placeholder="请输入时间" 
                  style={{ width: '100%' }} 
                />
              </Form.Item>
            </Col>
          </Row>

          <Card size="small" className="mb-4">
            <div className="flex items-center justify-between">
              <span className="font-medium">配置模式</span>
              <Radio.Group
                value={configMode}
                onChange={(e) => handleConfigModeChange(e.target.value)}
                options={[
                  { label: '比例(%)', value: 'ratio' },
                  { label: '数量(题)', value: 'count' },
                ]}
                optionType="button"
                buttonStyle="solid"
              />
            </div>
          </Card>

          <Card 
            size="small" 
            title={
              <div className="flex items-center justify-between">
                <span>{configMode === 'ratio' ? '题型比重配置' : '题型数量配置'}</span>
                <span className={`text-sm ${
                  configMode === 'ratio'
                    ? (Math.abs(sumValues(typeRatios) - 100) <= 0.01 ? 'text-green-600' : 'text-red-600')
                    : (sumValues(typeRatios) > 0 ? 'text-green-600' : 'text-red-600')
                }`}>
                  总计：{sumValues(typeRatios)}{configMode === 'ratio' ? '%' : '题'}
                </span>
              </div>
            } 
            className="mb-4"
          >
            <Form.Item name="typeRatios" noStyle>
              <div className="space-y-4">
                {questionTypes.map((type) => {
                  const value = typeRatios[type.key] || 0;
                  const total = sumValues(typeRatios);
                  const percent = configMode === 'ratio' ? value : (total > 0 ? Math.round((value / total) * 1000) / 10 : 0);
                  return (
                    <div key={type.key}>
                      <div className="flex items-center justify-between mb-2">
                        <span className="font-medium">{type.label}</span>
                        <span className="text-blue-600 font-bold">{configMode === 'ratio' ? `${value}%` : `${value}题`}</span>
                      </div>
                      <div className="flex items-center space-x-4">
                        <InputNumber
                          min={0}
                          max={configMode === 'ratio' ? 100 : 200}
                          precision={configMode === 'ratio' ? 2 : 0}
                          value={value}
                          onChange={(nextValue) => handleTypeRatioChange(type.key, nextValue || 0)}
                          style={{ width: 100 }}
                        />
                        <div style={{ flex: 1 }}>
                          <Progress 
                            percent={percent}
                            strokeColor={type.color}
                            showInfo={false}
                            size="small"
                          />
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </Form.Item>
          </Card>

          <Card 
            size="small" 
            title={
              <div className="flex items-center justify-between">
                <span>{configMode === 'ratio' ? '题目类别比重配置' : '题目类别数量配置'}</span>
                <span className={`text-sm ${
                  configMode === 'ratio'
                    ? (Math.abs(sumValues(categoryRatios) - 100) <= 0.01 ? 'text-green-600' : 'text-red-600')
                    : (sumValues(categoryRatios) === sumValues(typeRatios) && sumValues(categoryRatios) > 0 ? 'text-green-600' : 'text-red-600')
                }`}>
                  总计：{sumValues(categoryRatios)}{configMode === 'ratio' ? '%' : '题'}
                </span>
              </div>
            }
          >
            <Form.Item name="categoryRatios" noStyle>
              <div className="space-y-4">
                {categories.map((category) => {
                  const value = categoryRatios[category.name] || 0;
                  const total = sumValues(categoryRatios);
                  const percent = configMode === 'ratio' ? value : (total > 0 ? Math.round((value / total) * 1000) / 10 : 0);
                  return (
                    <div key={category.id}>
                      <div className="flex items-center justify-between mb-2">
                        <span className="font-medium">{category.name}</span>
                        <span className="text-blue-600 font-bold">{configMode === 'ratio' ? `${value}%` : `${value}题`}</span>
                      </div>
                      <div className="flex items-center space-x-4">
                        <InputNumber
                          min={0}
                          max={configMode === 'ratio' ? 100 : 200}
                          precision={configMode === 'ratio' ? 2 : 0}
                          value={value}
                          onChange={(nextValue) => handleCategoryRatioChange(category.name, nextValue || 0)}
                          style={{ width: 100 }}
                        />
                        <div style={{ flex: 1 }}>
                          <Progress 
                            percent={percent}
                            strokeColor="#1890ff"
                            showInfo={false}
                            size="small"
                          />
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </Form.Item>
          </Card>
        </Form>
      </Modal>

      {/* 浏览考题模态框 */}
      <Modal
        title={`${currentSubject?.name || ''} - 随机考题预览`}
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        width={900}
        footer={null}
        bodyStyle={{ maxHeight: '70vh', overflowY: 'auto' }}
      >
        {previewLoading ? (
          <div className="text-center py-10">
            <div className="ant-spin ant-spin-lg"></div>
            <p className="mt-4">正在生成随机考题...</p>
          </div>
        ) : quizPreview ? (
          <div>
            <Card size="small" className="mb-4">
              <div className="flex justify-between">
                <div>
                  <span className="font-medium mr-4">总分：</span>
                  <span>{quizPreview.totalScore} 分</span>
                </div>
                <div>
                  <span className="font-medium mr-4">时间限制：</span>
                  <span>{quizPreview.timeLimit} 分钟</span>
                </div>
                <div>
                  <span className="font-medium mr-4">题目数量：</span>
                  <span>{quizPreview.questions.length} 道</span>
                </div>
              </div>
            </Card>
            
            <div className="space-y-4">
              {quizPreview.questions.map((question, index) => (
                <Card key={question.id} className="shadow-sm">
                  <div className="flex justify-between items-start mb-3">
                    <h4 className="font-bold">
                      第 {index + 1} 题（{question.score} 分）
                      <span className="ml-2 text-blue-600 font-normal">
                        {question.type === 'single' ? '单选题' : 
                         question.type === 'multiple' ? '多选题' : 
                         question.type === 'judgment' ? '判断题' : '文字题'}
                      </span>
                    </h4>
                    <span className="text-gray-500 text-sm">{question.category}</span>
                  </div>
                  
                  <div className="mb-3">{question.content}</div>
                  
                  {question.options && question.options.length > 0 && (
                    <div className="mb-3">
                      {question.options.map((option, optIndex) => (
                        <div key={optIndex} className="mb-2">
                          <label className="flex items-center">
                            <span className="inline-block w-6 h-6 mr-2 text-center border border-gray-300 rounded">
                              {String.fromCharCode(65 + optIndex)}
                            </span>
                            <span>{option}</span>
                          </label>
                        </div>
                      ))}
                    </div>
                  )}
                  
                  <div className="mt-3">
                    <span className="font-medium mr-2">参考答案：</span>
                    <span className="text-green-600">
                      {Array.isArray(question.answer) ? 
                        // 多选题：直接拼接答案，不需要转换
                        question.answer.join(', ') :
                        question.type === 'judgment' ? (() => {
                          const v = String(question.answer ?? '').trim();
                          if (['A', 'T', 'true', 'True', 'TRUE', '1', '正确', '对', '是'].includes(v)) return '正确';
                          if (['B', 'F', 'false', 'False', 'FALSE', '0', '错误', '错', '否', '不是'].includes(v)) return '错误';
                          return v;
                        })() :
                          // 单选题：直接显示答案，不需要转换
                          question.answer}
                    </span>
                  </div>

                  <div className="mt-3">
                    <Tag color="blue">解析</Tag>
                    <span className="text-gray-300 whitespace-pre-wrap">{question.analysis || ''}</span>
                  </div>
                </Card>
              ))}
            </div>
          </div>
        ) : (
          <div className="text-center py-10 text-gray-400">
            暂无考题数据
          </div>
        )}
      </Modal>
    </GlassCard>
  );
};

export default ExamSubjectPage;
