import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/reading_exercise_model.dart';
import '../providers/reading_provider.dart';
import 'reading_exercise_screen.dart';

/// 阅读分类页面
class ReadingCategoryScreen extends ConsumerStatefulWidget {
  final ReadingExerciseType exerciseType;

  const ReadingCategoryScreen({
    super.key,
    required this.exerciseType,
  });

  @override
  ConsumerState<ReadingCategoryScreen> createState() => _ReadingCategoryScreenState();
}

class _ReadingCategoryScreenState extends ConsumerState<ReadingCategoryScreen> {
  ReadingDifficulty? selectedDifficulty;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadRemote();
    });
  }

  void _loadRemote() {
    final cat = _typeToCategory(widget.exerciseType);
    final level = selectedDifficulty != null ? _difficultyToLevel(selectedDifficulty!) : null;
    ref.read(readingMaterialsProvider.notifier).loadMaterials(
      category: cat,
      difficulty: level,
      page: 1,
    );
  }

  void _filterExercises() {
    _loadRemote();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.black87),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text(
          _categoryLabel(widget.exerciseType),
          style: const TextStyle(
            color: Colors.black87,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: true,
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          _loadRemote();
        },
        child: Column(
          children: [
            _buildFilterSection(),
            Expanded(
              child: _buildExercisesList(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildFilterSection() {
    return Container(
      width: double.infinity,
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(16),
      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: LayoutBuilder(
        builder: (context, constraints) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                '根据难度筛选文章',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey,
                ),
              ),
              const SizedBox(height: 16),
              const Text(
                '难度筛选',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              // 响应式难度筛选布局
              constraints.maxWidth > 600
                  ? Row(
                      children: [
                        _buildDifficultyChip('全部', null),
                        const SizedBox(width: 8),
                        ...ReadingDifficulty.values.map((difficulty) => 
                          Padding(
                            padding: const EdgeInsets.only(right: 8),
                            child: _buildDifficultyChip(_getDifficultyName(difficulty), difficulty),
                          ),
                        ),
                      ],
                    )
                  : Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: [
                        _buildDifficultyChip('全部', null),
                        ...ReadingDifficulty.values.map((difficulty) =>
                            _buildDifficultyChip(_getDifficultyName(difficulty), difficulty)),
                      ],
                    ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildDifficultyChip(String label, ReadingDifficulty? difficulty) {
    final isSelected = selectedDifficulty == difficulty;
    return FilterChip(
      label: Text(label),
      selected: isSelected,
      onSelected: (selected) {
        setState(() {
          selectedDifficulty = selected ? difficulty : null;
          _loadRemote();
        });
      },
      selectedColor: const Color(0xFF2196F3).withOpacity(0.2),
      checkmarkColor: const Color(0xFF2196F3),
    );
  }

  Widget _buildExercisesList() {
    final state = ref.watch(readingMaterialsProvider);
    if (state.isLoading) {
      return const Center(child: CircularProgressIndicator());
    }
    if (state.error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, size: 64, color: Colors.redAccent),
            const SizedBox(height: 16),
            Text('加载失败: ${state.error}', style: const TextStyle(color: Colors.redAccent)),
            const SizedBox(height: 8),
            TextButton(
              onPressed: _loadRemote,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    final exercises = state.materials;
    if (exercises.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.book_outlined,
              size: 64,
              color: Colors.grey,
            ),
            SizedBox(height: 16),
            Text(
              '暂无相关练习',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey,
              ),
            ),
          ],
        ),
      );
    }

    return LayoutBuilder(
      builder: (context, constraints) {
        if (constraints.maxWidth > 800) {
          return _buildGridLayout(exercises);
        } else {
          return _buildListLayout(exercises);
        }
      },
    );
  }

  Widget _buildListLayout(List<ReadingExercise> exercises) {
    return ListView.builder(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      itemCount: exercises.length,
      itemBuilder: (context, index) {
        final exercise = exercises[index];
        return Padding(
          padding: const EdgeInsets.only(bottom: 12),
          child: _buildExerciseCard(exercise),
        );
      },
    );
  }

  Widget _buildGridLayout(List<ReadingExercise> exercises) {
    return GridView.builder(
      padding: const EdgeInsets.all(16),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: _getCrossAxisCount(MediaQuery.of(context).size.width),
        crossAxisSpacing: 16,
        mainAxisSpacing: 16,
        childAspectRatio: 1.2,
      ),
      itemCount: exercises.length,
      itemBuilder: (context, index) {
        final exercise = exercises[index];
        return _buildExerciseCard(exercise);
      },
    );
  }

  int _getCrossAxisCount(double width) {
    if (width > 1200) return 3;
    if (width > 800) return 2;
    return 1;
  }

  Widget _buildExerciseCard(ReadingExercise exercise) {
    return GestureDetector(
      onTap: () => _navigateToExercise(exercise),
      child: Container(
        padding: const EdgeInsets.all(16),
        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: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Expanded(
                  child: Text(
                    exercise.title,
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: _getDifficultyColor(exercise.difficulty),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Text(
                    _getDifficultyLabel(exercise.difficulty),
                    style: const TextStyle(
                      fontSize: 12,
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Text(
              exercise.summary,
              style: const TextStyle(
                fontSize: 14,
                color: Colors.grey,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
            const SizedBox(height: 12),
            Row(
              children: [
                Icon(
                  Icons.access_time,
                  size: 16,
                  color: Colors.grey[600],
                ),
                const SizedBox(width: 4),
                Text(
                  '${exercise.estimatedTime}分钟',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
                const SizedBox(width: 16),
                Icon(
                  Icons.text_fields,
                  size: 16,
                  color: Colors.grey[600],
                ),
                const SizedBox(width: 4),
                Text(
                  '${exercise.wordCount}词',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
                const SizedBox(width: 16),
                Icon(
                  Icons.quiz,
                  size: 16,
                  color: Colors.grey[600],
                ),
                const SizedBox(width: 4),
                Text(
                  '${exercise.questions.length}题',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
            if (exercise.tags.isNotEmpty) ...[
              const SizedBox(height: 8),
              Wrap(
                spacing: 4,
                children: exercise.tags.take(3).map((tag) => Container(
                  padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                  decoration: BoxDecoration(
                    color: Colors.grey[200],
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Text(
                    tag,
                    style: const TextStyle(
                      fontSize: 10,
                      color: Colors.grey,
                    ),
                  ),
                )).toList(),
              ),
            ],
          ],
        ),
      ),
    );
  }

  String _getDifficultyName(ReadingDifficulty difficulty) {
    switch (difficulty) {
      case ReadingDifficulty.elementary:
        return '初级 (A1)';
      case ReadingDifficulty.intermediate:
        return '中级 (B1)';
      case ReadingDifficulty.upperIntermediate:
        return '中高级 (B2)';
      case ReadingDifficulty.advanced:
        return '高级 (C1)';
      case ReadingDifficulty.proficient:
        return '精通 (C2)';
    }
  }

  String _getDifficultyLabel(ReadingDifficulty difficulty) {
    switch (difficulty) {
      case ReadingDifficulty.elementary:
        return 'A1';
      case ReadingDifficulty.intermediate:
        return 'B1';
      case ReadingDifficulty.upperIntermediate:
        return 'B2';
      case ReadingDifficulty.advanced:
        return 'C1';
      case ReadingDifficulty.proficient:
        return 'C2';
    }
  }

  Color _getDifficultyColor(ReadingDifficulty difficulty) {
    switch (difficulty) {
      case ReadingDifficulty.elementary:
        return Colors.green;
      case ReadingDifficulty.intermediate:
        return Colors.blue;
      case ReadingDifficulty.upperIntermediate:
        return Colors.orange;
      case ReadingDifficulty.advanced:
        return Colors.red;
      case ReadingDifficulty.proficient:
        return Colors.purple;
    }
  }

  String _typeToCategory(ReadingExerciseType type) {
    switch (type) {
      case ReadingExerciseType.news:
        return 'news';
      case ReadingExerciseType.story:
        return 'story';
      case ReadingExerciseType.science:
        return 'science';
      case ReadingExerciseType.business:
        return 'business';
      case ReadingExerciseType.culture:
        return 'culture';
      case ReadingExerciseType.technology:
        return 'technology';
      case ReadingExerciseType.health:
        return 'health';
      case ReadingExerciseType.travel:
        return 'travel';
    }
  }

  String _difficultyToLevel(ReadingDifficulty difficulty) {
    switch (difficulty) {
      case ReadingDifficulty.elementary:
        return 'elementary';
      case ReadingDifficulty.intermediate:
        return 'intermediate';
      case ReadingDifficulty.upperIntermediate:
        return 'upper-intermediate';
      case ReadingDifficulty.advanced:
        return 'advanced';
      case ReadingDifficulty.proficient:
        return 'proficient';
    }
  }

  String _categoryLabel(ReadingExerciseType type) {
    switch (type) {
      case ReadingExerciseType.news:
        return '新闻';
      case ReadingExerciseType.story:
        return '故事';
      case ReadingExerciseType.science:
        return '科学';
      case ReadingExerciseType.business:
        return '商务';
      case ReadingExerciseType.culture:
        return '文化';
      case ReadingExerciseType.technology:
        return '科技';
      case ReadingExerciseType.health:
        return '健康';
      case ReadingExerciseType.travel:
        return '旅游';
    }
  }

  void _navigateToExercise(ReadingExercise exercise) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ReadingExerciseScreen(exercise: exercise),
      ),
    );
  }
}