import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../shared/services/word_book_service.dart';
import '../../../core/services/tts_service.dart';

/// 生词本页面
class WordBookScreen extends ConsumerStatefulWidget {
  const WordBookScreen({super.key});

  @override
  ConsumerState<WordBookScreen> createState() => _WordBookScreenState();
}

class _WordBookScreenState extends ConsumerState<WordBookScreen> {
  final TTSService _ttsService = TTSService();
  bool _isLoading = true;
  List<dynamic> _words = [];
  Map<String, dynamic>? _stats;
  int _currentPage = 1;
  final int _pageSize = 20;
  String _sortBy = 'created_at';
  String _order = 'desc';

  @override
  void initState() {
    super.initState();
    _ttsService.initialize();
    _loadData();
  }

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

  Future<void> _loadData() async {
    setState(() => _isLoading = true);
    
    try {
      final wordBookService = ref.read(wordBookServiceProvider);
      
      // 加载生词列表
      final wordsData = await wordBookService.getFavoriteWords(
        page: _currentPage,
        pageSize: _pageSize,
        sortBy: _sortBy,
        order: _order,
      );
      
      // 加载统计信息
      final stats = await wordBookService.getFavoriteStats();
      
      setState(() {
        _words = wordsData['words'];
        _stats = stats;
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载失败: $e')),
        );
      }
    }
  }

  Future<void> _removeWord(int wordId) async {
    try {
      final wordBookService = ref.read(wordBookServiceProvider);
      await wordBookService.removeFromFavorite(wordId);
      
      _loadData(); // 刷新列表
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('已从生词本移除')),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('移除失败: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
        title: const Text('生词本'),
        backgroundColor: const Color(0xFF2196F3),
        foregroundColor: Colors.white,
        actions: [
          PopupMenuButton<String>(
            onSelected: (value) {
              setState(() {
                if (value == 'proficiency_asc') {
                  _sortBy = 'proficiency';
                  _order = 'asc';
                } else if (value == 'proficiency_desc') {
                  _sortBy = 'proficiency';
                  _order = 'desc';
                } else if (value == 'word_asc') {
                  _sortBy = 'word';
                  _order = 'asc';
                } else if (value == 'created_at_desc') {
                  _sortBy = 'created_at';
                  _order = 'desc';
                }
                _currentPage = 1;
                _loadData();
              });
            },
            itemBuilder: (context) => [
              const PopupMenuItem(
                value: 'created_at_desc',
                child: Text('按添加时间排序'),
              ),
              const PopupMenuItem(
                value: 'proficiency_asc',
                child: Text('按熟练度（低到高）'),
              ),
              const PopupMenuItem(
                value: 'proficiency_desc',
                child: Text('按熟练度（高到低）'),
              ),
              const PopupMenuItem(
                value: 'word_asc',
                child: Text('按单词字母排序'),
              ),
            ],
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : RefreshIndicator(
              onRefresh: _loadData,
              child: Column(
                children: [
                  if (_stats != null) _buildStatsCard(),
                  Expanded(
                    child: _words.isEmpty
                        ? _buildEmptyState()
                        : _buildWordList(),
                  ),
                ],
              ),
            ),
    );
  }

  Widget _buildStatsCard() {
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '学习统计',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: _buildStatItem(
                  '总词数',
                  _stats!['total_words'].toString(),
                  Icons.book,
                  const Color(0xFF2196F3),
                ),
              ),
              Expanded(
                child: _buildStatItem(
                  '已掌握',
                  _stats!['mastered_words'].toString(),
                  Icons.check_circle,
                  const Color(0xFF4CAF50),
                ),
              ),
              Expanded(
                child: _buildStatItem(
                  '复习中',
                  _stats!['reviewing_words'].toString(),
                  Icons.loop,
                  const Color(0xFFFF9800),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon, Color color) {
    return Column(
      children: [
        Icon(icon, color: color, size: 24),
        const SizedBox(height: 8),
        Text(
          value,
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: const TextStyle(fontSize: 12, color: Colors.grey),
        ),
      ],
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.bookmark_border,
            size: 64,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            '生词本为空',
            style: TextStyle(
              fontSize: 18,
              color: Colors.grey[600],
              fontWeight: FontWeight.w500,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '在学习时点击收藏按钮添加生词',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[500],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildWordList() {
    return ListView.builder(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      itemCount: _words.length,
      itemBuilder: (context, index) {
        final word = _words[index];
        return _buildWordCard(word);
      },
    );
  }

  Widget _buildWordCard(Map<String, dynamic> word) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: ListTile(
        contentPadding: const EdgeInsets.all(16),
        title: Row(
          children: [
            Expanded(
              child: Text(
                word['word'] ?? '',
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            if (word['phonetic'] != null)
              Text(
                word['phonetic'],
                style: const TextStyle(
                  fontSize: 14,
                  color: Colors.grey,
                ),
              ),
          ],
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 8),
            if (word['definitions'] != null)
              Text(
                word['definitions'],
                style: const TextStyle(fontSize: 14),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            const SizedBox(height: 8),
            Row(
              children: [
                _buildLevelBadge(word['level']),
                const SizedBox(width: 8),
                Text(
                  '熟练度: ${word['proficiency'] ?? 0}%',
                  style: TextStyle(
                    fontSize: 12,
                    color: _getProficiencyColor(word['proficiency'] ?? 0),
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ],
        ),
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            IconButton(
              icon: const Icon(Icons.volume_up, color: Color(0xFF2196F3)),
              onPressed: () async {
                await _ttsService.speak(word['word'] ?? '');
              },
            ),
            IconButton(
              icon: const Icon(Icons.delete, color: Colors.red),
              onPressed: () {
                showDialog(
                  context: context,
                  builder: (context) => AlertDialog(
                    title: const Text('确认移除'),
                    content: Text('确定要将"${word['word']}"从生词本移除吗？'),
                    actions: [
                      TextButton(
                        onPressed: () => Navigator.pop(context),
                        child: const Text('取消'),
                      ),
                      TextButton(
                        onPressed: () {
                          Navigator.pop(context);
                          _removeWord(word['id']);
                        },
                        child: const Text('确定'),
                      ),
                    ],
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLevelBadge(String? level) {
    Color color;
    String text;
    
    switch (level) {
      case 'beginner':
        color = const Color(0xFF4CAF50);
        text = '初级';
        break;
      case 'intermediate':
        color = const Color(0xFF2196F3);
        text = '中级';
        break;
      case 'advanced':
        color = const Color(0xFFFF9800);
        text = '高级';
        break;
      default:
        color = Colors.grey;
        text = '未知';
    }
    
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        text,
        style: TextStyle(
          fontSize: 11,
          color: color,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  Color _getProficiencyColor(int proficiency) {
    if (proficiency >= 80) return const Color(0xFF4CAF50);
    if (proficiency >= 60) return const Color(0xFF2196F3);
    if (proficiency >= 40) return const Color(0xFFFF9800);
    return const Color(0xFFF44336);
  }
}
