import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:get/get.dart';
import '../../../app/data/sp/ix_sp.dart';
import '../ix_theme.dart';

/// 响应式主题扩展
/// 支持三种模式：system（跟随系统）、dark、light
class ReactiveTheme {
  static final RxBool _isLightTheme = true.obs;

  /// 初始化主题状态
  static void init() {
    _updateThemeFromMode();
  }

  /// 根据当前模式更新主题
  static void _updateThemeFromMode() {
    final mode = IXSP.getThemeMode();
    bool isLight;

    switch (mode) {
      case 'light':
        isLight = true;
        break;
      case 'dark':
        isLight = false;
        break;
      case 'system':
      default:
        // 跟随系统
        final brightness =
            SchedulerBinding.instance.platformDispatcher.platformBrightness;
        isLight = brightness == Brightness.light;
        break;
    }

    _isLightTheme.value = isLight;
  }

  /// 获取当前主题状态
  static bool get isLightTheme => _isLightTheme.value;

  /// 获取初始 ThemeMode（用于 GetMaterialApp）
  static ThemeMode get initialThemeMode {
    final mode = IXSP.getThemeMode();
    switch (mode) {
      case 'light':
        return ThemeMode.light;
      case 'dark':
        return ThemeMode.dark;
      case 'system':
      default:
        return ThemeMode.system;
    }
  }

  /// 切换主题（legacy，保持兼容）
  static void toggleTheme() {
    _isLightTheme.value = !_isLightTheme.value;
    IXSP.setThemeIsLight(_isLightTheme.value);
    Get.changeThemeMode(_isLightTheme.value ? ThemeMode.light : ThemeMode.dark);
  }

  /// 设置主题模式
  static void setThemeMode(String mode) {
    IXSP.setThemeMode(mode);

    ThemeMode themeMode;
    bool isLight;

    switch (mode) {
      case 'light':
        themeMode = ThemeMode.light;
        isLight = true;
        break;
      case 'dark':
        themeMode = ThemeMode.dark;
        isLight = false;
        break;
      case 'system':
      default:
        themeMode = ThemeMode.system;
        final brightness =
            SchedulerBinding.instance.platformDispatcher.platformBrightness;
        isLight = brightness == Brightness.light;
        break;
    }

    _isLightTheme.value = isLight;
    IXSP.setThemeIsLight(isLight);
    Get.changeThemeMode(themeMode);
  }

  /// 设置主题（legacy，保持兼容）
  static void setTheme(bool isLight) {
    if (_isLightTheme.value != isLight) {
      _isLightTheme.value = isLight;
      IXSP.setThemeIsLight(isLight);
      Get.changeThemeMode(isLight ? ThemeMode.light : ThemeMode.dark);
    }
  }

  /// 响应式主题数据
  static ThemeData get theme =>
      IXTheme.getThemeData(isLight: _isLightTheme.value);
}

/// 扩展 GetX，添加响应式主题方法
extension GetXThemeExtension on GetInterface {
  /// 响应式主题数据
  ThemeData get reactiveTheme => ReactiveTheme.theme;
}
