import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/test_models.dart';
import '../providers/test_riverpod_provider.dart';
import '../screens/test_execution_screen.dart';
import '../../auth/providers/auth_provider.dart' as auth;

/// 综合测试页面
class ComprehensiveTestScreen extends ConsumerStatefulWidget {
  const ComprehensiveTestScreen({super.key});

  @override
  ConsumerState<ComprehensiveTestScreen> createState() => _ComprehensiveTestScreenState();
}

class _ComprehensiveTestScreenState extends ConsumerState<ComprehensiveTestScreen> {
  @override
  void initState() {
    super.initState();
    // 加载测试模板和最近结果
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(testProvider.notifier).loadTestTemplates();
      _loadRecentResults();
    });
  }

  void _loadRecentResults() async {
    // 尝试获取认证状态，但不强制要求登录
    try {
      final authState = ref.read(auth.authProvider);
      final userId = authState.user?.id;
      if (userId != null) {
        ref.read(testProvider.notifier).loadRecentResults(userId: userId);
      } else {
        // 用户未登录时，显示模拟数据或空状态
        print('用户未登录，显示静态内容');
      }
    } catch (e) {
      // 认证服务出错时，继续显示静态内容
      print('认证服务错误: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    final testState = ref.watch(testProvider);
    
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        title: const Text(
          '综合测试',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
        backgroundColor: const Color(0xFF2196F3),
        elevation: 0,
        centerTitle: true,
      ),
      body: _buildBody(testState),
    );
  }

  Widget _buildBody(TestState testState) {
    // 如果正在加载，显示加载指示器
    if (testState.isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    // 如果有错误，显示错误信息
    if (testState.errorMessage != null) {
      return _buildErrorView(testState.errorMessage!);
    }

    // 显示正常内容（静态展示，不强制登录）
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildWelcomeSection(),
          const SizedBox(height: 24),
          _buildTestTypes(testState),
          const SizedBox(height: 32),
          _buildRecentResults(testState),
        ],
      ),
    );
  }

  Widget _buildErrorView(String errorMessage) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 64,
            color: Colors.red[300],
          ),
          const SizedBox(height: 16),
          Text(
            errorMessage,
            style: TextStyle(
              fontSize: 16,
              color: Colors.red[600],
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: () {
              ref.read(testProvider.notifier).loadTestTemplates();
              _loadRecentResults();
            },
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  Widget _buildWelcomeSection() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Colors.teal.withOpacity(0.1),
            Colors.teal.withOpacity(0.05),
          ],
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: Colors.teal.withOpacity(0.2)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.teal.withOpacity(0.2),
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  Icons.quiz,
                  color: Colors.teal,
                  size: 24,
                ),
              ),
              const SizedBox(width: 16),
              const Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '全面能力评估',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                    ),
                    SizedBox(height: 4),
                    Text(
                      '测试您的英语综合能力水平',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildTestTypes(TestState testState) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '测试类型',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 16),
        if (testState.templates.isEmpty)
          const Center(
            child: Text(
              '暂无可用的测试模板',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey,
              ),
            ),
          )
        else
          GridView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: 16,
              mainAxisSpacing: 16,
              childAspectRatio: 1.2,
            ),
            itemCount: testState.templates.length,
            itemBuilder: (context, index) {
              final template = testState.templates[index];
              return _buildTestCard(
                template: template,
                onTap: () => _startTest(template),
              );
            },
          ),
      ],
    );
  }

  Widget _buildTestCard({
    required TestTemplate template,
    required VoidCallback onTap,
  }) {
    final color = _getColorForTestType(template.type);
    final icon = _getIconForTestType(template.type);
    
    return Card(
      elevation: 4,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(16),
        child: Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16),
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                color.withOpacity(0.1),
                color.withOpacity(0.05),
              ],
            ),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: color.withOpacity(0.2),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  icon,
                  size: 24,
                  color: color,
                ),
              ),
              const SizedBox(height: 12),
              Text(
                template.name,
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                ),
                textAlign: TextAlign.center,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 4),
              Text(
                '${template.duration}分钟',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey[600],
                ),
                textAlign: TextAlign.center,
              ),
              if (template.totalQuestions > 0)
                  Text(
                    '${template.totalQuestions}题',
                  style: TextStyle(
                    fontSize: 10,
                    color: Colors.grey[500],
                  ),
                  textAlign: TextAlign.center,
                ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildRecentResults(TestState testState) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '最近测试结果',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 16),
        if (testState.testResults.isEmpty)
          Card(
            elevation: 2,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            child: const Padding(
              padding: EdgeInsets.all(32),
              child: Center(
                child: Column(
                  children: [
                    Icon(
                      Icons.quiz_outlined,
                      size: 48,
                      color: Colors.grey,
                    ),
                    SizedBox(height: 16),
                    Text(
                      '暂无测试记录',
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.grey,
                      ),
                    ),
                    SizedBox(height: 8),
                    Text(
                      '完成第一次测试后，结果将显示在这里',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ],
                ),
              ),
            ),
          )
        else
          Card(
            elevation: 2,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                children: testState.testResults
                    .asMap()
                    .entries
                    .map((entry) {
                  final index = entry.key;
                  final result = entry.value;
                  return Column(
                    children: [
                      if (index > 0) const Divider(),
                      _buildResultItem(result: result),
                    ],
                  );
                }).toList(),
              ),
            ),
          ),
      ],
    );
  }

  Widget _buildResultItem({
    required TestResult result,
  }) {
    final template = ref.read(testProvider)
        .templates
        .firstWhere(
          (t) => t.id == result.testId,
          orElse: () => TestTemplate(
            id: result.testId,
            name: '未知测试',
            description: '',
            type: TestType.standard,
            duration: 0,
            totalQuestions: 0,
            skillDistribution: {},
            difficultyDistribution: {},
            questionIds: [],
            isActive: true,
            createdAt: DateTime.now(),
            updatedAt: DateTime.now(),
          ),
        );

    return InkWell(
      onTap: () => _showResultDetails(result),
      borderRadius: BorderRadius.circular(8),
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 8),
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: Colors.teal.withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: const Icon(
                Icons.quiz,
                color: Colors.teal,
                size: 20,
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    template.name,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: Colors.black87,
                    ),
                  ),
                  Text(
                    _formatDate(result.endTime),
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text(
                  '${result.totalScore.toStringAsFixed(0)}分',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: _getScoreColor(result.totalScore.toDouble()),
                  ),
                ),
                Text(
                  _getScoreLevel(result.totalScore.toDouble()),
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
            const SizedBox(width: 8),
            Icon(
              Icons.chevron_right,
              color: Colors.grey[400],
              size: 20,
            ),
          ],
        ),
      ),
    );
  }

  void _startTest(TestTemplate template) {
    // 显示测试开始确认对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('开始测试'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('确定要开始「${template.name}」吗？'),
              const SizedBox(height: 16),
              if (template.description.isNotEmpty) ...[
                Text(
                  template.description,
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[600],
                  ),
                ),
                const SizedBox(height: 12),
              ],
              Row(
                children: [
                  Icon(Icons.timer, size: 16, color: Colors.grey[600]),
                  const SizedBox(width: 4),
                  Text(
                    '${template.duration}分钟',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[600],
                    ),
                  ),
                  const SizedBox(width: 16),
                  Icon(Icons.quiz, size: 16, color: Colors.grey[600]),
                  const SizedBox(width: 4),
                  Text(
                    '${template.totalQuestions}题',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop();
                _navigateToTest(template);
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.teal,
                foregroundColor: Colors.white,
              ),
              child: const Text('开始'),
            ),
          ],
        );
      },
    );
  }

  void _navigateToTest(TestTemplate template) {
    // 导航到测试执行页面
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => TestExecutionScreen(template: template),
      ),
    );
  }

  void _showResultDetails(TestResult result) {
    // 显示测试结果详情
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('测试结果详情'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('总分：${result.totalScore.toStringAsFixed(1)}'),
              const SizedBox(height: 8),
              Text('完成时间：${_formatDate(result.endTime)}'),
              const SizedBox(height: 8),
              Text('用时：${result.duration}秒'),
              if (result.skillScores.isNotEmpty) ...[
                const SizedBox(height: 16),
                const Text(
                  '各项技能得分：',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                ...result.skillScores.map(
                  (skillScore) => Padding(
                    padding: const EdgeInsets.symmetric(vertical: 2),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(_getSkillTypeName(skillScore.skillType)),
                        Text('${skillScore.score}/${skillScore.maxScore}分'),
                      ],
                    ),
                  ),
                ),
              ],
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('关闭'),
            ),
          ],
        );
      },
    );
  }

  Color _getColorForTestType(TestType type) {
    switch (type) {
      case TestType.quick:
        return Colors.blue;
      case TestType.standard:
        return Colors.green;
      case TestType.full:
        return Colors.orange;
      case TestType.mock:
        return Colors.purple;
      case TestType.vocabulary:
        return Colors.teal;
      case TestType.grammar:
        return Colors.indigo;
      case TestType.reading:
        return Colors.brown;
      case TestType.listening:
        return Colors.cyan;
      case TestType.speaking:
        return Colors.pink;
      case TestType.writing:
        return Colors.amber;
    }
  }

  IconData _getIconForTestType(TestType type) {
    switch (type) {
      case TestType.quick:
        return Icons.flash_on;
      case TestType.standard:
        return Icons.school;
      case TestType.full:
        return Icons.quiz;
      case TestType.mock:
        return Icons.assignment;
      case TestType.vocabulary:
        return Icons.book;
      case TestType.grammar:
        return Icons.text_fields;
      case TestType.reading:
        return Icons.menu_book;
      case TestType.listening:
        return Icons.headphones;
      case TestType.speaking:
        return Icons.mic;
      case TestType.writing:
        return Icons.edit;
    }
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }

  Color _getScoreColor(double score) {
    if (score >= 90) return Colors.green;
    if (score >= 80) return Colors.blue;
    if (score >= 70) return Colors.orange;
    return Colors.red;
  }

  String _getScoreLevel(double score) {
    if (score >= 90) return '优秀';
    if (score >= 80) return '良好';
    if (score >= 70) return '中等';
    if (score >= 60) return '及格';
    return '不及格';
  }

  String _getSkillName(LanguageSkill skill) {
    switch (skill) {
      case LanguageSkill.listening:
        return '听力';
      case LanguageSkill.reading:
        return '阅读';
      case LanguageSkill.speaking:
        return '口语';
      case LanguageSkill.writing:
        return '写作';
      case LanguageSkill.vocabulary:
        return '词汇';
      case LanguageSkill.grammar:
        return '语法';
      case LanguageSkill.pronunciation:
        return '发音';
      case LanguageSkill.comprehension:
        return '理解';
    }
  }

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