import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/word_model.dart';
import '../models/vocabulary_book_model.dart';
import '../providers/vocabulary_provider.dart';
import '../../../core/services/audio_service.dart';
import '../../../core/theme/app_colors.dart';

enum LearningMode { normal, review, test }

class WordLearningScreen extends ConsumerStatefulWidget {
  final VocabularyBook vocabularyBook;
  final List<Word>? specificWords;
  final LearningMode mode;

  const WordLearningScreen({
    super.key,
    required this.vocabularyBook,
    this.specificWords,
    this.mode = LearningMode.normal,
  });

  @override
  ConsumerState<WordLearningScreen> createState() => _WordLearningScreenState();
}

class _WordLearningScreenState extends ConsumerState<WordLearningScreen> {
  int _currentIndex = 0;
  bool _showMeaning = false;
  final AudioService _audioService = AudioService();
  Map<String, bool> _studyResults = {}; // 记录每个单词的学习结果
  List<Word> _words = [];

  @override
  void initState() {
    super.initState();
    _audioService.initialize();
    _words = widget.specificWords ?? [];
    
    // 如果没有指定单词，这里可以从 Provider 加载
    if (_words.isEmpty) {
      print('⚠️ 没有指定学习单词');
    }
  }

  @override
  void dispose() {
    _audioService.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_words.isEmpty) {
      return Scaffold(
        appBar: AppBar(
          title: Text(widget.vocabularyBook.name),
        ),
        body: const Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.book_outlined, size: 64, color: Colors.grey),
              SizedBox(height: 16),
              Text('暂无可学习的单词'),
            ],
          ),
        ),
      );
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.vocabularyBook.name),
        actions: [
          // 显示当前进度
          Center(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Text(
                '${_currentIndex + 1}/${_words.length}',
                style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          // 进度条
          LinearProgressIndicator(
            value: (_currentIndex + 1) / _words.length,
            backgroundColor: Colors.grey[200],
            valueColor: AlwaysStoppedAnimation<Color>(AppColors.primary),
          ),
          Expanded(
            child: _buildLearningCard(),
          ),
        ],
      ),
    );
  }

  Widget _buildLearningCard() {
    final word = _words[_currentIndex];
    // 根据学习模式判断：review模式为复习，其他为新词
    final isNewWord = widget.mode != LearningMode.review;
    
    return Container(
      color: Colors.grey[50],
      child: Column(
        children: [
          // 上半部分：单词卡片
          Expanded(
            flex: 3,
            child: Container(
              width: double.infinity,
              margin: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.08),
                    blurRadius: 20,
                    offset: const Offset(0, 4),
                  ),
                ],
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // 新词/复习标签
                  Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 8,
                    ),
                    decoration: BoxDecoration(
                      color: isNewWord 
                          ? Colors.orange.withOpacity(0.15)
                          : Colors.blue.withOpacity(0.15),
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          isNewWord ? Icons.fiber_new_rounded : Icons.refresh_rounded,
                          size: 18,
                          color: isNewWord ? Colors.orange[700] : Colors.blue[700],
                        ),
                        const SizedBox(width: 6),
                        Text(
                          isNewWord ? '新词' : '复习',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            color: isNewWord ? Colors.orange[700] : Colors.blue[700],
                          ),
                        ),
                      ],
                    ),
                  ),
                  
                  const SizedBox(height: 40),
                  
                  // 单词
                  Text(
                    word.word,
                    style: const TextStyle(
                      fontSize: 48,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFF2C3E50),
                      letterSpacing: 1.5,
                    ),
                  ),
                  
                  const SizedBox(height: 16),
                  
                  // 音标 + 发音按钮
                  if (word.phonetic != null)
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 20,
                        vertical: 10,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.grey[100],
                        borderRadius: BorderRadius.circular(25),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            word.phonetic!,
                            style: TextStyle(
                              fontSize: 18,
                              color: Colors.grey[700],
                              fontStyle: FontStyle.italic,
                            ),
                          ),
                          const SizedBox(width: 12),
                          InkWell(
                            onTap: () => _playAudio(word),
                            borderRadius: BorderRadius.circular(20),
                            child: Container(
                              padding: const EdgeInsets.all(8),
                              decoration: BoxDecoration(
                                color: AppColors.primary,
                                shape: BoxShape.circle,
                              ),
                              child: const Icon(
                                Icons.volume_up_rounded,
                                color: Colors.white,
                                size: 20,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  
                  const SizedBox(height: 40),
                  
                  // 显示释义按钮
                  if (!_showMeaning)
                    InkWell(
                      onTap: () {
                        setState(() {
                          _showMeaning = true;
                        });
                      },
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 32,
                          vertical: 14,
                        ),
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            colors: [AppColors.primary, AppColors.primary.withOpacity(0.8)],
                          ),
                          borderRadius: BorderRadius.circular(25),
                          boxShadow: [
                            BoxShadow(
                              color: AppColors.primary.withOpacity(0.3),
                              blurRadius: 12,
                              offset: const Offset(0, 4),
                            ),
                          ],
                        ),
                        child: const Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              Icons.visibility_rounded,
                              color: Colors.white,
                              size: 20,
                            ),
                            SizedBox(width: 8),
                            Text(
                              '点击查看释义',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                ],
              ),
            ),
          ),
          
          // 下半部分：释义内容（点击后显示）
          if (_showMeaning)
            Expanded(
              flex: 2,
              child: SingleChildScrollView(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: _buildMeaningContent(word),
                ),
              ),
            ),
          
          // 底部按钮区
          if (_showMeaning)
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 10,
                    offset: const Offset(0, -2),
                  ),
                ],
              ),
              child: _buildActionButtons(),
            ),
        ],
      ),
    );
  }

  List<Widget> _buildMeaningContent(Word word) {
    return [
      // 释义区域
      if (word.definitions.isNotEmpty) ...[
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16),
            border: Border.all(color: Colors.grey[200]!),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.book_rounded, size: 20, color: AppColors.primary),
                  const SizedBox(width: 8),
                  const Text(
                    '释义',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFF2C3E50),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 12),
              ...word.definitions.take(3).map((def) => Padding(
                padding: const EdgeInsets.only(bottom: 10),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      margin: const EdgeInsets.only(top: 6),
                      width: 6,
                      height: 6,
                      decoration: BoxDecoration(
                        color: AppColors.primary,
                        shape: BoxShape.circle,
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: RichText(
                        text: TextSpan(
                          style: const TextStyle(
                            fontSize: 15,
                            color: Color(0xFF2C3E50),
                            height: 1.5,
                          ),
                          children: [
                            TextSpan(
                              text: '${_getWordTypeText(def.type)} ',
                              style: TextStyle(
                                color: Colors.grey[600],
                                fontSize: 13,
                              ),
                            ),
                            TextSpan(text: def.translation),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              )),
            ],
          ),
        ),
        const SizedBox(height: 12),
      ],
      
      // 例句区域
      if (word.examples.isNotEmpty) ...[
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [
                Colors.blue[50]!,
                Colors.blue[50]!.withOpacity(0.5),
              ],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
            borderRadius: BorderRadius.circular(16),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.lightbulb_outline_rounded, size: 20, color: Colors.blue[700]),
                  const SizedBox(width: 8),
                  Text(
                    '例句',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.blue[700],
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 12),
              Text(
                word.examples.first.sentence,
                style: const TextStyle(
                  fontSize: 15,
                  fontStyle: FontStyle.italic,
                  color: Color(0xFF2C3E50),
                  height: 1.6,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                word.examples.first.translation,
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[700],
                  height: 1.5,
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),
      ],
    ];
  }

  Widget _buildActionButtons() {
    return Row(
      children: [
        Expanded(
          child: InkWell(
            onTap: () => _handleStudyResult(false),
            borderRadius: BorderRadius.circular(16),
            child: Container(
              padding: const EdgeInsets.symmetric(vertical: 16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(16),
                border: Border.all(color: Colors.red[400]!, width: 2),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.close_rounded, color: Colors.red[600], size: 24),
                  const SizedBox(width: 8),
                  Text(
                    '不认识',
                    style: TextStyle(
                      fontSize: 17,
                      fontWeight: FontWeight.w600,
                      color: Colors.red[600],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: InkWell(
            onTap: () => _handleStudyResult(true),
            borderRadius: BorderRadius.circular(16),
            child: Container(
              padding: const EdgeInsets.symmetric(vertical: 16),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Colors.green[400]!, Colors.green[600]!],
                ),
                borderRadius: BorderRadius.circular(16),
                boxShadow: [
                  BoxShadow(
                    color: Colors.green.withOpacity(0.3),
                    blurRadius: 8,
                    offset: const Offset(0, 4),
                  ),
                ],
              ),
              child: const Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.check_rounded, color: Colors.white, size: 24),
                  SizedBox(width: 8),
                  Text(
                    '认识',
                    style: TextStyle(
                      fontSize: 17,
                      fontWeight: FontWeight.w600,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  void _handleStudyResult(bool isKnown) {
    // 记录学习结果
    _studyResults[_words[_currentIndex].id] = isKnown;
    
    // 如果是最后一个单词，显示结果
    if (_currentIndex >= _words.length - 1) {
      _showResults();
    } else {
      // 下一个单词
      setState(() {
        _currentIndex++;
        _showMeaning = false;
      });
    }
  }

  void _showResults() {
    final knownCount = _studyResults.values.where((v) => v).length;
    final totalCount = _studyResults.length;
    final accuracy = totalCount > 0 ? (knownCount / totalCount * 100).round() : 0;
    
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: const Text('学习完成！'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.celebration,
              size: 64,
              color: accuracy >= 80 ? Colors.green : Colors.orange,
            ),
            const SizedBox(height: 16),
            Text(
              '正确率：$accuracy%',
              style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
            Text('认识 $knownCount/$totalCount 个单词'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(); // 关闭对话框
              Navigator.of(context).pop(_studyResults); // 返回结果
            },
            child: const Text('完成'),
          ),
        ],
      ),
    );
  }

  Future<void> _playAudio(Word word) async {
    try {
      if (word.audioUrl != null && word.audioUrl!.isNotEmpty) {
        await _audioService.playAudio(word.audioUrl!);
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('该单词暂无音频')),
        );
      }
    } catch (e) {
      print('播放音频失败: $e');
    }
  }

  String _getWordTypeText(WordType type) {
    switch (type) {
      case WordType.noun:
        return '名词';
      case WordType.verb:
        return '动词';
      case WordType.adjective:
        return '形容词';
      case WordType.adverb:
        return '副词';
      case WordType.preposition:
        return '介词';
      case WordType.conjunction:
        return '连词';
      case WordType.interjection:
        return '感叹词';
      case WordType.pronoun:
        return '代词';
      case WordType.article:
        return '冠词';
      case WordType.phrase:
        return '短语';
    }
  }

  Future<void> _saveProgress() async {
    final notifier = ref.read(vocabularyProvider.notifier);
    await notifier.loadUserVocabularyOverallStats();
    await notifier.loadWeeklyStudyStats();
  }
}
