import { useState, useEffect } from 'react';
import { Form, InputNumber, Button, Row, Col, Progress, App } from 'antd';
import { adminAPI } from '../../services/api';
import GlassCard from '../../components/common/GlassCard';

interface QuizConfig {
  singleRatio: number;
  multipleRatio: number;
  judgmentRatio: number;
  textRatio: number;
  totalScore: number;
}

const QuizConfigPage = () => {
  const [form] = Form.useForm();
  const { message } = App.useApp();
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  // 使用state来跟踪实时配置值
  const [configValues, setConfigValues] = useState<QuizConfig>({
    singleRatio: 40,
    multipleRatio: 30,
    judgmentRatio: 20,
    textRatio: 10,
    totalScore: 100
  });

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

  const fetchConfig = async () => {
    try {
      setLoading(true);
      const response = await adminAPI.getQuizConfig();
      const config = response.data;
      form.setFieldsValue(config);
      setConfigValues(config); // 更新state
    } catch (error: any) {
      message.error(error.message || '获取配置失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (values: QuizConfig) => {
    try {
      setSaving(true);
      
      // 验证比例总和（添加容错，允许±0.01的精度误差）
      const totalRatio = values.singleRatio + values.multipleRatio + values.judgmentRatio + values.textRatio;
      console.log('题型比例总和:', totalRatio);
      if (Math.abs(totalRatio - 100) > 0.01) {
        message.error('题型比例总和必须为100%');
        return;
      }

      // 验证总分
      if (values.totalScore <= 0) {
        message.error('总分必须大于0');
        return;
      }

      await adminAPI.updateQuizConfig(values);
      message.success('配置更新成功');
      setConfigValues(values); // 更新state
    } catch (error: any) {
      message.error(error.message || '更新配置失败');
      console.error('更新配置失败:', error);
    } finally {
      setSaving(false);
    }
  };

  const onValuesChange = (changedValues: any, allValues: QuizConfig) => {
    // 只更新state，不调用setFieldsValue，避免循环更新
    setConfigValues(allValues);
  };

  const getProgressColor = (ratio: number) => {
    if (ratio >= 40) return '#52c41a';
    if (ratio >= 20) return '#faad14';
    return '#ff4d4f';
  };

  return (
    <GlassCard>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-white">抽题配置</h1>
        <p className="text-white/60 mt-2">设置各题型的比例和试卷总分</p>
      </div>

      <div className="bg-white/5 p-6 rounded-lg mb-6">
        <div className="flex items-center justify-between mb-6">
          <span className="text-lg font-medium text-white">抽题配置</span>
          <span className={`text-sm ${configValues.singleRatio + configValues.multipleRatio + configValues.judgmentRatio + configValues.textRatio === 100 ? 'text-green-400' : 'text-red-400'}`}>
            比例总和：{configValues.singleRatio + configValues.multipleRatio + configValues.judgmentRatio + configValues.textRatio}%
          </span>
        </div>
        
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          onValuesChange={onValuesChange}
          initialValues={{
            singleRatio: 40,
            multipleRatio: 30,
            judgmentRatio: 20,
            textRatio: 10,
            totalScore: 100
          }}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                label={<span className="text-white">单选题比例 (%)</span>}
                name="singleRatio"
                rules={[{ required: true, message: '请输入单选题比例' }]}
              >
                <InputNumber
                  min={0}
                  max={100}
                  style={{ width: '100%' }}
                  formatter={(value) => `${value}%`}
                  parser={(value) => value!.replace('%', '') as any}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <div className="mt-8">
                <Progress
                  percent={configValues.singleRatio}
                  strokeColor={getProgressColor(configValues.singleRatio)}
                  showInfo={false}
                  trailColor="rgba(255,255,255,0.1)"
                />
              </div>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                label={<span className="text-white">多选题比例 (%)</span>}
                name="multipleRatio"
                rules={[{ required: true, message: '请输入多选题比例' }]}
              >
                <InputNumber
                  min={0}
                  max={100}
                  style={{ width: '100%' }}
                  formatter={(value) => `${value}%`}
                  parser={(value) => value!.replace('%', '') as any}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <div className="mt-8">
                <Progress
                  percent={configValues.multipleRatio}
                  strokeColor={getProgressColor(configValues.multipleRatio)}
                  showInfo={false}
                  trailColor="rgba(255,255,255,0.1)"
                />
              </div>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                label={<span className="text-white">判断题比例 (%)</span>}
                name="judgmentRatio"
                rules={[{ required: true, message: '请输入判断题比例' }]}
              >
                <InputNumber
                  min={0}
                  max={100}
                  style={{ width: '100%' }}
                  formatter={(value) => `${value}%`}
                  parser={(value) => value!.replace('%', '') as any}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <div className="mt-8">
                <Progress
                  percent={configValues.judgmentRatio}
                  strokeColor={getProgressColor(configValues.judgmentRatio)}
                  showInfo={false}
                  trailColor="rgba(255,255,255,0.1)"
                />
              </div>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                label={<span className="text-white">文字题比例 (%)</span>}
                name="textRatio"
                rules={[{ required: true, message: '请输入文字题比例' }]}
              >
                <InputNumber
                  min={0}
                  max={100}
                  style={{ width: '100%' }}
                  formatter={(value) => `${value}%`}
                  parser={(value) => value!.replace('%', '') as any}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <div className="mt-8">
                <Progress
                  percent={configValues.textRatio}
                  strokeColor={getProgressColor(configValues.textRatio)}
                  showInfo={false}
                  trailColor="rgba(255,255,255,0.1)"
                />
              </div>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                label={<span className="text-white">试卷总分</span>}
                name="totalScore"
                rules={[{ required: true, message: '请输入试卷总分' }]}
              >
                <InputNumber
                  min={1}
                  max={200}
                  style={{ width: '100%' }}
                  formatter={(value) => `${value}分`}
                  parser={(value) => value!.replace('分', '') as any}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <div className="h-full flex items-center text-white/50 pt-4">
                建议设置：100-150分
              </div>
            </Col>
          </Row>

          <Form.Item className="mb-0">
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={saving}
              className="rounded-lg"
            >
              保存配置
            </Button>
          </Form.Item>
        </Form>
      </div>

      {/* 配置说明 */}
      <div className="bg-white/5 p-6 rounded-lg">
        <h3 className="text-lg font-medium text-white mb-4">配置说明</h3>
        <div className="space-y-3 text-white/60">
          <p>• 各题型比例总和必须为100%</p>
          <p>• 系统会根据比例和总分自动计算各题型的题目数量</p>
          <p>• 建议单选题比例不低于30%，确保试卷的覆盖面</p>
          <p>• 文字题比例建议不超过20%，避免评分主观性过强</p>
          <p>• 总分设置建议为100分，便于成绩统计和分析</p>
        </div>
      </div>
    </GlassCard>
  );
};

export default QuizConfigPage;