import 'dart:math';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/config/app_constants.dart';

class GenFilterNotifier extends Notifier<Set<int>> {
  @override
  Set<int> build() {
    _load();
    // Default: all gens enabled
    return Set.from(List.generate(AppConstants.genRanges.length, (i) => i));
  }

  Future<void> _load() async {
    final prefs = await SharedPreferences.getInstance();
    final saved = prefs.getStringList(AppConstants.prefsGenFilter);
    if (saved != null && saved.isNotEmpty) {
      state = saved.map(int.parse).toSet();
    }
  }

  Future<void> toggle(int genIndex) async {
    final next = Set<int>.from(state);
    if (next.contains(genIndex)) {
      // Prevent deselecting the last gen
      if (next.length == 1) return;
      next.remove(genIndex);
    } else {
      next.add(genIndex);
    }
    state = next;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setStringList(
      AppConstants.prefsGenFilter,
      state.map((i) => i.toString()).toList(),
    );
  }

  /// Returns a random Pokémon ID within the currently enabled gens.
  int randomId(Random random) {
    final ranges = state.map((i) => AppConstants.genRanges[i]).toList();
    final totalPool = ranges.fold(0, (sum, r) => sum + (r.$2 - r.$1 + 1));
    var pick = random.nextInt(totalPool);
    for (final r in ranges) {
      final size = r.$2 - r.$1 + 1;
      if (pick < size) return r.$1 + pick;
      pick -= size;
    }
    return 1;
  }
}

final genFilterProvider =
    NotifierProvider<GenFilterNotifier, Set<int>>(GenFilterNotifier.new);
