import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/vocabulary_book_model.dart';
import '../models/vocabulary_book_category.dart';
import '../services/vocabulary_service.dart';
import '../providers/vocabulary_provider.dart';
import '../../../core/routes/app_routes.dart';
import '../../../core/network/api_client.dart';
import '../../../core/services/storage_service.dart';

class VocabularyCategoryScreen extends ConsumerStatefulWidget {
  final String category;

  const VocabularyCategoryScreen({
    super.key,
    required this.category,
  });

  @override
  ConsumerState<VocabularyCategoryScreen> createState() => _VocabularyCategoryScreenState();
}

class _VocabularyCategoryScreenState extends ConsumerState<VocabularyCategoryScreen> {
  List<VocabularyBook> _categoryBooks = [];
  bool _isLoading = true;
  String? _error;

  @override
  void initState() {
    super.initState();
    _loadCategoryBooks();
  }

  Future<void> _loadCategoryBooks() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      final apiClient = ApiClient.instance;
      final storageService = await StorageService.getInstance();
      final vocabularyService = VocabularyService(
        apiClient: apiClient,
        storageService: storageService,
      );

      // 从 API 获取该分类下的词书
      final books = await vocabularyService.getSystemVocabularyBooks(
        category: widget.category,
        limit: 100,
      );

