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

import 'package:household_keeper/features/tasks/domain/task_sort_option.dart';

part 'sort_preference_notifier.g.dart';

const _sortOptionKey = 'task_sort_option';

/// Notifier that manages the active task sort preference.
///
/// Defaults to [TaskSortOption.alphabetical] synchronously (matching the
/// existing A-Z sort in CalendarDayList), then loads the persisted value
/// asynchronously on first build.
///
/// Follows the same pattern as [ThemeNotifier] in
/// `lib/core/theme/theme_provider.dart`.
@Riverpod(keepAlive: true)
class SortPreferenceNotifier extends _$SortPreferenceNotifier {
  @override
  TaskSortOption build() {
    _loadPersisted();
    return TaskSortOption.alphabetical;
  }

  Future<void> _loadPersisted() async {
    final prefs = await SharedPreferences.getInstance();
    final persisted = prefs.getString(_sortOptionKey);
    if (persisted != null) {
      state = _fromString(persisted);
    }
  }

  /// Update the active sort preference and persist it.
  Future<void> setSortOption(TaskSortOption option) async {
    state = option;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_sortOptionKey, _toString(option));
  }

  static TaskSortOption _fromString(String value) {
    switch (value) {
      case 'alphabetical':
        return TaskSortOption.alphabetical;
      case 'interval':
        return TaskSortOption.interval;
      case 'effort':
        return TaskSortOption.effort;
      default:
        return TaskSortOption.alphabetical;
    }
  }

  static String _toString(TaskSortOption option) {
    return option.name;
  }
}
