import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/writing_task.dart';
import '../providers/writing_provider.dart';
import 'writing_detail_screen.dart';

/// 写作练习列表页面
class WritingListScreen extends ConsumerStatefulWidget {
  final WritingType? type;
  final WritingDifficulty? difficulty;
  final String title;

  const WritingListScreen({
    super.key,
    this.type,
    this.difficulty,
    required this.title,
  });

  @override
  ConsumerState<WritingListScreen> createState() => _WritingListScreenState();
}

class _WritingListScreenState extends ConsumerState<WritingListScreen> {
  WritingDifficulty? selectedDifficulty;
  WritingType? selectedType;

  @override
  void initState() {
    super.initState();
    selectedDifficulty = widget.difficulty;
    selectedType = widget.type;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadTasks();
    });
  }

  void _loadTasks() {
    ref.read(writingTasksProvider.notifier).loadTasks(
      type: selectedType,
      difficulty: selectedDifficulty,
      page: 1,
    );
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(writingTasksProvider);
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
        title: Text(widget.title),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.filter_list),
            onPressed: _showFilterDialog,
          ),
        ],
      ),
      body: Column(
        children: [
          if (selectedDifficulty != null || selectedType != null)
            Container(
              padding: const EdgeInsets.all(16),
              color: Colors.white,
              child: Row(
                children: [
                  if (selectedDifficulty != null)
                    Chip(
                      label: Text(selectedDifficulty!.displayName),
                      onDeleted: () {
                        setState(() {
                          selectedDifficulty = null;
                        });
                        _loadTasks();
                      },
                    ),
                  if (selectedType != null)
                    Padding(
                      padding: const EdgeInsets.only(left: 8),
                      child: Chip(
                        label: Text(selectedType!.displayName),
                        onDeleted: () {
                          setState(() {
                            selectedType = null;
                          });
                          _loadTasks();
                        },
                      ),
                    ),
                ],
              ),
            ),
          Expanded(
            child: Builder(
              builder: (context) {
                if (state.isLoading) {
                  return const Center(child: CircularProgressIndicator());
                }
                if (state.error != null) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.error_outline,
                          size: 48,
                          color: Colors.grey[400],
                        ),
                        const SizedBox(height: 12),
                        Text(
                          '加载失败',
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.grey[600],
                          ),
                        ),
                        const SizedBox(height: 8),
                        TextButton(
                          onPressed: _loadTasks,
                          child: const Text('重试'),
                        ),
                      ],
                    ),
                  );
                }
                if (state.tasks.isEmpty) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.edit_note,
                          size: 64,
                          color: Colors.grey[400],
                        ),
                        const SizedBox(height: 12),
                        Text(
                          '暂无写作任务',
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.grey[600],
                          ),
                        ),
                      ],
                    ),
                  );
                }
                return ListView.builder(
                  padding: const EdgeInsets.all(16),
                  itemCount: state.tasks.length,
                  itemBuilder: (context, index) {
                    final task = state.tasks[index];
                    return _buildTaskCard(task);
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTaskCard(WritingTask task) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      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: InkWell(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => WritingDetailScreen(task: task),
            ),
          );
        },
        borderRadius: BorderRadius.circular(16),
        child: Padding(
          padding: const EdgeInsets.all(20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Expanded(
                    child: Text(
                      task.title,
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: _getDifficultyColor(task.difficulty),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Text(
                      task.difficulty.displayName,
                      style: const TextStyle(
                        fontSize: 12,
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Text(
                task.description,
                style: const TextStyle(
                  fontSize: 14,
                  color: Colors.grey,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 12),
              Row(
                children: [
                  _buildInfoChip(
                    Icons.category,
                    task.type.displayName,
                    const Color(0xFF2196F3),
                  ),
                  const SizedBox(width: 8),
                  _buildInfoChip(
                    Icons.timer,
                    '${task.timeLimit}分钟',
                    const Color(0xFF4CAF50),
                  ),
                  const SizedBox(width: 8),
                  _buildInfoChip(
                    Icons.text_fields,
                    '${task.wordLimit}词',
                    const Color(0xFFFF9800),
                  ),
                ],
              ),
              if (task.keywords.isNotEmpty) ...[
                const SizedBox(height: 12),
                Wrap(
                  spacing: 6,
                  runSpacing: 6,
                  children: task.keywords.take(3).map((keyword) => Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: Colors.grey[100],
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Text(
                      keyword,
                      style: const TextStyle(
                        fontSize: 12,
                        color: Colors.grey,
                      ),
                    ),
                  )).toList(),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildInfoChip(IconData icon, String text, Color color) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            size: 14,
            color: color,
          ),
          const SizedBox(width: 4),
          Text(
            text,
            style: TextStyle(
              fontSize: 12,
              color: color,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  Color _getDifficultyColor(WritingDifficulty difficulty) {
    switch (difficulty) {
      case WritingDifficulty.beginner:
        return const Color(0xFF4CAF50);
      case WritingDifficulty.elementary:
        return const Color(0xFF8BC34A);
      case WritingDifficulty.intermediate:
        return const Color(0xFFFF9800);
      case WritingDifficulty.upperIntermediate:
        return const Color(0xFFFF5722);
      case WritingDifficulty.advanced:
        return const Color(0xFFF44336);
    }
  }

  void _showFilterDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('筛选条件'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('难度等级'),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              children: WritingDifficulty.values.map((difficulty) => FilterChip(
                label: Text(difficulty.displayName),
                selected: selectedDifficulty == difficulty,
                onSelected: (selected) {
                  setState(() {
                    selectedDifficulty = selected ? difficulty : null;
                  });
                },
              )).toList(),
            ),
            const SizedBox(height: 16),
            const Text('写作类型'),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              children: WritingType.values.map((type) => FilterChip(
                label: Text(type.displayName),
                selected: selectedType == type,
                onSelected: (selected) {
                  setState(() {
                    selectedType = selected ? type : null;
                  });
                },
              )).toList(),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              setState(() {
                selectedDifficulty = null;
                selectedType = null;
              });
              Navigator.pop(context);
              _loadTasks();
            },
            child: const Text('清除'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              _loadTasks();
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }
}