import 'package:shared_preferences/shared_preferences.dart';

enum UiThemeMode {
  system,
  light,
  dark;

  static UiThemeMode fromStorage(String? value) {
    return UiThemeMode.values.firstWhere(
      (mode) => mode.name == value,
      orElse: () => UiThemeMode.system,
    );
  }
}

class UiSettings {
  const UiSettings({
    this.host = '',
    this.nickname = '',
    this.themeMode = UiThemeMode.system,
  });

  final String host;
  final String nickname;
  final UiThemeMode themeMode;
}

class UiPreferencesService {
  static const _hostKey = 'ui.host';
  static const _nicknameKey = 'ui.nickname';
  static const _themeModeKey = 'ui.theme_mode';
  static const _permissionsExplainedKey = 'perms_explained';

  const UiPreferencesService();

  Future<UiSettings> loadSettings() async {
    final prefs = await SharedPreferences.getInstance();
    return UiSettings(
      host: prefs.getString(_hostKey) ?? '',
      nickname: prefs.getString(_nicknameKey) ?? '',
      themeMode: UiThemeMode.fromStorage(prefs.getString(_themeModeKey)),
    );
  }

  Future<void> saveSettings({String? host, String? nickname}) async {
    final prefs = await SharedPreferences.getInstance();
    if (host != null) await prefs.setString(_hostKey, host);
    if (nickname != null) await prefs.setString(_nicknameKey, nickname);
  }

  Future<void> saveThemeMode(UiThemeMode themeMode) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_themeModeKey, themeMode.name);
  }

  Future<bool> hasExplainedPermissions() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getBool(_permissionsExplainedKey) ?? false;
  }

  Future<void> markPermissionsExplained() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_permissionsExplainedKey, true);
  }
}
