import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'dart:async';
import '../models/test_models.dart';
import '../providers/test_riverpod_provider.dart';
import '../data/test_static_data.dart';
import '../widgets/question_widgets.dart';
import 'test_result_screen.dart';

/// 测试执行页面
class TestExecutionScreen extends ConsumerStatefulWidget {
  final TestTemplate template;

  const TestExecutionScreen({
    super.key,
    required this.template,
  });

  @override
  ConsumerState<TestExecutionScreen> createState() => _TestExecutionScreenState();
}

class _TestExecutionScreenState extends ConsumerState<TestExecutionScreen> {
  Timer? _timer;
  int _timeRemaining = 0;
  bool _isTestStarted = false;
  bool _isTestCompleted = false;
  Map<String, UserAnswer> _userAnswers = {};
  
  @override
  void initState() {
    super.initState();
    _timeRemaining = widget.template.duration * 60; // 转换为秒
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _startTest();
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  void _startTest() async {
    setState(() {
      _isTestStarted = true;
    });
    
    // 创建测试会话（使用静态数据）
    final questions = TestStaticData.getAllQuestions().take(10).toList(); // 取前10题作为测试
    final session = TestSession(
      id: 'test_session_${DateTime.now().millisecondsSinceEpoch}',
      templateId: widget.template.id,
      userId: 'current_user',
      status: TestStatus.inProgress,
      questions: questions,
      answers: [],
      currentQuestionIndex: 0,
      startTime: DateTime.now(),
      timeRemaining: _timeRemaining,
      metadata: {},
    );
    
    // 更新provider状态
    ref.read(testProvider.notifier).setCurrentSession(session);
    
    // 启动计时器
    _startTimer();
  }

  void _startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_timeRemaining > 0) {
          _timeRemaining--;
        } else {
          _submitTest();
        }
      });
    });
  }

  void _submitTest() async {
    if (_isTestCompleted) return;
    
    _timer?.cancel();
    setState(() {
      _isTestCompleted = true;
    });

    // 获取当前会话和答案
    final currentSession = ref.read(testProvider).currentSession;
    if (currentSession == null) return;

    // 创建测试结果
    final testResult = _createTestResult(currentSession);
    
    // 更新provider状态
    ref.read(testProvider.notifier).setCurrentResult(testResult);
    
    // 导航到结果页面
    if (mounted) {
      Navigator.of(context).pushReplacement(
        MaterialPageRoute(
          builder: (context) => TestResultScreen(
            testResult: testResult,
          ),
        ),
      );
    }
  }

  TestResult _createTestResult(TestSession session) {
    final answers = session.answers;
    int totalScore = 0;
    int maxScore = 0;
    Map<SkillType, List<int>> skillScores = {};

    // 计算得分
    for (final question in session.questions) {
      maxScore += question.points;
      final userAnswer = answers.where((a) => a.questionId == question.id).firstOrNull;
      
      if (userAnswer != null) {
        // 简单的评分逻辑
        bool isCorrect = false;
        if (question.type == QuestionType.multipleChoice) {
          isCorrect = userAnswer.selectedAnswers.isNotEmpty && 
                     question.correctAnswers.contains(userAnswer.selectedAnswers.first);
        } else if (question.type == QuestionType.fillInBlank) {
          isCorrect = userAnswer.textAnswer?.toLowerCase().trim() != null &&
                     question.correctAnswers.any((correct) => 
                       correct.toLowerCase().trim() == userAnswer.textAnswer!.toLowerCase().trim());
        }
        
        if (isCorrect) {
          totalScore += question.points;
        }
        
        // 记录技能得分
        final skill = question.skillType;
        if (!skillScores.containsKey(skill)) {
          skillScores[skill] = [];
        }
        skillScores[skill]!.add(isCorrect ? question.points : 0);
      }
    }

    // 计算技能得分
    final skillScoresList = skillScores.entries.map((entry) {
      final skill = entry.key;
      final scores = entry.value;
      final skillTotal = scores.reduce((a, b) => a + b);
      final skillMax = scores.length * 10; // 假设每题10分
      final percentage = skillMax > 0 ? (skillTotal / skillMax * 100) : 0.0;
      
      return SkillScore(
        skillType: skill,
        score: skillTotal,
        maxScore: skillMax,
        percentage: percentage,
        level: _getSkillLevel(percentage),
        feedback: _getSkillFeedback(skill, percentage),
      );
    }).toList();

    final overallPercentage = maxScore > 0 ? (totalScore / maxScore * 100) : 0.0;
    
    return TestResult(
      id: 'result_${DateTime.now().millisecondsSinceEpoch}',
      testId: session.id,
      userId: session.userId,
      testType: TestType.standard,
      totalScore: totalScore,
      maxScore: maxScore,
      percentage: overallPercentage,
      overallLevel: _getSkillLevel(overallPercentage),
      skillScores: skillScoresList,
      answers: answers,
      startTime: session.startTime!,
      endTime: DateTime.now(),
      duration: DateTime.now().difference(session.startTime!).inSeconds,
      feedback: _getOverallFeedback(totalScore, maxScore),
      recommendations: _getRecommendations(skillScoresList),
    );
  }

  LanguageSkill _convertSkillType(SkillType skillType) {
    switch (skillType) {
      case SkillType.vocabulary:
        return LanguageSkill.vocabulary;
      case SkillType.grammar:
        return LanguageSkill.grammar;
      case SkillType.reading:
        return LanguageSkill.reading;
      case SkillType.listening:
        return LanguageSkill.listening;
      case SkillType.speaking:
        return LanguageSkill.speaking;
      case SkillType.writing:
        return LanguageSkill.writing;
    }
  }

  DifficultyLevel _getSkillLevel(double percentage) {
    if (percentage >= 90) return DifficultyLevel.expert;
    if (percentage >= 80) return DifficultyLevel.advanced;
    if (percentage >= 70) return DifficultyLevel.upperIntermediate;
    if (percentage >= 60) return DifficultyLevel.intermediate;
    if (percentage >= 50) return DifficultyLevel.elementary;
    return DifficultyLevel.beginner;
  }

  String _getSkillTypeName(SkillType skillType) {
    switch (skillType) {
      case SkillType.vocabulary:
        return '词汇';
      case SkillType.grammar:
        return '语法';
      case SkillType.reading:
        return '阅读';
      case SkillType.listening:
        return '听力';
      case SkillType.speaking:
        return '口语';
      case SkillType.writing:
        return '写作';
    }
  }

  String _getSkillFeedback(SkillType skillType, double percentage) {
    final skillName = _getSkillTypeName(skillType);
    if (percentage >= 80) {
      return '$skillName 掌握得很好，继续保持！';
    } else if (percentage >= 60) {
      return '$skillName 基础不错，还有提升空间。';
    } else {
      return '$skillName 需要加强练习。';
    }
  }

  String _getSkillName(SkillType skillType) {
    switch (skillType) {
      case SkillType.vocabulary:
        return '词汇';
      case SkillType.grammar:
        return '语法';
      case SkillType.reading:
        return '阅读';
      case SkillType.listening:
        return '听力';
      case SkillType.speaking:
        return '口语';
      case SkillType.writing:
        return '写作';
    }
  }

  String _getOverallFeedback(int totalScore, int maxScore) {
    final percentage = (totalScore / maxScore * 100).round();
    if (percentage >= 90) {
      return '恭喜！您的表现非常出色，各项技能都达到了很高的水平。';
    } else if (percentage >= 80) {
      return '您的表现很好！大部分技能都掌握得不错，但还有一些提升空间。';
    } else if (percentage >= 70) {
      return '您的基础还不错，但需要在某些技能上加强练习。';
    } else if (percentage >= 60) {
      return '您已经掌握了一些基础知识，但还需要更多的练习和学习。';
    } else {
      return '建议您从基础开始系统性地学习，多做练习。';
    }
  }

  Map<String, dynamic> _getRecommendations(List<SkillScore> skillScores) {
    final weakSkills = skillScores
        .where((skill) => skill.percentage < 70)
        .map((skill) => _getSkillTypeName(skill.skillType))
        .toList();

    List<String> recommendations = [];

    if (weakSkills.isNotEmpty) {
      recommendations.add('重点加强${weakSkills.join('、')}方面的练习');
    }

    recommendations.addAll([
      '每天坚持30分钟的英语学习',
      '多做相关类型的练习题',
      '建议参加更多的模拟测试',
    ]);

    return {
      'general': recommendations,
      'weakSkills': weakSkills,
    };
  }

  void _onAnswerChanged(String questionId, UserAnswer answer) {
    setState(() {
      _userAnswers[questionId] = answer;
    });
  }

  void _nextQuestion() {
    ref.read(testProvider.notifier).nextQuestion();
  }

  void _previousQuestion() {
    ref.read(testProvider.notifier).previousQuestion();
  }

  String _formatTime(int seconds) {
    final minutes = seconds ~/ 60;
    final remainingSeconds = seconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    final testState = ref.watch(testProvider);
    final currentQuestion = testState.currentQuestion;
    final currentSession = testState.currentSession;

    if (!_isTestStarted || currentSession == null) {
      return _buildLoadingScreen();
    }

    if (currentQuestion == null) {
      return _buildCompletionScreen();
    }

    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        title: Text(widget.template.name),
        backgroundColor: const Color(0xFF2196F3),
        foregroundColor: Colors.white,
        elevation: 0,
        actions: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            margin: const EdgeInsets.only(right: 16),
            decoration: BoxDecoration(
              color: _timeRemaining < 300 ? Colors.red : Colors.white.withOpacity(0.2),
              borderRadius: BorderRadius.circular(20),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(
                  Icons.timer,
                  size: 16,
                  color: _timeRemaining < 300 ? Colors.white : Colors.white,
                ),
                const SizedBox(width: 4),
                Text(
                  _formatTime(_timeRemaining),
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: _timeRemaining < 300 ? Colors.white : Colors.white,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          _buildProgressBar(currentSession),
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildQuestionHeader(currentQuestion, currentSession),
                  const SizedBox(height: 24),
                  _buildQuestionContent(),
                ],
              ),
            ),
          ),
          _buildNavigationBar(currentSession),
        ],
      ),
    );
  }

  Widget _buildLoadingScreen() {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      body: const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text(
              '正在准备测试...',
              style: TextStyle(fontSize: 16),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCompletionScreen() {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.check_circle,
              size: 64,
              color: Colors.green,
            ),
            const SizedBox(height: 16),
            const Text(
              '测试已完成！',
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8),
            const Text(
              '正在计算结果...',
              style: TextStyle(fontSize: 16),
            ),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: _submitTest,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.green,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 12),
              ),
              child: const Text('查看结果'),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildProgressBar(TestSession session) {
    final progress = (session.currentQuestionIndex + 1) / session.questions.length;
    
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '题目 ${session.currentQuestionIndex + 1} / ${session.questions.length}',
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                ),
              ),
              Text(
                '${(progress * 100).toInt()}% 完成',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[600],
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          LinearProgressIndicator(
            value: progress,
            backgroundColor: Colors.grey[200],
            valueColor: const AlwaysStoppedAnimation<Color>(Color(0xFF2196F3)),
          ),
        ],
      ),
    );
  }

  Widget _buildQuestionHeader(TestQuestion question, TestSession session) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: _getSkillColor(question.skillType).withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  _getSkillName(question.skillType),
                  style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.w600,
                    color: _getSkillColor(question.skillType),
                  ),
                ),
              ),
              const SizedBox(width: 8),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: _getDifficultyColor(question.difficulty).withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  _getDifficultyName(question.difficulty),
                  style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.w600,
                    color: _getDifficultyColor(question.difficulty),
                  ),
                ),
              ),
              const Spacer(),
              Row(
                children: [
                  Icon(
                    Icons.star,
                    size: 16,
                    color: Colors.amber[600],
                  ),
                  const SizedBox(width: 4),
                  Text(
                    '${question.points} 分',
                    style: TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.w600,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildQuestionContent() {
    final testState = ref.watch(testProvider);
    final currentQuestion = testState.currentQuestion;
    
    if (currentQuestion == null) {
      return const Center(
        child: Text(
          '没有找到题目',
          style: TextStyle(fontSize: 16, color: Colors.grey),
        ),
      );
    }

    final userAnswer = testState.currentSession?.answers
        .where((answer) => answer.questionId == currentQuestion.id)
        .firstOrNull;

    return QuestionWidget(
      question: currentQuestion,
      userAnswer: userAnswer,
      onAnswerChanged: (answer) {
        ref.read(testProvider.notifier).recordAnswer(answer);
      },
    );
  }

  Widget _buildNavigationBar(TestSession session) {
    final canGoPrevious = session.currentQuestionIndex > 0;
    final canGoNext = session.currentQuestionIndex < session.questions.length - 1;
    final isLastQuestion = session.currentQuestionIndex == session.questions.length - 1;

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 4,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: ElevatedButton(
              onPressed: canGoPrevious ? _previousQuestion : null,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.grey[300],
                foregroundColor: Colors.grey[700],
                padding: const EdgeInsets.symmetric(vertical: 12),
              ),
              child: const Text('上一题'),
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            flex: 2,
            child: ElevatedButton(
              onPressed: isLastQuestion ? _submitTest : (canGoNext ? _nextQuestion : null),
              style: ElevatedButton.styleFrom(
                backgroundColor: isLastQuestion ? Colors.green : const Color(0xFF2196F3),
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(vertical: 12),
              ),
              child: Text(isLastQuestion ? '提交测试' : '下一题'),
            ),
          ),
        ],
      ),
    );
  }

  Color _getSkillColor(SkillType skillType) {
    switch (skillType) {
      case SkillType.vocabulary:
        return Colors.blue;
      case SkillType.grammar:
        return Colors.green;
      case SkillType.reading:
        return Colors.orange;
      case SkillType.listening:
        return Colors.purple;
      case SkillType.speaking:
        return Colors.red;
      case SkillType.writing:
        return Colors.teal;
    }
  }

  Color _getDifficultyColor(DifficultyLevel difficulty) {
    switch (difficulty) {
      case DifficultyLevel.beginner:
        return Colors.green;
      case DifficultyLevel.elementary:
        return Colors.lightGreen;
      case DifficultyLevel.intermediate:
        return Colors.orange;
      case DifficultyLevel.upperIntermediate:
        return Colors.deepOrange;
      case DifficultyLevel.advanced:
        return Colors.red;
      case DifficultyLevel.expert:
        return Colors.purple;
    }
  }

  String _getDifficultyName(DifficultyLevel difficulty) {
    switch (difficulty) {
      case DifficultyLevel.beginner:
        return '初级';
      case DifficultyLevel.elementary:
        return '基础';
      case DifficultyLevel.intermediate:
        return '中级';
      case DifficultyLevel.upperIntermediate:
        return '中高级';
      case DifficultyLevel.advanced:
        return '高级';
      case DifficultyLevel.expert:
        return '专家级';
    }
  }
}