import 'package:flutter/material.dart';
import '../models/pronunciation_item.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../services/speaking_service.dart';
import '../providers/speaking_provider.dart';
import 'pronunciation_practice_screen.dart';

class PronunciationListScreen extends StatefulWidget {
  final PronunciationType type;

  const PronunciationListScreen({
    super.key,
    required this.type,
  });

  @override
  State<PronunciationListScreen> createState() => _PronunciationListScreenState();
}

class _PronunciationListScreenState extends State<PronunciationListScreen> {
  List<PronunciationItem> _items = [];
  DifficultyLevel? _selectedDifficulty;
  String? _selectedCategory;
  bool _loading = true;
  String? _error;

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

  void _loadItems() {
    setState(() {
      _loading = true;
      _error = null;
    });

    final service = SpeakingService();
    service.getPronunciationItems(widget.type, limit: 50).then((resp) {
      if (resp.success && resp.data != null) {
        setState(() {
          _items = resp.data!;
          _loading = false;
        });
        _applyFilters();
      } else {
        setState(() {
          _error = resp.message;
          _loading = false;
        });
      }
    }).catchError((e) {
      setState(() {
        _error = e.toString();
        _loading = false;
      });
    });
  }

  void _applyFilters() {
    List<PronunciationItem> filteredItems = List.of(_items);

    if (_selectedDifficulty != null) {
      filteredItems = filteredItems
          .where((item) => item.difficulty == _selectedDifficulty)
          .toList();
    }

    if (_selectedCategory != null) {
      filteredItems = filteredItems
          .where((item) => item.category == _selectedCategory)
          .toList();
    }

    setState(() {
      _items = filteredItems;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F7FA),
      appBar: AppBar(
        title: Text(widget.type.displayName),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.filter_list),
            onPressed: _showFilterDialog,
          ),
        ],
      ),
      body: Column(
        children: [
          _buildHeader(),
          _buildFilterChips(),
          Expanded(
            child: _loading
                ? const Center(child: CircularProgressIndicator())
                : _error != null
                    ? Center(child: Text(_error!, style: const TextStyle(color: Colors.red)))
                    : _buildItemList(),
          ),
        ],
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(20),
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(20),
          bottomRight: Radius.circular(20),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            widget.type.displayName,
            style: const TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            widget.type.description,
            style: const TextStyle(
              fontSize: 16,
              color: Colors.grey,
            ),
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Text(
                widget.type.icon,
                style: const TextStyle(fontSize: 32),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Text(
                  '共 ${_items.length} 个练习项目',
                  style: const TextStyle(
                    fontSize: 14,
                    color: Colors.grey,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildFilterChips() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children: [
            if (_selectedDifficulty != null)
              _buildFilterChip(
                '${_selectedDifficulty!.displayName} (${_selectedDifficulty!.code})',
                () {
                  setState(() {
                    _selectedDifficulty = null;
                    _applyFilters();
                  });
                },
                true,
              ),
            if (_selectedCategory != null)
              _buildFilterChip(
                _selectedCategory!,
                () {
                  setState(() {
                    _selectedCategory = null;
                    _applyFilters();
                  });
                },
                true,
              ),
            if (_selectedDifficulty == null && _selectedCategory == null)
              const Text(
                '点击右上角筛选按钮进行筛选',
                style: TextStyle(
                  color: Colors.grey,
                  fontSize: 14,
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildFilterChip(String label, VoidCallback onDeleted, bool showDelete) {
    return Container(
      margin: const EdgeInsets.only(right: 8),
      child: Chip(
        label: Text(label),
        onDeleted: showDelete ? onDeleted : null,
        backgroundColor: Colors.blue.withOpacity(0.1),
        deleteIconColor: Colors.blue,
      ),
    );
  }

  Widget _buildItemList() {
    if (_items.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.search_off,
              size: 64,
              color: Colors.grey,
            ),
            SizedBox(height: 16),
            Text(
              '没有找到符合条件的练习项目',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey,
              ),
            ),
          ],
        ),
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(20),
      itemCount: _items.length,
      itemBuilder: (context, index) {
        return _buildItemCard(_items[index]);
      },
    );
  }

  Widget _buildItemCard(PronunciationItem item) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      child: Card(
        elevation: 2,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
        child: InkWell(
          borderRadius: BorderRadius.circular(12),
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => PronunciationPracticeScreen(item: item),
              ),
            );
          },
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        item.text,
                        style: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    _buildDifficultyBadge(item.difficulty),
                  ],
                ),
                if (item.type != PronunciationType.sentence && item.phonetic.isNotEmpty) ...[
                  const SizedBox(height: 8),
                  Text(
                    item.phonetic,
                    style: const TextStyle(
                      fontSize: 16,
                      color: Colors.blue,
                      fontFamily: 'monospace',
                    ),
                  ),
                ],
                const SizedBox(height: 8),
                Row(
                  children: [
                    Icon(
                      Icons.category,
                      size: 16,
                      color: Colors.grey[600],
                    ),
                    const SizedBox(width: 4),
                    Text(
                      item.category,
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey[600],
                      ),
                    ),
                    const Spacer(),
                    Icon(
                      Icons.tips_and_updates,
                      size: 16,
                      color: Colors.grey[600],
                    ),
                    const SizedBox(width: 4),
                    Text(
                      '${item.tips.length} 个提示',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildDifficultyBadge(DifficultyLevel difficulty) {
    Color color;
    switch (difficulty) {
      case DifficultyLevel.beginner:
        color = Colors.green;
        break;
      case DifficultyLevel.intermediate:
        color = Colors.orange;
        break;
      case DifficultyLevel.advanced:
        color = Colors.red;
        break;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withOpacity(0.3)),
      ),
      child: Text(
        difficulty.displayName,
        style: TextStyle(
          fontSize: 12,
          color: color,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  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: DifficultyLevel.values.map((difficulty) {
                return 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: _getCategories().map((category) {
                return FilterChip(
                  label: Text(category),
                  selected: _selectedCategory == category,
                  onSelected: (selected) {
                    setState(() {
                      _selectedCategory = selected ? category : null;
                    });
                  },
                );
              }).toList(),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              setState(() {
                _selectedDifficulty = null;
                _selectedCategory = null;
              });
              Navigator.pop(context);
              _applyFilters();
            },
            child: const Text('清除'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              _applyFilters();
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  List<String> _getCategories() {
    final set = <String>{};
    for (final item in _items) {
      if (item.category.isNotEmpty) set.add(item.category);
    }
    return set.toList();
  }
}