import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/listening_exercise_model.dart';
// 改为使用后端真实数据，移除静态数据依赖
import '../../../core/routes/app_routes.dart';
import '../providers/listening_provider.dart';

class ListeningDifficultyScreen extends ConsumerStatefulWidget {
  const ListeningDifficultyScreen({Key? key}) : super(key: key);

  @override
  ConsumerState<ListeningDifficultyScreen> createState() => _ListeningDifficultyScreenState();
}

class _ListeningDifficultyScreenState extends ConsumerState<ListeningDifficultyScreen> {
  ListeningDifficulty? selectedDifficulty;

  final Map<ListeningDifficulty, Map<String, dynamic>> difficultyInfo = {
    ListeningDifficulty.beginner: {
      'title': '初级 (A1-A2)',
      'description': '适合英语初学者，语速较慢，词汇简单',
      'features': ['语速慢', '词汇基础', '发音清晰', '内容简单'],
      'color': Colors.green,
      'icon': Icons.sentiment_very_satisfied,
      'level': 'A1-A2',
    },
    ListeningDifficulty.intermediate: {
      'title': '中级 (B1)',
      'description': '适合有一定基础的学习者，语速适中',
      'features': ['语速适中', '词汇丰富', '语法复杂', '话题多样'],
      'color': Colors.orange,
      'icon': Icons.sentiment_satisfied,
      'level': 'B1',
    },
    ListeningDifficulty.advanced: {
      'title': '高级 (B2)',
      'description': '适合英语水平较高的学习者，接近自然语速',
      'features': ['语速较快', '词汇高级', '语法复杂', '专业话题'],
      'color': Colors.red,
      'icon': Icons.sentiment_neutral,
      'level': 'B2',
    },
    ListeningDifficulty.expert: {
      'title': '专家级 (C1-C2)',
      'description': '适合英语高手，自然语速，复杂内容',
      'features': ['自然语速', '专业词汇', '复杂语法', '学术内容'],
      'color': Colors.purple,
      'icon': Icons.psychology,
      'level': 'C1-C2',
    },
  };

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择难度等级'),
        backgroundColor: Colors.blue[50],
        elevation: 0,
      ),
      body: Column(
        children: [
          // 头部说明
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              color: Colors.blue[50],
              borderRadius: const BorderRadius.only(
                bottomLeft: Radius.circular(20),
                bottomRight: Radius.circular(20),
              ),
            ),
            child: Column(
              children: [
                Icon(
                  Icons.tune,
                  size: 48,
                  color: Colors.blue[600],
                ),
                const SizedBox(height: 12),
                Text(
                  '根据你的英语水平选择合适的难度',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.w600,
                    color: Colors.blue[700],
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  '基于欧洲共同语言参考标准 (CEFR)',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.blue[600],
                  ),
                ),
              ],
            ),
          ),
          
          // 难度选择列表
          Expanded(
            child: ListView(
              padding: const EdgeInsets.all(16),
              children: difficultyInfo.entries.map((entry) {
                final difficulty = entry.key;
                final info = entry.value;
                final isSelected = selectedDifficulty == difficulty;
                final exerciseCount = null;
                
                return Container(
                  margin: const EdgeInsets.only(bottom: 16),
                  child: InkWell(
                    onTap: () {
                      setState(() {
                        selectedDifficulty = difficulty;
                      });
                    },
                    borderRadius: BorderRadius.circular(16),
                    child: Container(
                      padding: const EdgeInsets.all(20),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(16),
                        border: Border.all(
                          color: isSelected ? info['color'] : Colors.grey[300]!,
                          width: isSelected ? 2 : 1,
                        ),
                        color: isSelected ? info['color'].withOpacity(0.1) : Colors.white,
                        boxShadow: isSelected
                            ? [
                                BoxShadow(
                                  color: info['color'].withOpacity(0.3),
                                  spreadRadius: 2,
                                  blurRadius: 8,
                                  offset: const Offset(0, 4),
                                ),
                              ]
                            : [
                                BoxShadow(
                                  color: Colors.grey.withOpacity(0.1),
                                  spreadRadius: 1,
                                  blurRadius: 4,
                                  offset: const Offset(0, 2),
                                ),
                              ],
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Container(
                                padding: const EdgeInsets.all(12),
                                decoration: BoxDecoration(
                                  color: info['color'].withOpacity(0.2),
                                  borderRadius: BorderRadius.circular(12),
                                ),
                                child: Icon(
                                  info['icon'],
                                  color: info['color'],
                                  size: 24,
                                ),
                              ),
                              const SizedBox(width: 16),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      children: [
                                        Text(
                                          info['title'],
                                          style: TextStyle(
                                            fontSize: 18,
                                            fontWeight: FontWeight.bold,
                                            color: isSelected ? info['color'] : Colors.black87,
                                          ),
                                        ),
                                        const SizedBox(width: 8),
                                        Container(
                                          padding: const EdgeInsets.symmetric(
                                            horizontal: 8,
                                            vertical: 4,
                                          ),
                                          decoration: BoxDecoration(
                                            color: info['color'].withOpacity(0.2),
                                            borderRadius: BorderRadius.circular(12),
                                          ),
                                          child: Text(
                                            info['level'],
                                            style: TextStyle(
                                              fontSize: 12,
                                              fontWeight: FontWeight.w600,
                                              color: info['color'],
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                    const SizedBox(height: 4),
                                    Text(
                                      '练习数量将基于后端加载',
                                      style: TextStyle(
                                        fontSize: 12,
                                        color: Colors.grey[600],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              if (isSelected)
                                Container(
                                  padding: const EdgeInsets.all(4),
                                  decoration: BoxDecoration(
                                    color: info['color'],
                                    shape: BoxShape.circle,
                                  ),
                                  child: const Icon(
                                    Icons.check,
                                    color: Colors.white,
                                    size: 16,
                                  ),
                                ),
                            ],
                          ),
                          
                          const SizedBox(height: 16),
                          
                          Text(
                            info['description'],
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.grey[700],
                              height: 1.4,
                            ),
                          ),
                          
                          const SizedBox(height: 16),
                          
                          // 特点标签
                          Wrap(
                            spacing: 8,
                            runSpacing: 8,
                            children: (info['features'] as List<String>).map((feature) {
                              return Container(
                                padding: const EdgeInsets.symmetric(
                                  horizontal: 12,
                                  vertical: 6,
                                ),
                                decoration: BoxDecoration(
                                  color: isSelected 
                                      ? info['color'].withOpacity(0.2)
                                      : Colors.grey[100],
                                  borderRadius: BorderRadius.circular(16),
                                  border: Border.all(
                                    color: isSelected 
                                        ? info['color'].withOpacity(0.3)
                                        : Colors.grey[300]!,
                                  ),
                                ),
                                child: Text(
                                  feature,
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: isSelected ? info['color'] : Colors.grey[600],
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              );
                            }).toList(),
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
          ),
          
          // 底部按钮
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.2),
                  spreadRadius: 1,
                  blurRadius: 4,
                  offset: const Offset(0, -2),
                ),
              ],
            ),
            child: Row(
              children: [
                Expanded(
                  child: OutlinedButton(
                    onPressed: () => Navigator.pop(context),
                    style: OutlinedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                    child: const Text('取消'),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: ElevatedButton(
                    onPressed: selectedDifficulty != null
                        ? () async {
                            final lp = ref.read(listeningProvider);
                            await lp.fetchExercises(
                              difficulty: selectedDifficulty,
                              page: 1,
                              limit: 1,
                              forceRefresh: true,
                            );
                            if (lp.exercises.isNotEmpty) {
                              final first = lp.exercises.first;
                              Navigator.pushNamed(
                                context,
                                Routes.listeningExerciseDetail,
                                arguments: {'exerciseId': first.id},
                              );
                            } else {
                              ScaffoldMessenger.of(context).showSnackBar(
                                const SnackBar(content: Text('该难度暂无练习材料')),
                              );
                            }
                          }
                        : null,
                    style: ElevatedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      backgroundColor: selectedDifficulty != null
                          ? difficultyInfo[selectedDifficulty]!['color']
                          : null,
                    ),
                    child: const Text(
                      '开始练习',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}