import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/test_models.dart';
import '../providers/test_riverpod_provider.dart';

/// 测试结果页面
class TestResultScreen extends ConsumerWidget {
  final TestResult testResult;

  const TestResultScreen({
    super.key,
    required this.testResult,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        title: const Text('测试结果'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black87,
        elevation: 0,
        actions: [
          IconButton(
            onPressed: () => _shareResult(context),
            icon: const Icon(Icons.share),
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildOverallScore(),
            const SizedBox(height: 24),
            _buildSkillBreakdown(),
            const SizedBox(height: 24),
            _buildPerformanceAnalysis(),
            const SizedBox(height: 24),
            _buildRecommendations(),
            const SizedBox(height: 24),
            _buildActionButtons(context),
          ],
        ),
      ),
    );
  }

  Widget _buildOverallScore() {
    final percentage = (testResult.totalScore / testResult.maxScore * 100).round();
    final level = _getScoreLevel(percentage);
    final color = _getScoreColor(percentage);

    return Container(
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        children: [
          Row(
            children: [
              Icon(
                Icons.emoji_events,
                size: 32,
                color: color,
              ),
              const SizedBox(width: 12),
              const Expanded(
                child: Text(
                  '总体成绩',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 20),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.baseline,
            textBaseline: TextBaseline.alphabetic,
            children: [
              Text(
                '$percentage',
                style: TextStyle(
                  fontSize: 48,
                  fontWeight: FontWeight.bold,
                  color: color,
                ),
              ),
              Text(
                '%',
                style: TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.w600,
                  color: color,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Text(
            level,
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: color,
            ),
          ),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildScoreDetail('得分', '${testResult.totalScore}'),
              _buildScoreDetail('满分', '${testResult.maxScore}'),
              _buildScoreDetail('用时', _formatDuration(testResult.duration)),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildScoreDetail(String label, String value) {
    return Column(
      children: [
        Text(
          value,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey[600],
          ),
        ),
      ],
    );
  }

  Widget _buildSkillBreakdown() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Row(
            children: [
              Icon(
                Icons.analytics,
                size: 24,
                color: Colors.blue,
              ),
              SizedBox(width: 8),
              Text(
                '技能分析',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
          const SizedBox(height: 20),
          ...testResult.skillScores.map((skillScore) => _buildSkillItem(skillScore)),
        ],
      ),
    );
  }

  Widget _buildSkillItem(SkillScore skillScore) {
    final color = _getSkillColor(skillScore.skillType);
    final percentage = skillScore.percentage;

    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                _getSkillName(skillScore.skillType),
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                ),
              ),
              Text(
                '${percentage.round()}%',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: color,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          LinearProgressIndicator(
            value: percentage / 100,
            backgroundColor: Colors.grey[200],
            valueColor: AlwaysStoppedAnimation<Color>(color),
          ),
          const SizedBox(height: 4),
          Text(
            _getDifficultyName(skillScore.level),
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPerformanceAnalysis() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Row(
            children: [
              Icon(
                Icons.insights,
                size: 24,
                color: Colors.green,
              ),
              SizedBox(width: 8),
              Text(
                '表现分析',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          if (testResult.feedback != null) ...[
            Text(
              testResult.feedback!,
              style: const TextStyle(
                fontSize: 14,
                height: 1.5,
              ),
            ),
          ] else ...[
            _buildDefaultAnalysis(),
          ],
        ],
      ),
    );
  }

  Widget _buildDefaultAnalysis() {
    final percentage = (testResult.totalScore / testResult.maxScore * 100).round();
    String analysis;
    
    if (percentage >= 90) {
      analysis = '恭喜！您的表现非常出色，各项技能都达到了很高的水平。继续保持这种学习状态，可以尝试更高难度的挑战。';
    } else if (percentage >= 80) {
      analysis = '您的表现很好！大部分技能都掌握得不错，但还有一些提升空间。建议重点关注得分较低的技能领域。';
    } else if (percentage >= 70) {
      analysis = '您的基础还不错，但需要在某些技能上加强练习。建议制定针对性的学习计划，逐步提升薄弱环节。';
    } else if (percentage >= 60) {
      analysis = '您已经掌握了一些基础知识，但还需要更多的练习和学习。建议从基础开始，循序渐进地提升各项技能。';
    } else {
      analysis = '建议您从基础开始系统性地学习，多做练习，不要着急，学习是一个循序渐进的过程。';
    }

    return Text(
      analysis,
      style: const TextStyle(
        fontSize: 14,
        height: 1.5,
      ),
    );
  }

  Widget _buildRecommendations() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Row(
            children: [
              Icon(
                Icons.lightbulb,
                size: 24,
                color: Colors.orange,
              ),
              SizedBox(width: 8),
              Text(
                '学习建议',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          if (testResult.recommendations != null && testResult.recommendations!.isNotEmpty) ...[
            ...testResult.recommendations!.values.where((v) => v is String).map((recommendation) => _buildRecommendationItem(recommendation as String)),
          ] else ...[
            ..._getDefaultRecommendations().map((recommendation) => _buildRecommendationItem(recommendation)),
          ],
        ],
      ),
    );
  }

  Widget _buildRecommendationItem(String recommendation) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 6,
            height: 6,
            margin: const EdgeInsets.only(top: 6),
            decoration: const BoxDecoration(
              color: Colors.orange,
              shape: BoxShape.circle,
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              recommendation,
              style: const TextStyle(
                fontSize: 14,
                height: 1.4,
              ),
            ),
          ),
        ],
      ),
    );
  }

  List<String> _getDefaultRecommendations() {
    final weakSkills = testResult.skillScores
        .where((skill) => skill.percentage < 70)
        .map((skill) => _getSkillName(skill.skillType))
        .toList();

    List<String> recommendations = [];

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

    recommendations.addAll([
      '每天坚持30分钟的英语学习',
      '多做相关类型的练习题',
      '建议参加更多的模拟测试',
      '可以寻求老师或同学的帮助',
    ]);

    return recommendations;
  }

  Widget _buildActionButtons(BuildContext context) {
    return Column(
      children: [
        SizedBox(
          width: double.infinity,
          child: ElevatedButton(
            onPressed: () => _retakeTest(context),
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF2196F3),
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(vertical: 16),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
            ),
            child: const Text(
              '重新测试',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ),
        const SizedBox(height: 12),
        SizedBox(
          width: double.infinity,
          child: OutlinedButton(
            onPressed: () => _backToHome(context),
            style: OutlinedButton.styleFrom(
              foregroundColor: const Color(0xFF2196F3),
              padding: const EdgeInsets.symmetric(vertical: 16),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
            ),
            child: const Text(
              '返回首页',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ),
      ],
    );
  }

  void _shareResult(BuildContext context) {
    // 这里应该实现分享功能
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('分享功能正在开发中...'),
        backgroundColor: Colors.blue,
      ),
    );
  }

  void _retakeTest(BuildContext context) {
    Navigator.of(context).popUntil((route) => route.isFirst);
  }

  void _backToHome(BuildContext context) {
    Navigator.of(context).popUntil((route) => route.isFirst);
  }

  String _formatDuration(int seconds) {
    final minutes = seconds ~/ 60;
    final remainingSeconds = seconds % 60;
    return '${minutes}分${remainingSeconds}秒';
  }

  String _getScoreLevel(int percentage) {
    if (percentage >= 90) return '优秀';
    if (percentage >= 80) return '良好';
    if (percentage >= 70) return '中等';
    if (percentage >= 60) return '及格';
    return '需要努力';
  }

  Color _getScoreColor(int percentage) {
    if (percentage >= 90) return Colors.green;
    if (percentage >= 80) return Colors.blue;
    if (percentage >= 70) return Colors.orange;
    if (percentage >= 60) return Colors.amber;
    return Colors.red;
  }

  Color _getSkillColor(SkillType skill) {
    switch (skill) {
      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;
    }
  }

  String _getSkillName(SkillType skill) {
    switch (skill) {
      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 _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 '专家级';
    }
  }
}