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

// ==================== 设置键名常量 ====================

const String _keyNotificationsEnabled = 'settings_notifications_enabled';
const String _keyDarkModeEnabled = 'settings_dark_mode_enabled';

// ==================== 消息通知设置 ====================

/// 消息通知开关状态 Provider
final notificationsEnabledProvider = StateNotifierProvider<NotificationsNotifier, bool>((ref) {
  return NotificationsNotifier();
});

class NotificationsNotifier extends StateNotifier<bool> {
  NotificationsNotifier() : super(true) {
    _loadFromStorage();
  }

  Future<void> _loadFromStorage() async {
    final prefs = await SharedPreferences.getInstance();
    state = prefs.getBool(_keyNotificationsEnabled) ?? true;
  }

  Future<void> toggle() async {
    state = !state;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_keyNotificationsEnabled, state);
  }

  Future<void> setEnabled(bool enabled) async {
    state = enabled;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_keyNotificationsEnabled, enabled);
  }
}

// ==================== 深色模式设置 ====================

/// 深色模式开关状态 Provider
final darkModeEnabledProvider = StateNotifierProvider<DarkModeNotifier, bool>((ref) {
  return DarkModeNotifier();
});

class DarkModeNotifier extends StateNotifier<bool> {
  DarkModeNotifier() : super(false) {
    _loadFromStorage();
  }

  Future<void> _loadFromStorage() async {
    final prefs = await SharedPreferences.getInstance();
    state = prefs.getBool(_keyDarkModeEnabled) ?? false;
  }

  Future<void> toggle() async {
    state = !state;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_keyDarkModeEnabled, state);
  }

  Future<void> setEnabled(bool enabled) async {
    state = enabled;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_keyDarkModeEnabled, enabled);
  }
}

// ==================== 主题模式 Provider ====================

/// 应用主题模式 Provider
final themeModeProvider = Provider<ThemeMode>((ref) {
  final isDarkMode = ref.watch(darkModeEnabledProvider);
  return isDarkMode ? ThemeMode.dark : ThemeMode.light;
});
