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

import '../models/enum_theme.dart';
import '../config.dart';

const _keyThemeMode = AppSharedPreferencesKey.themeMode;
const _keyUseDynamic = AppSharedPreferencesKey.useDynamicColor;

final themeModeProvider = StateNotifierProvider<ThemeModeNotifier, ThemeModeType>(
  (ref) => ThemeModeNotifier(),
);

final useDynamicColorProvider = StateNotifierProvider<UseDynamicColorNotifier, bool>(
  (ref) => UseDynamicColorNotifier(),
);

class UseDynamicColorNotifier extends StateNotifier<bool> {
  UseDynamicColorNotifier() : super(true) {
    _load();
  }

  Future<void> _load() async {
    final prefs = await SharedPreferences.getInstance();
    state = prefs.getBool(_keyUseDynamic) ?? AppConfig.useDynamicColor;
  }

  Future<void> set(bool value) async {
    state = value;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_keyUseDynamic, value);
  }
}


class ThemeModeNotifier extends StateNotifier<ThemeModeType> {
  ThemeModeNotifier() : super(ThemeModeType.system) {
    _load();
  }

  Future<void> _load() async {
    final prefs = await SharedPreferences.getInstance();
    final index = prefs.getInt(_keyThemeMode);
    if (index != null) {
      state = ThemeModeType.fromIndex(index);
    } else state = AppConfig.themeMode;
  }

  Future<void> set(ThemeModeType mode) async {
    state = mode;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_keyThemeMode, mode.index);
  }
}
