import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/utils/responsive_utils.dart';
import '../../../shared/widgets/custom_app_bar.dart';
import '../../../shared/widgets/loading_widget.dart';
import '../../../shared/widgets/error_widget.dart' as custom;
import '../models/word_model.dart';
import '../models/vocabulary_book_model.dart';
import '../providers/vocabulary_provider.dart';
import '../../auth/providers/auth_provider.dart';
import 'word_learning_screen.dart';
import '../../../core/services/audio_service.dart';
import '../../../shared/services/word_book_service.dart' as shared;
import '../services/vocabulary_service.dart';
import '../../../core/services/storage_service.dart';
import '../../../core/network/api_client.dart';

class DailyWordsScreen extends ConsumerStatefulWidget {
  const DailyWordsScreen({super.key});

  @override
  ConsumerState<DailyWordsScreen> createState() => _DailyWordsScreenState();
}

class _DailyWordsScreenState extends ConsumerState<DailyWordsScreen> {
  bool _isLoading = false;
  List<Word> _dailyWords = [];
  int _currentIndex = 0;
  // 已学习的单词ID集合（从后端获取或学习后更新）
  Set<String> _learnedWordIds = {};
  // 今日学习统计（从后端获取）
  int _todayStudiedCount = 0;
  int _todayNewWords = 0;
  int _todayReviewWords = 0;
  // 音频服务
  final AudioService _audioService = AudioService();
  // 生词本服务
  shared.WordBookService? _wordBookService;
  // 收藏的单词ID集合
  Set<int> _favoriteWordIds = {};

  @override
  void initState() {
    super.initState();
    _initializeServices();
    _loadDailyWords();
    _loadTodayStatistics();  // 加载今日学习统计
  }

  Future<void> _initializeServices() async {
    try {
      await _audioService.initialize();
      _wordBookService = shared.WordBookService();
      await _loadFavoriteWords();
    } catch (e) {
      print('初始化服务失败: $e');
    }
  }

  Future<void> _loadFavoriteWords() async {
    if (_wordBookService == null) return;
    try {
      // 从后端获取生词本列表
      final result = await _wordBookService!.getFavoriteWords(pageSize: 1000);
      final List<dynamic> words = result['words'] ?? [];
      setState(() {
        _favoriteWordIds = words.map((w) => w['vocabulary_id'] as int).toSet();
      });
      print('✅ 已加载 ${_favoriteWordIds.length} 个收藏单词');
    } catch (e) {
      print('加载收藏单词失败: $e');
    }
  }

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

  Future<void> _loadDailyWords() async {
    setState(() {
      _isLoading = true;
    });

    try {
      print('=== 加载今日单词 ===');
      
      // 使用与首页一样的接口获取今日单词
      final apiClient = ApiClient.instance;
      final storageService = await StorageService.getInstance();
      final vocabularyService = VocabularyService(
        apiClient: apiClient,
        storageService: storageService,
      );
      
      // 调用getTodayStudyWords方法，获取今日学习单词（完整信息）
      final words = await vocabularyService.getTodayStudyWords(limit: 50);
      
      setState(() {
        _dailyWords = words;
        _isLoading = false;
      });
      print('✅ 今日单词加载完成，数量: ${words.length}');
    } catch (e) {
      print('❌ 加载今日单词异常: $e');
      setState(() {
        _dailyWords = [];
        _isLoading = false;
      });
    }
  }

  /// 加载今日学习统计
  Future<void> _loadTodayStatistics() async {
    try {
      final apiClient = ApiClient.instance;
      final response = await apiClient.get('/learning/today/statistics');
      
      if (response.statusCode == 200 && response.data['code'] == 200) {
        final data = response.data['data'];
        setState(() {
          _todayStudiedCount = (data['todayTotalStudied'] ?? 0).toInt();
          _todayNewWords = (data['todayNewWords'] ?? 0).toInt();
          _todayReviewWords = (data['todayReviewWords'] ?? 0).toInt();
        });
        print('✅ 今日学习统计: 新词$_todayNewWords + 复习$_todayReviewWords = 总计$_todayStudiedCount');
      }
    } catch (e) {
      print('❌ 加载今日学习统计失败: $e');
    }
  }

