import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../core/core.dart';

/// 分类列表 Provider
final categoriesProvider = FutureProvider<List<CategoryModel>>((ref) async {
  return CharacterRepository.getCategories();
});

/// 角色列表 Provider
final charactersProvider = FutureProvider<List<CharacterModel>>((ref) async {
  return CharacterRepository.getCharacters();
});

/// 当前选中的分类代码 Notifier
class SelectedCategoryNotifier extends Notifier<String> {
  @override
  String build() => 'all';
  
  void setCategory(String code) {
    state = code;
  }
}

/// 当前选中的分类代码
final selectedCategoryProvider = NotifierProvider<SelectedCategoryNotifier, String>(
  SelectedCategoryNotifier.new,
);

/// 根据分类筛选后的角色列表
final filteredCharactersProvider = Provider<AsyncValue<List<CharacterModel>>>((ref) {
  final categoryCode = ref.watch(selectedCategoryProvider);
  final charactersAsync = ref.watch(charactersProvider);
  
  return charactersAsync.when(
    data: (characters) {
      if (categoryCode == 'all') {
        return AsyncValue.data(characters);
      }
      
      // 本地筛选
      final filtered = characters.where((c) {
        final tags = c.tagNames.join('');
        switch (categoryCode) {
          case 'gentle':
            return tags.contains('治愈') || tags.contains('温顺') || tags.contains('医疗');
          case 'dom':
            return tags.contains('强势') || tags.contains('调教') || tags.contains('指令');
          case 'wild':
            return tags.contains('病娇') || tags.contains('神秘') || 
                   tags.contains('不稳定') || tags.contains('极乐');
          case 'exclusive':
            return c.isLocked;
          default:
            return false;
        }
      }).toList();
      
      return AsyncValue.data(filtered);
    },
    loading: () => const AsyncValue.loading(),
    error: (e, st) => AsyncValue.error(e, st),
  );
});

/// 单个角色详情 Provider
final characterDetailProvider = FutureProvider.family<CharacterModel?, String>((ref, id) async {
  return CharacterRepository.getCharacterById(id);
});
