import {useEffect, useState} from "react";
import {ArrowLeft, ArrowRight} from '@nutui/icons-react-taro'
import {Button, Radio, Input, Progress} from '@nutui/nutui-react-taro'
import Taro from '@tarojs/taro'
import { TextArea } from '@nutui/nutui-react-taro'
import {pageHjmQuestions} from "@/api/hjm/hjmQuestions";
import {HjmQuestions} from "@/api/hjm/hjmQuestions/model";
import {addHjmExamLog} from "@/api/hjm/hjmExamLog";

// 用户答案接口
interface UserAnswer {
  questionId: number;
  answer: string;
  isCorrect: boolean;
  score: number;
}

// 考试状态枚举
enum ExamStatus {
  NOT_STARTED = 'not_started',
  IN_PROGRESS = 'in_progress',
  COMPLETED = 'completed'
}

/**
 * 考试系统
 * @constructor
 */
const Exam = () => {
  const [questions, setQuestions] = useState<HjmQuestions[]>([])
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState<number>(0)
  const [userAnswers, setUserAnswers] = useState<UserAnswer[]>([])
  const [currentAnswer, setCurrentAnswer] = useState<any>('')
  const [examStatus, setExamStatus] = useState<ExamStatus>(ExamStatus.NOT_STARTED)
  const [totalScore, setTotalScore] = useState<number>(0)
  const [timeRemaining, setTimeRemaining] = useState<number>(600) // 10分钟考试时间
  const [loading, setLoading] = useState<boolean>(false)
  const [error, setError] = useState<string>('')

  // 加载题目
  const loadQuestions = () => {
    setLoading(true)
    setError('')
    console.log('开始加载题目...')

    pageHjmQuestions({}).then(data => {
      console.log('API返回数据:', data)
      const questionList = data?.list || []
      // 限制为10道题目
      const limitedQuestions = questionList.slice(0, 10)
      setQuestions(limitedQuestions)
      console.log('加载题目成功:', limitedQuestions)

      // 调试：检查选择题的 choicesList 数据
      limitedQuestions.forEach((question, index) => {
        if (question.type === 0) {
          console.log(`第${index + 1}题 (选择题):`, {
            question: question.question,
            choicesList: question.choicesList,
            correctAnswer: question.correctAnswer
          });
        }
      });

      if (limitedQuestions.length === 0) {
        setError('没有找到题目数据')
      }
    }).catch(error => {
      console.error('加载题目失败:', error)
      setError('加载题目失败: ' + (error.message || '未知错误'))
      Taro.showToast({
        title: '加载题目失败',
        icon: 'error'
      })
    }).finally(() => {
      setLoading(false)
    })
  }

  // 开始考试
  const startExam = () => {
    if (questions.length === 0) {
      Taro.showToast({
        title: '没有题目数据',
        icon: 'error'
      })
      return
    }
    console.log('开始考试，题目数量:', questions.length)
    setExamStatus(ExamStatus.IN_PROGRESS)
    setCurrentQuestionIndex(0)
    setUserAnswers([])
    setCurrentAnswer('')
    setTotalScore(0)
    setTimeRemaining(600)
  }

  // 获取当前题目
  const getCurrentQuestion = (): HjmQuestions | null => {
    try {
      if (questions && questions.length > 0 &&
        currentQuestionIndex >= 0 &&
        currentQuestionIndex < questions.length) {
        return questions[currentQuestionIndex]
      }
      return null
    } catch (error) {
      console.error('获取当前题目时出错:', error)
      return null
    }
  }

  // 提交当前题目答案
  const submitCurrentAnswer = () => {
    const currentQuestion = getCurrentQuestion()
    if (!currentQuestion || !currentAnswer.trim()) {
      Taro.showToast({
        title: '请选择或填写答案',
        icon: 'error'
      })
      return
    }

    // 计算得分
    const isCorrect = checkAnswer(currentQuestion, currentAnswer)
    const score = isCorrect ? 10 : 0 // 每题10分

    const userAnswer: UserAnswer = {
      questionId: currentQuestion.id!,
      answer: currentAnswer,
      isCorrect,
      score
    }

    const newUserAnswers = [...userAnswers, userAnswer]
    setUserAnswers(newUserAnswers)

    // 显示答题反馈
    const currentScore = userAnswers.reduce((sum, answer) => sum + answer.score, 0) + score
    Taro.showToast({
      title: isCorrect ? `回答正确！+10分 (总分:${currentScore})` : `回答错误！(总分:${currentScore})`,
      icon: isCorrect ? 'success' : 'none',
      duration: 1500
    })

    // 清空当前答案
    setCurrentAnswer('')

    // 延迟跳转，让用户看到反馈
    setTimeout(() => {
      // 检查是否是最后一题
      if (currentQuestionIndex === questions.length - 1) {
        // 考试结束
        finishExam(newUserAnswers)
      } else {
        // 下一题
        setCurrentQuestionIndex(currentQuestionIndex + 1)
      }
    }, 1500)
  }

  // 检查答案是否正确
  const checkAnswer = (question: HjmQuestions, answer: string): boolean => {
    try {
      if (question.type === 0) { // 选择题
        // 使用 choicesList 来检查答案
        if (question.choicesList && question.choicesList.length > 0) {
          // 找到用户选择的选项索引
          let selectedIndex = -1;

          // 如果答案是字母格式（A, B, C, D）
          if (answer.length === 1 && answer >= 'A' && answer <= 'D') {
            selectedIndex = answer.charCodeAt(0) - 65; // A=0, B=1, C=2, D=3
          }
          // 如果答案是数字格式（0, 1, 2, 3）
          else if (!isNaN(Number(answer))) {
            selectedIndex = Number(answer);
          }

          // 检查索引是否有效
          if (selectedIndex >= 0 && selectedIndex < question.choicesList.length) {
            return question.choicesList[selectedIndex]?.isCorrect || false;
          }
        }
        // 备用方案：使用 correctAnswer 字段
        return answer === question.correctAnswer
      } else if (question.type === 1) { // 填空题
        // 简单的字符串匹配，可以根据需要改进
        return answer.trim().toLowerCase() === question.correctAnswer?.trim().toLowerCase()
      }
      return false
    } catch (error) {
      console.error('检查答案时出错:', error)
      return false
    }
  }

  // 完成考试
  const finishExam = (answers: UserAnswer[]) => {
    const total = answers.reduce((sum, answer) => sum + answer.score, 0)
    setTotalScore(total)
    setExamStatus(ExamStatus.COMPLETED)
    Taro.showToast({
      title: `考试完成！得分：${total}分`,
      icon: 'success',
      duration: 3000
    })
    // 考试得满分完成本月学习任务
    addHjmExamLog({total: total.toString(), status: total == 100 ? 1 : 0, useTime: formatTime(600 - timeRemaining)}).then(() => {})
  }

  // 重新开始考试
  const restartExam = () => {
    setExamStatus(ExamStatus.NOT_STARTED)
    setCurrentQuestionIndex(0)
    setUserAnswers([])
    setCurrentAnswer('')
    setTotalScore(0)
    setTimeRemaining(600)
  }

  // 计算进度百分比
  const getProgress = (): number => {
    if (questions.length === 0) return 0
    return Math.round(((currentQuestionIndex + 1) / questions.length) * 100)
  }

  // 格式化时间显示
  const formatTime = (seconds: number): string => {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
  }

  // 获取成绩等级
  const getGradeLevel = (score: number, totalScore: number): { level: string, color: string, description: string } => {
    const percentage = (score / totalScore) * 100
    if (percentage >= 90) {
      return {level: '优秀', color: '#52c41a', description: '恭喜您！成绩优异！'}
    } else if (percentage >= 80) {
      return {level: '良好', color: '#1890ff', description: '成绩良好，继续努力！'}
    } else if (percentage >= 70) {
      return {level: '中等', color: '#faad14', description: '成绩中等，还有提升空间！'}
    } else if (percentage >= 60) {
      return {level: '及格', color: '#fa8c16', description: '刚好及格，需要加强学习！'}
    } else {
      return {level: '不及格', color: '#f5222d', description: '成绩不理想，建议重新学习！'}
    }
  }

  // 获取答题统计
  const getAnswerStats = () => {
    const correctCount = userAnswers.filter(answer => answer.isCorrect).length
    const wrongCount = userAnswers.length - correctCount
    const totalTime = 600 - timeRemaining
    return {
      correctCount,
      wrongCount,
      totalTime: formatTime(totalTime),
      accuracy: userAnswers.length > 0 ? Math.round((correctCount / userAnswers.length) * 100) : 0
    }
  }

  useEffect(() => {
    loadQuestions()
  }, [])

  // 倒计时效果
  useEffect(() => {
    let timer: NodeJS.Timeout
    if (examStatus === ExamStatus.IN_PROGRESS && timeRemaining > 0) {
      timer = setTimeout(() => {
        setTimeRemaining(prev => prev - 1)
      }, 1000)
    } else if (timeRemaining === 0 && examStatus === ExamStatus.IN_PROGRESS) {
      // 时间到，自动提交
      finishExam(userAnswers)
    }
    return () => {
      if (timer) {
        clearTimeout(timer)
      }
    }
  }, [examStatus, timeRemaining]) // 移除 userAnswers 依赖，避免无限循环

  const currentQuestion = getCurrentQuestion()

  return (
    <div style={{padding: '16px', minHeight: '100vh', backgroundColor: '#f5f5f5'}}>
      {/* 加载状态 */}
      {loading && (
        <div style={{backgroundColor: 'white', borderRadius: '8px', padding: '24px', textAlign: 'center'}}>
          <h1 style={{fontSize: '20px', fontWeight: 'bold', marginBottom: '16px'}}>正在加载题目...</h1>
          <div style={{color: '#666'}}>请稍候</div>
        </div>
      )}

      {/* 错误状态 */}
      {error && !loading && (
        <div style={{backgroundColor: 'white', borderRadius: '8px', padding: '24px', textAlign: 'center'}}>
          <h1 style={{fontSize: '20px', fontWeight: 'bold', marginBottom: '16px', color: '#f5222d'}}>加载失败</h1>
          <div style={{marginBottom: '16px', color: '#666'}}>{error}</div>
          <Button type="primary" onClick={loadQuestions}>
            重新加载
          </Button>
        </div>
      )}

      {/* 考试未开始 */}
      {!loading && !error && examStatus === ExamStatus.NOT_STARTED && (
        <div style={{backgroundColor: 'white', borderRadius: '8px', padding: '24px', textAlign: 'center'}}>
          <h1 style={{fontSize: '20px', fontWeight: 'bold', marginBottom: '16px'}}>在线考试系统</h1>
          <div style={{marginBottom: '16px', color: '#666'}}>
            <p>题目数量：{questions.length} 道</p>
            <p>考试时间：10 分钟</p>
            <p>每题分值：10 分</p>
            <p>总分：{questions.length * 10} 分</p>
          </div>
          <Button
            type="primary"
            size="large"
            onClick={startExam}
            disabled={questions.length === 0}
          >
            开始考试
          </Button>
          {questions.length === 0 && (
            <div style={{marginTop: '8px', fontSize: '14px', color: '#f5222d'}}>
              暂无题目数据，请联系管理员
            </div>
          )}
        </div>
      )}

      {/* 考试进行中 */}
      {examStatus === ExamStatus.IN_PROGRESS && currentQuestion && (
        <div>
          {/* 顶部信息栏 */}
          <div style={{backgroundColor: 'white', borderRadius: '8px', padding: '16px', marginBottom: '16px'}}>
            <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px'}}>
              <span style={{fontSize: '14px', color: '#666'}}>
                第 {currentQuestionIndex + 1} 题 / 共 {questions.length} 题
              </span>
              <span style={{fontSize: '14px', fontWeight: 'bold', color: '#f5222d'}}>
                剩余时间：{formatTime(timeRemaining)}
              </span>
            </div>
            <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px'}}>
              <span style={{fontSize: '14px', color: '#1890ff'}}>
                当前得分：{userAnswers.reduce((sum, answer) => sum + answer.score, 0)} 分
              </span>
              <span style={{fontSize: '14px', color: '#666'}}>
                已答：{userAnswers.length} 题
              </span>
            </div>
            <Progress percent={getProgress()} color="#1890ff"/>
          </div>

          {/* 题目内容 */}
          <div style={{backgroundColor: 'white', borderRadius: '8px', padding: '16px', marginBottom: '16px'}}>
            <div style={{marginBottom: '16px'}}>
              <h2 style={{fontSize: '18px', fontWeight: 'bold', marginBottom: '8px'}}>
                {currentQuestionIndex + 1}. {currentQuestion.question}
              </h2>
              <div style={{fontSize: '14px', color: '#999'}}>
                {currentQuestion.type === 0 ? '选择题' : currentQuestion.type === 1 ? '填空题' : '问答题'}
                （{currentQuestion.difficulty === 0 ? '简单' : currentQuestion.difficulty === 1 ? '中等' : '困难'}）
              </div>
            </div>

            {/* 选择题选项 */}
            {currentQuestion.type === 0 && (
              <div>
                <Radio.Group
                  value={currentAnswer}
                  onChange={(value) => setCurrentAnswer(value)}
                >
                  {currentQuestion.choicesList && currentQuestion.choicesList.length > 0 ? (
                    // 使用 choicesList 显示选项
                    currentQuestion.choicesList.map((choice, index) => {
                      const optionLabel = String.fromCharCode(65 + index); // A, B, C, D
                      return (
                        <div key={index} style={{marginBottom: '8px'}}>
                          <Radio value={optionLabel}>
                            {optionLabel}. {choice.content}
                          </Radio>
                        </div>
                      );
                    })
                  ) : (
                    // 备用方案：使用传统的 choicesA, choicesB 等字段
                    <>
                      {currentQuestion.choicesA && (
                        <div style={{marginBottom: '8px'}}>
                          <Radio value="A">A. {currentQuestion.choicesA}</Radio>
                        </div>
                      )}
                      {currentQuestion.choicesB && (
                        <div style={{marginBottom: '8px'}}>
                          <Radio value="B">B. {currentQuestion.choicesB}</Radio>
                        </div>
                      )}
                      {currentQuestion.choicesC && (
                        <div style={{marginBottom: '8px'}}>
                          <Radio value="C">C. {currentQuestion.choicesC}</Radio>
                        </div>
                      )}
                      {currentQuestion.choicesD && (
                        <div style={{marginBottom: '8px'}}>
                          <Radio value="D">D. {currentQuestion.choicesD}</Radio>
                        </div>
                      )}
                    </>
                  )}
                </Radio.Group>
              </div>
            )}

            {/* 填空题输入 */}
            {currentQuestion.type === 1 && (
              <div style={{marginBottom: '16px'}}>
                <Input
                  placeholder="请输入答案"
                  value={currentAnswer}
                  onChange={(value) => setCurrentAnswer(value)}
                />
              </div>
            )}

            {/* 问答题输入 */}
            {currentQuestion.type === 2 && (
              <div style={{marginBottom: '16px'}}>
                <TextArea
                  placeholder={'个性签名'}
                  value={currentAnswer}
                  onChange={(value) => setCurrentAnswer(value)}
                />
              </div>
            )}
          </div>

          {/* 操作按钮 */}
          <div style={{backgroundColor: 'white', borderRadius: '8px', padding: '16px'}}>
            <div style={{display: 'flex', justifyContent: 'space-between'}}>
              <Button
                type="default"
                disabled={currentQuestionIndex === 0}
                onClick={() => setCurrentQuestionIndex(currentQuestionIndex - 1)}
              >
                <ArrowLeft size={16}/> 上一题
              </Button>

              <Button
                type="primary"
                onClick={submitCurrentAnswer}
                disabled={!currentAnswer.trim()}
              >
                {currentQuestionIndex === questions.length - 1 ? '提交试卷' : '下一题'}
                <ArrowRight size={16}/>
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* 考试完成 */}
      {examStatus === ExamStatus.COMPLETED && (
        <div style={{backgroundColor: 'white', borderRadius: '8px', padding: '24px', textAlign: 'center'}}>
          <h1 style={{fontSize: '24px', fontWeight: 'bold', marginBottom: '16px', color: '#52c41a'}}>🎉
            考试完成！</h1>

          {/* 成绩展示 */}
          <div style={{marginBottom: '24px'}}>
            <div style={{fontSize: '36px', fontWeight: 'bold', color: '#1890ff', marginBottom: '8px'}}>{totalScore} 分
            </div>
            <div style={{color: '#666', marginBottom: '8px'}}>总分：{questions.length * 10} 分</div>

            {/* 成绩等级 */}
            {(() => {
              const gradeInfo = getGradeLevel(totalScore, questions.length * 10)
              return (
                <div style={{marginBottom: '16px'}}>
                  <div
                    style={{
                      display: 'inline-block',
                      padding: '8px 16px',
                      borderRadius: '20px',
                      color: 'white',
                      fontWeight: 'bold',
                      marginBottom: '8px',
                      backgroundColor: gradeInfo.color
                    }}
                  >
                    {gradeInfo.level}
                  </div>
                  <div style={{fontSize: '14px', color: '#666'}}>{gradeInfo.description}</div>
                </div>
              )
            })()}
          </div>

          {/* 答题统计 */}
          <div style={{marginBottom: '24px', backgroundColor: '#f5f5f5', borderRadius: '8px', padding: '16px'}}>
            <h3 style={{fontWeight: 'bold', marginBottom: '12px', textAlign: 'left'}}>📊 答题统计</h3>
            {(() => {
              const stats = getAnswerStats()
              return (
                <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', fontSize: '14px'}}>
                  <div style={{textAlign: 'center'}}>
                    <div style={{color: '#52c41a', fontWeight: 'bold', fontSize: '18px'}}>{stats.correctCount}</div>
                    <div style={{color: '#666'}}>答对题数</div>
                  </div>
                  <div style={{textAlign: 'center'}}>
                    <div style={{color: '#f5222d', fontWeight: 'bold', fontSize: '18px'}}>{stats.wrongCount}</div>
                    <div style={{color: '#666'}}>答错题数</div>
                  </div>
                  <div style={{textAlign: 'center'}}>
                    <div style={{color: '#1890ff', fontWeight: 'bold', fontSize: '18px'}}>{stats.accuracy}%</div>
                    <div style={{color: '#666'}}>正确率</div>
                  </div>
                  <div style={{textAlign: 'center'}}>
                    <div style={{color: '#722ed1', fontWeight: 'bold', fontSize: '18px'}}>{stats.totalTime}</div>
                    <div style={{color: '#666'}}>用时</div>
                  </div>
                </div>
              )
            })()}
          </div>

          {/* 答题详情 */}
          <div style={{marginBottom: '24px', textAlign: 'left'}}>
            <h3 style={{fontWeight: 'bold', marginBottom: '12px'}}>📝 答题详情</h3>
            <div style={{maxHeight: '320px', overflowY: 'auto'}}>
              {userAnswers.map((answer, index) => {
                const question = questions.find(q => q.id === answer.questionId)
                return (
                  <div
                    key={index}
                    style={{
                      padding: '12px',
                      borderRadius: '8px',
                      borderLeft: `4px solid ${answer.isCorrect ? '#52c41a' : '#f5222d'}`,
                      backgroundColor: answer.isCorrect ? '#f6ffed' : '#fff2f0',
                      marginBottom: '12px'
                    }}
                  >
                    <div style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'flex-start',
                      marginBottom: '8px'
                    }}>
                      <span style={{fontWeight: '500', fontSize: '14px'}}>第{index + 1}题</span>
                      <span style={{
                        fontSize: '14px',
                        fontWeight: 'bold',
                        color: answer.isCorrect ? '#52c41a' : '#f5222d'
                      }}>
                        {answer.isCorrect ? '✓ 正确' : '✗ 错误'} ({answer.score}分)
                      </span>
                    </div>
                    <div style={{fontSize: '14px', color: '#333', marginBottom: '8px'}}>
                      <strong>题目：</strong>{question?.question}
                    </div>
                    <div style={{fontSize: '14px'}}>
                      <span style={{color: '#666'}}>您的答案：</span>
                      <span style={{color: answer.isCorrect ? '#52c41a' : '#f5222d'}}>{answer.answer}</span>
                    </div>
                    {!answer.isCorrect && (
                      <div style={{fontSize: '14px', marginTop: '4px'}}>
                        <span style={{color: '#666'}}>正确答案：</span>
                        <span style={{color: '#52c41a'}}>
                          {(() => {
                            // 如果是选择题，显示正确选项的内容
                            if (question?.type === 0 && question.choicesList) {
                              const correctChoice = question.choicesList.find(choice => choice.isCorrect);
                              if (correctChoice) {
                                const correctIndex = question.choicesList.indexOf(correctChoice);
                                const correctLabel = String.fromCharCode(65 + correctIndex);
                                return `${correctLabel}. ${correctChoice.content}`;
                              }
                            }
                            // 备用方案：使用 correctAnswer 字段
                            return question?.correctAnswer || '未知';
                          })()}
                        </span>
                      </div>
                    )}
                  </div>
                )
              })}
            </div>
          </div>

          <div style={{display: 'flex', flexDirection: 'column', gap: '8px'}}>
            <Button type="primary" size="large" onClick={restartExam}>
              重新考试
            </Button>
            <Button type="default" size="large" onClick={() => Taro.navigateBack()}>
              返回
            </Button>
          </div>
        </div>
      )}
    </div>
  )
}
export default Exam
