import 'package:flutter/material.dart';
import '../../../core/routes/app_routes.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers/listening_provider.dart';
import '../models/listening_exercise_model.dart';

class ListeningCategory {
  final String id;
  final String name;
  final String description;
  final IconData icon;
  final int exerciseCount;
  final ListeningExerciseType type;

  const ListeningCategory({
    required this.id,
    required this.name,
    required this.description,
    required this.icon,
    required this.exerciseCount,
    required this.type,
  });
}

/// 听力材料分类页面
class ListeningCategoryScreen extends ConsumerStatefulWidget {
  final ListeningCategory category;

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

  @override
  ConsumerState<ListeningCategoryScreen> createState() => _ListeningCategoryScreenState();
}

class _ListeningCategoryScreenState extends ConsumerState<ListeningCategoryScreen> {
  String selectedFilter = '全部';
  List<ListeningExercise> filteredExercises = [];
  bool _requested = false;

  @override
  void initState() {
    super.initState();
    _initializeExercises();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!_requested) {
        _requested = true;
        ref.read(listeningProvider).fetchExercises(
          type: widget.category.type,
          page: 1,
          limit: 50,
        );
      }
    });
  }

  void _initializeExercises() {
    setState(() {
      filteredExercises = [];
    });
  }

  void _applyFilter(String filter) {
    setState(() {
      selectedFilter = filter;
      final allExercises = filteredExercises;
      
      switch (filter) {
        case '全部':
          filteredExercises = allExercises;
          break;
        case '入门':
          filteredExercises = allExercises.where((e) => e.difficulty == ListeningDifficulty.beginner).toList();
          break;
        case '初级':
          filteredExercises = allExercises.where((e) => e.difficulty == ListeningDifficulty.elementary).toList();
          break;
        case '中级':
          filteredExercises = allExercises.where((e) => e.difficulty == ListeningDifficulty.intermediate).toList();
          break;
        case '高级':
          filteredExercises = allExercises.where((e) => e.difficulty == ListeningDifficulty.advanced).toList();
          break;
        case '专家':
          filteredExercises = allExercises.where((e) => e.difficulty == ListeningDifficulty.expert).toList();
          break;
        case '最新':
          filteredExercises = List.from(allExercises)..sort((a, b) => b.id.compareTo(a.id));
          break;
        case '热门':
          filteredExercises = List.from(allExercises)..sort((a, b) => b.playCount.compareTo(a.playCount));
          break;
        default:
          filteredExercises = allExercises;
      }
    });
  }

  @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(
          widget.category.name,
          style: const TextStyle(
            color: Colors.black87,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildCategoryHeader(),
              const SizedBox(height: 20),
              _buildFilterSection(),
              const SizedBox(height: 20),
              Consumer(
                builder: (context, ref, _) {
                  final lp = ref.watch(listeningProvider);
                  final all = lp.exercises.where((e) => e.type == widget.category.type).toList();
                  final exercises = _applyCurrentFilter(all);
                  filteredExercises = exercises;
                  return _buildExercisesList(
                    context,
                    exercises,
                    onRefresh: () async {
                      await ref.read(listeningProvider).fetchExercises(
                        type: widget.category.type,
                        page: 1,
                        limit: 50,
                        forceRefresh: true,
                      );
                    },
                  );
                },
              ),
              const SizedBox(height: 100), // 底部导航栏空间
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildCategoryHeader() {
    return Container(
      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: Row(
        children: [
          Container(
            width: 60,
            height: 60,
            decoration: BoxDecoration(
              color: _getTypeColor(widget.category.type).withOpacity(0.1),
              borderRadius: BorderRadius.circular(30),
            ),
            child: Icon(
              widget.category.icon,
              color: _getTypeColor(widget.category.type),
              size: 30,
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  widget.category.name,
                  style: const TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  widget.category.description,
                  style: const TextStyle(
                    fontSize: 14,
                    color: Colors.grey,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  '${filteredExercises.length} 个练习',
                  style: TextStyle(
                    fontSize: 12,
                    color: _getTypeColor(widget.category.type),
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFilterSection() {
    return Container(
      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: _buildFilterChip('全部', selectedFilter == '全部'),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _buildFilterChip('入门', selectedFilter == '入门'),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _buildFilterChip('初级', selectedFilter == '初级'),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _buildFilterChip('中级', selectedFilter == '中级'),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Row(
            children: [
              Expanded(
                child: _buildFilterChip('高级', selectedFilter == '高级'),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _buildFilterChip('专家', selectedFilter == '专家'),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _buildFilterChip('最新', selectedFilter == '最新'),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _buildFilterChip('热门', selectedFilter == '热门'),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildFilterChip(String label, bool isSelected) {
    return GestureDetector(
      onTap: () => _applyFilter(label),
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
        decoration: BoxDecoration(
          color: isSelected ? _getTypeColor(widget.category.type) : Colors.grey[100],
          borderRadius: BorderRadius.circular(20),
          border: isSelected
              ? Border.all(
                  color: _getTypeColor(widget.category.type),
                  width: 2,
                )
              : null,
        ),
        child: Text(
          label,
          textAlign: TextAlign.center,
          style: TextStyle(
            fontSize: 12,
            color: isSelected ? Colors.white : Colors.grey[600],
            fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
          ),
        ),
      ),
    );
  }

  Widget _buildExercisesList(BuildContext context, List<ListeningExercise> exercises, {Future<void> Function()? onRefresh}) {
    return Container(
      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: [
          Text(
            '练习列表 (${exercises.length})',
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          if (exercises.isEmpty)
            Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Icon(Icons.inbox, size: 36, color: Colors.grey),
                  const SizedBox(height: 8),
                  const Text(
                    '暂无练习',
                    style: TextStyle(fontSize: 14, color: Colors.grey),
                  ),
                  const SizedBox(height: 12),
                  ElevatedButton.icon(
                    onPressed: onRefresh,
                    icon: const Icon(Icons.refresh, size: 16),
                    label: const Text('刷新'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color(0xFF2196F3),
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                    ),
                  ),
                ],
              ),
            )
          else
            ...exercises.map((exercise) => _buildExerciseItem(context, exercise)).toList(),
        ],
      ),
    );
  }

  Widget _buildExerciseItem(BuildContext context, ListeningExercise exercise) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: InkWell(
        onTap: () {
          Navigator.of(context).pushNamed(
            Routes.listeningExerciseDetail,
            arguments: {'exerciseId': exercise.id},
          );
        },
        child: Row(
          children: [
            Container(
              width: 50,
              height: 50,
              decoration: BoxDecoration(
                color: _getTypeColor(widget.category.type).withOpacity(0.1),
                borderRadius: BorderRadius.circular(25),
              ),
              child: const Icon(
                Icons.play_arrow,
                color: Color(0xFF2196F3),
                size: 24,
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    exercise.title,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    exercise.description,
                    style: const TextStyle(
                      fontSize: 12,
                      color: Colors.grey,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      _buildTag(_getDifficultyText(exercise.difficulty)),
                      const SizedBox(width: 8),
                      _buildTag('${exercise.duration ~/ 60}分钟'),
                      const SizedBox(width: 8),
                      _buildTag('${exercise.questions.length}题'),
                    ],
                  ),
                ],
              ),
            ),
            Column(
              children: [
                Row(
                  children: [
                    const Icon(
                      Icons.star,
                      color: Colors.amber,
                      size: 16,
                    ),
                    const SizedBox(width: 4),
                    Text(
                      exercise.rating.toStringAsFixed(1),
                      style: const TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 4),
                Text(
                  '${exercise.playCount}次播放',
                  style: const TextStyle(
                    fontSize: 10,
                    color: Colors.grey,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTag(String text) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: _getTypeColor(widget.category.type).withOpacity(0.1),
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        text,
        style: TextStyle(
          fontSize: 10,
          color: _getTypeColor(widget.category.type),
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  List<ListeningExercise> _applyCurrentFilter(List<ListeningExercise> allExercises) {
    switch (selectedFilter) {
      case '全部':
        return allExercises;
      case '入门':
        return allExercises.where((e) => e.difficulty == ListeningDifficulty.beginner).toList();
      case '初级':
        return allExercises.where((e) => e.difficulty == ListeningDifficulty.elementary).toList();
      case '中级':
        return allExercises.where((e) => e.difficulty == ListeningDifficulty.intermediate).toList();
      case '高级':
        return allExercises.where((e) => e.difficulty == ListeningDifficulty.advanced).toList();
      case '专家':
        return allExercises.where((e) => e.difficulty == ListeningDifficulty.expert).toList();
      case '最新':
        return List.from(allExercises)..sort((a, b) => b.updatedAt.compareTo(a.updatedAt));
      case '热门':
        return List.from(allExercises)..sort((a, b) => b.playCount.compareTo(a.playCount));
      default:
        return allExercises;
    }
  }

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

  Color _getTypeColor(ListeningExerciseType type) {
    switch (type) {
      case ListeningExerciseType.conversation:
        return Colors.blue;
      case ListeningExerciseType.news:
        return Colors.orange;
      case ListeningExerciseType.lecture:
        return Colors.green;
      case ListeningExerciseType.story:
        return Colors.purple;
      case ListeningExerciseType.interview:
        return Colors.red;
      case ListeningExerciseType.dialogue:
        return Colors.teal;
    }
  }
}