  void _startLearning() async {
    if (_dailyWords.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('暂无单词可学习')),
      );
      return;
    }

    // 创建一个临时的词汇书用于学习
    final vocabularyBook = VocabularyBook(
      id: 'daily_words',
      name: '今日单词',
      description: '今日推荐学习的单词',
      type: VocabularyBookType.system,
      difficulty: VocabularyBookDifficulty.beginner,
      totalWords: _dailyWords.length,
      createdAt: DateTime.now(),
      updatedAt: DateTime.now(),
    );

    final result = await Navigator.of(context).push<Map<String, dynamic>>(
      MaterialPageRoute(
        builder: (context) => WordLearningScreen(
          vocabularyBook: vocabularyBook,
          specificWords: _dailyWords,
          mode: LearningMode.normal,
        ),
      ),
    );

    // 从学习页面返回后更新进度
    if (result != null && result is Map<String, bool>) {
      _updateProgressFromLearningResult({'answers': result});
      _loadTodayStatistics();  // 重新加载今日统计（从后端获取最新数据）
    }
  }

  void _startReviewMode() async {
    // 获取已学习的单词
    final learnedWords = _dailyWords.where((word) => _learnedWordIds.contains(word.id)).toList();
    
    if (learnedWords.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('暂无已学单词可复习')),
      );
      return;
    }

    // 创建一个临时的词汇书用于复习
    final vocabularyBook = VocabularyBook(
      id: 'daily_words_review',
      name: '今日单词复习',
      description: '复习今日已学的单词',
      type: VocabularyBookType.system,
      difficulty: VocabularyBookDifficulty.beginner,
      totalWords: learnedWords.length,
      createdAt: DateTime.now(),
      updatedAt: DateTime.now(),
    );

    final result = await Navigator.of(context).push<Map<String, dynamic>>(
      MaterialPageRoute(
        builder: (context) => WordLearningScreen(
          vocabularyBook: vocabularyBook,
          specificWords: learnedWords,
          mode: LearningMode.review,
        ),
      ),
    );

    // 从复习页面返回后更新状态
    if (result != null && result is Map<String, bool>) {
      _updateProgressFromReviewResult({'answers': result});
      _loadTodayStatistics();  // 重新加载今日统计
    }
  }

  void _markAsLearned(int index) {
    setState(() {
      if (index < _dailyWords.length) {
        _learnedWordIds.add(_dailyWords[index].id);
      }
    });
  }

  void _updateProgressFromLearningResult(Map<String, dynamic> result) {
    final answers = result['answers'] as Map<String, bool>? ?? {};
    
    setState(() {
      // 将答对的单词ID添加到已学习集合
      answers.forEach((wordId, isCorrect) {
        if (isCorrect) {
          _learnedWordIds.add(wordId);
        }
      });
    });
    
    final learnedWordsCount = _learnedWordIds.length;

    // 显示学习结果提示
    final totalWords = answers.length;
    if (totalWords > 0) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('学习完成！掌握了 $learnedWordsCount/$totalWords 个单词'),
          backgroundColor: Colors.green,
          duration: const Duration(seconds: 3),
        ),
      );
    }
  }

  void _updateProgressFromReviewResult(Map<String, dynamic> result) {
    final answers = result['answers'] as Map<String, bool>? ?? {};
    final correctCount = answers.values.where((answer) => answer == true).length;
    final totalCount = answers.length;
    
    // 显示复习结果提示
    if (totalCount > 0) {
      final accuracy = (correctCount / totalCount * 100).round();
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('复习完成！正确率：$accuracy% ($correctCount/$totalCount)'),
          backgroundColor: accuracy >= 80 ? Colors.green : Colors.orange,
          duration: const Duration(seconds: 3),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final isMobile = ResponsiveUtils.isMobile(context);
    
    return Scaffold(
      appBar: CustomAppBar(
        title: '今日复习',
      ),
      body: _isLoading
          ? const LoadingWidget()
          : _buildContent(context, isMobile),
    );
  }

  Widget _buildEmptyState(BuildContext context, bool isMobile) {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(isMobile ? 32.0 : 48.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.book_outlined,
              size: isMobile ? 80 : 100,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 24),
            Text(
              '暂无今日单词',
              style: TextStyle(
                fontSize: isMobile ? 20 : 24,
                fontWeight: FontWeight.bold,
                color: Colors.grey[700],
              ),
            ),
            const SizedBox(height: 12),
            Text(
              '今天还没有推荐的学习单词',
              style: TextStyle(
                fontSize: isMobile ? 14 : 16,
                color: Colors.grey[600],
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 32),
            ElevatedButton.icon(
              onPressed: _loadDailyWords,
              icon: const Icon(Icons.refresh),
              label: const Text('重新加载'),
              style: ElevatedButton.styleFrom(
                padding: EdgeInsets.symmetric(
                  horizontal: isMobile ? 24 : 32,
                  vertical: isMobile ? 12 : 16,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildContent(BuildContext context, bool isMobile) {
    return SingleChildScrollView(
      padding: EdgeInsets.all(isMobile ? 16.0 : 24.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 学习统计（始终显示）
          _buildProgressSection(context, isMobile),
          const SizedBox(height: 24),
          
          // 如果有今日推荐单词，显示操作按钮和单词列表
          if (_dailyWords.isNotEmpty) ...[
            _buildActionButtons(context, isMobile),
            const SizedBox(height: 24),
            _buildWordsList(context, isMobile),
          ] else ...[
            // 没有今日需要复习的单词时的提示
            Center(
              child: Padding(
                padding: const EdgeInsets.all(32.0),
                child: Column(
                  children: [
                    Icon(
                      Icons.check_circle_outline,
                      size: 64,
                      color: Colors.green[400],
                    ),
                    const SizedBox(height: 16),
                    Text(
                      '今天没有需要复习的单词',
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.grey[700],
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      '继续保持！去词汇书页面学习新单词吧',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey[500],
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ],
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildProgressSection(BuildContext context, bool isMobile) {
    return Container(
      padding: EdgeInsets.all(isMobile ? 16.0 : 20.0),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.blue.shade400, Colors.blue.shade600],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.blue.withOpacity(0.3),
            blurRadius: 8,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.today,
                color: Colors.white,
                size: isMobile ? 24 : 28,
              ),
              const SizedBox(width: 12),
              Text(
                '今日学习进度',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: isMobile ? 18 : 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '$_todayStudiedCount 个单词',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: isMobile ? 16 : 18,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      '新词 $_todayNewWords + 复习 $_todayReviewWords',
                      style: TextStyle(
                        color: Colors.white.withOpacity(0.9),
                        fontSize: isMobile ? 12 : 14,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 16),
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.2),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  Icons.check_circle,
                  color: Colors.white,
                  size: isMobile ? 32 : 40,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildActionButtons(BuildContext context, bool isMobile) {
    return Row(
      children: [
        Expanded(
          child: ElevatedButton.icon(
            onPressed: _startLearning,
            icon: const Icon(Icons.play_arrow),
            label: const Text('开始学习'),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.green,
              foregroundColor: Colors.white,
              padding: EdgeInsets.symmetric(
                vertical: isMobile ? 12 : 16,
                horizontal: isMobile ? 16 : 24,
              ),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
            ),
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: OutlinedButton.icon(
            onPressed: _startReviewMode,
            icon: const Icon(Icons.refresh),
            label: const Text('复习模式'),
            style: OutlinedButton.styleFrom(
              foregroundColor: Colors.blue,
              padding: EdgeInsets.symmetric(
                vertical: isMobile ? 12 : 16,
                horizontal: isMobile ? 16 : 24,
              ),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildWordsList(BuildContext context, bool isMobile) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '单词列表',
          style: TextStyle(
            fontSize: isMobile ? 18 : 20,
            fontWeight: FontWeight.bold,
            color: Colors.grey[800],
          ),
        ),
        const SizedBox(height: 16),
        ListView.separated(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemCount: _dailyWords.length,
          separatorBuilder: (context, index) => const SizedBox(height: 12),
          itemBuilder: (context, index) {
            return _buildWordCard(context, _dailyWords[index], index, isMobile);
          },
        ),
      ],
    );
  }

  Widget _buildWordCard(BuildContext context, Word word, int index, bool isMobile) {
    final isLearned = _learnedWordIds.contains(word.id);
    
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: Padding(
        padding: EdgeInsets.all(isMobile ? 16.0 : 20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            word.word,
                            style: TextStyle(
                              fontSize: isMobile ? 18 : 20,
                              fontWeight: FontWeight.bold,
                              color: isLearned ? Colors.green : Colors.grey[800],
                            ),
                          ),
                          const SizedBox(width: 8),
                          if (isLearned)
                            Icon(
                              Icons.check_circle,
                              color: Colors.green,
                              size: isMobile ? 20 : 24,
                            ),
                        ],
                      ),
                      const SizedBox(height: 4),
                      if (word.phonetic != null)
                        Text(
                          word.phonetic!,
                          style: TextStyle(
                            fontSize: isMobile ? 14 : 16,
                            color: Colors.blue[600],
                            fontStyle: FontStyle.italic,
                          ),
                        ),
                    ],
                  ),
                ),
                Row(
                  children: [
                    IconButton(
                      onPressed: () => _playWordAudio(word),
                      icon: const Icon(Icons.volume_up),
                      color: Colors.blue,
                      tooltip: '播放发音',
                    ),
                    IconButton(
                      onPressed: () => _toggleFavorite(word),
                      icon: Icon(
                        _favoriteWordIds.contains(int.tryParse(word.id))
                            ? Icons.favorite
                            : Icons.favorite_border,
                      ),
                      color: Colors.red,
                      tooltip: _favoriteWordIds.contains(int.tryParse(word.id)) ? '取消收藏' : '收藏单词',
                    ),
                  ],
                ),
              ],
            ),
            const SizedBox(height: 12),
            if (word.definitions.isNotEmpty)
              Text(
                word.definitions.first.translation,
                style: TextStyle(
                  fontSize: isMobile ? 14 : 16,
                  color: Colors.grey[700],
                ),
              ),
            const SizedBox(height: 8),
            if (word.examples.isNotEmpty)
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.grey[50],
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.grey[200]!),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      word.examples.first.sentence,
                      style: TextStyle(
                        fontSize: isMobile ? 13 : 15,
                        fontStyle: FontStyle.italic,
                        color: Colors.grey[800],
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      word.examples.first.translation,
                      style: TextStyle(
                        fontSize: isMobile ? 12 : 14,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
              ),
            const SizedBox(height: 12),
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: _getDifficultyColor(word.difficulty).withOpacity(0.1),
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(
                      color: _getDifficultyColor(word.difficulty),
                      width: 1,
                    ),
                  ),
                  child: Text(
                    _getDifficultyText(word.difficulty),
                    style: TextStyle(
                      fontSize: 12,
                      color: _getDifficultyColor(word.difficulty),
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: Colors.blue.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Text(
                    _getCategoryText(word.definitions.isNotEmpty ? word.definitions.first.type : WordType.noun),
                    style: const TextStyle(
                      fontSize: 12,
                      color: Colors.blue,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                const Spacer(),
                if (!isLearned)
                  TextButton(
                    onPressed: () => _markAsLearned(index),
                    child: const Text('标记已学'),
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }

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

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

  String _getCategoryText(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> _playWordAudio(Word word) async {
    try {
      if (word.audioUrl != null && word.audioUrl!.isNotEmpty) {
        await _audioService.playAudio(word.audioUrl!);
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Row(
                children: [
                  const Icon(Icons.volume_up, color: Colors.white, size: 20),
                  const SizedBox(width: 8),
                  Text('正在播放: ${word.word}'),
                ],
              ),
              duration: const Duration(seconds: 2),
              backgroundColor: Colors.blue,
            ),
          );
        }
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('该单词暂无音频'),
              duration: Duration(seconds: 2),
            ),
          );
        }
      }
    } catch (e) {
      print('播放音频失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('播放失败'),
            duration: Duration(seconds: 2),
          ),
        );
      }
    }
  }

  Future<void> _toggleFavorite(Word word) async {
    if (_wordBookService == null) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('生词本服务正在初始化，请稍后再试'),
            duration: Duration(seconds: 2),
            backgroundColor: Colors.orange,
          ),
        );
      }
      return;
    }

    try {
      // 调用后端 API 切换收藏状态
      final wordId = int.tryParse(word.id);
      if (wordId == null) {
        throw Exception('无效的单词 ID');
      }

      final result = await _wordBookService!.toggleFavorite(wordId);
      final isFavorite = result['is_favorite'] as bool;
      
      setState(() {
        if (isFavorite) {
          _favoriteWordIds.add(wordId);
        } else {
          _favoriteWordIds.remove(wordId);
        }
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(isFavorite ? '已添加到生词本: ${word.word}' : '已从生词本移除: ${word.word}'),
            duration: const Duration(seconds: 2),
            backgroundColor: isFavorite ? Colors.green : Colors.orange,
          ),
        );
      }
    } catch (e) {
      print('操作生词本失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('操作失败: ${e.toString()}'),
            duration: const Duration(seconds: 2),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }
}