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

/// 主题提供者 - 管理明暗主题切换
///
/// 功能：
/// - 支持浅色/深色/跟随系统三种模式
/// - 持久化主题设置到本地存储
/// - 提供主题切换方法
class ThemeProvider extends ChangeNotifier {
  static const String _themeModeKey = 'theme_mode';

  ThemeMode _themeMode = ThemeMode.dark;

  /// 当前主题模式
  ThemeMode get themeMode => _themeMode;

  /// 是否为深色模式
  bool get isDarkMode => _themeMode == ThemeMode.dark;

  /// 初始化主题设置（从本地存储加载）
  Future<void> init() async {
    final prefs = await SharedPreferences.getInstance();
    final modeString = prefs.getString(_themeModeKey);

    if (modeString != null) {
      _themeMode = ThemeMode.values.firstWhere(
        (mode) => mode.toString() == modeString,
        orElse: () => ThemeMode.dark,
      );
      notifyListeners();
    }
  }

  /// 切换主题（浅色/深色）
  Future<void> toggleTheme() async {
    _themeMode = _themeMode == ThemeMode.light ? ThemeMode.dark : ThemeMode.light;
    await _saveThemeMode();
    notifyListeners();
  }

  /// 设置主题模式
  Future<void> setThemeMode(ThemeMode mode) async {
    if (_themeMode == mode) return;
    _themeMode = mode;
    await _saveThemeMode();
    notifyListeners();
  }

  /// 保存主题设置到本地存储
  Future<void> _saveThemeMode() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_themeModeKey, _themeMode.toString());
  }
}