      setState(() {
        _categoryBooks = books;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _error = e.toString();
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.category),
        centerTitle: true,
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (_error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.error_outline,
              size: 64,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              '加载失败',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 8),
            Text(
              _error!,
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey[400],
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _loadCategoryBooks,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (_categoryBooks.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.book_outlined,
              size: 64,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              '该分类下暂无词书',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 8),
            Text(
              '分类: ${widget.category}',
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey[400],
              ),
            ),
          ],
        ),
      );
    }

    return LayoutBuilder(
      builder: (context, constraints) {
        final isMobile = constraints.maxWidth < 600;
        return _buildBooksList(context, _categoryBooks, isMobile);
      },
    );
  }

  Widget _buildBooksList(BuildContext context, List<VocabularyBook> books, bool isMobile) {
    return GridView.builder(
      padding: EdgeInsets.all(isMobile ? 16.0 : 24.0),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: isMobile ? 2 : 3,
        crossAxisSpacing: 12,
        mainAxisSpacing: 12,
        childAspectRatio: isMobile ? 0.75 : 0.8,
      ),
      itemCount: books.length,
      itemBuilder: (context, index) {
        final book = books[index];
        return _buildBookCard(context, book, isMobile);
      },
    );
  }

  Widget _buildBookCard(BuildContext context, VocabularyBook book, bool isMobile) {
    final difficultyColor = _getDifficultyColor(book.difficulty);
    
    return GestureDetector(
      onTap: () => _navigateToBook(context, book),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.08),
              blurRadius: 12,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 顶部渐变封面区域
            Container(
              height: isMobile ? 120 : 140,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    difficultyColor.withOpacity(0.15),
                    difficultyColor.withOpacity(0.05),
                  ],
                ),
                borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
              ),
              child: Stack(
                children: [
                  // 装饰性图案
                  Positioned(
                    right: -20,
                    top: -20,
                    child: Icon(
                      Icons.auto_stories_outlined,
                      size: 100,
                      color: difficultyColor.withOpacity(0.1),
                    ),
                  ),
                  // 书本图标
                  Center(
                    child: Container(
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        shape: BoxShape.circle,
                        boxShadow: [
                          BoxShadow(
                            color: difficultyColor.withOpacity(0.2),
                            blurRadius: 8,
                            offset: const Offset(0, 2),
                          ),
                        ],
                      ),
                      child: Icon(
                        Icons.menu_book_rounded,
                        size: isMobile ? 32 : 40,
                        color: difficultyColor,
                      ),
                    ),
                  ),
                  // 难度标签
                  Positioned(
                    top: 12,
                    right: 12,
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                      decoration: BoxDecoration(
                        color: difficultyColor,
                        borderRadius: BorderRadius.circular(12),
                        boxShadow: [
                          BoxShadow(
                            color: difficultyColor.withOpacity(0.3),
                            blurRadius: 4,
                            offset: const Offset(0, 2),
                          ),
                        ],
                      ),
                      child: Text(
                        _getDifficultyText(book.difficulty),
                        style: const TextStyle(
                          fontSize: 11,
                          color: Colors.white,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            // 词书信息区域
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 词书名称
                    Text(
                      book.name,
                      style: TextStyle(
                        fontSize: isMobile ? 15 : 17,
                        fontWeight: FontWeight.bold,
                        color: const Color(0xFF2C3E50),
                        height: 1.3,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 8),
                    // 词汇量信息
                    Row(
                      children: [
                        Icon(
                          Icons.library_books_outlined,
                          size: 16,
                          color: Colors.grey[600],
                        ),
                        const SizedBox(width: 4),
                        Text(
                          '${book.totalWords} 词',
                          style: TextStyle(
                            fontSize: isMobile ? 13 : 14,
                            color: Colors.grey[700],
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 12),
                    // 学习进度
                    Consumer(
                      builder: (context, ref, child) {
                        final progressAsync = ref.watch(vocabularyBookProgressProvider(book.id));
                        return progressAsync.when(
                          data: (progress) {
                            final percentage = (progress.progressPercentage / 100.0).clamp(0.0, 1.0);
                            return Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(
                                      '学习进度',
                                      style: TextStyle(
                                        fontSize: 12,
                                        color: Colors.grey[600],
                                      ),
                                    ),
                                    Text(
                                      '${progress.progressPercentage.toStringAsFixed(0)}%',
                                      style: TextStyle(
                                        fontSize: 12,
                                        color: difficultyColor,
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                  ],
                                ),
                                const SizedBox(height: 6),
                                ClipRRect(
                                  borderRadius: BorderRadius.circular(10),
                                  child: LinearProgressIndicator(
                                    value: percentage,
                                    backgroundColor: difficultyColor.withOpacity(0.1),
                                    valueColor: AlwaysStoppedAnimation<Color>(difficultyColor),
                                    minHeight: 6,
                                  ),
                                ),
                              ],
                            );
                          },
                          loading: () => Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    '学习进度',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: Colors.grey[600],
                                    ),
                                  ),
                                  Text(
                                    '0%',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: difficultyColor,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 6),
                              ClipRRect(
                                borderRadius: BorderRadius.circular(10),
                                child: LinearProgressIndicator(
                                  value: 0,
                                  backgroundColor: difficultyColor.withOpacity(0.1),
                                  valueColor: AlwaysStoppedAnimation<Color>(difficultyColor),
                                  minHeight: 6,
                                ),
                              ),
                            ],
                          ),
                          error: (_, __) => Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    '学习进度',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: Colors.grey[600],
                                    ),
                                  ),
                                  Text(
                                    '0%',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: difficultyColor,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 6),
                              ClipRRect(
                                borderRadius: BorderRadius.circular(10),
                                child: LinearProgressIndicator(
                                  value: 0,
                                  backgroundColor: difficultyColor.withOpacity(0.1),
                                  valueColor: AlwaysStoppedAnimation<Color>(difficultyColor),
                                  minHeight: 6,
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                    const Spacer(),
                    // 底部操作区域
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                      decoration: BoxDecoration(
                        color: difficultyColor.withOpacity(0.08),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(
                            Icons.play_circle_outline,
                            size: 18,
                            color: difficultyColor,
                          ),
                          const SizedBox(width: 6),
                          Text(
                            '开始学习',
                            style: TextStyle(
                              fontSize: 13,
                              color: difficultyColor,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

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

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

  void _navigateToBook(BuildContext context, VocabularyBook book) {
    Navigator.pushNamed(
      context,
      Routes.vocabularyList,
      arguments: {'vocabularyBook': book},
    );
  }
}