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

enum RecipesViewMode { grid, list }

class RecipesViewNotifier extends AsyncNotifier<({RecipesViewMode mode, int columns})> {
  static const _modeKey = 'recipes_view_mode';
  static const _columnsKey = 'recipes_grid_columns';

  @override
  Future<({RecipesViewMode mode, int columns})> build() async {
    final prefs = await SharedPreferences.getInstance();
    final mode = RecipesViewMode.values[prefs.getInt(_modeKey) ?? 0];
    final columns = prefs.getInt(_columnsKey) ?? 2;
    return (mode: mode, columns: columns);
  }

  Future<void> toggleMode() async {
    final prefs = await SharedPreferences.getInstance();
    final current = state.maybeWhen(
          data: (v) => v,
          orElse: () => (mode: RecipesViewMode.grid, columns: 2),
        );
    final newMode = current.mode == RecipesViewMode.grid ? RecipesViewMode.list : RecipesViewMode.grid;
    await prefs.setInt(_modeKey, newMode.index);
    state = AsyncData((mode: newMode, columns: current.columns));
  }

  Future<void> setColumns(int columns) async {
    final prefs = await SharedPreferences.getInstance();
    final current = state.maybeWhen(
          data: (v) => v,
          orElse: () => (mode: RecipesViewMode.grid, columns: 2),
        );
    await prefs.setInt(_columnsKey, columns);
    state = AsyncData((mode: current.mode, columns: columns));
  }
}

final recipesViewProvider =
    AsyncNotifierProvider<RecipesViewNotifier, ({RecipesViewMode mode, int columns})>(
        RecipesViewNotifier.new);
