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

// ── SharedPreferences Provider ────────────────────────
final sharedPreferencesProvider = Provider<SharedPreferences>((ref) {
  throw UnimplementedError('在 main.dart 中 override 此 Provider');
});

// ── 主题模式 ─────────────────────────────────────────
const _kThemeKey = 'theme_mode';

class ThemeNotifier extends Notifier<ThemeMode> {
  @override
  ThemeMode build() {
    final prefs = ref.read(sharedPreferencesProvider);
    final saved = prefs.getString(_kThemeKey);
    return switch (saved) {
      'light' => ThemeMode.light,
      'dark' => ThemeMode.dark,
      _ => ThemeMode.dark, // 默认夜间模式
    };
  }

  /// 切换主题
  void setTheme(ThemeMode mode) {
    state = mode;
    final prefs = ref.read(sharedPreferencesProvider);
    prefs.setString(_kThemeKey, mode.name);
  }

  /// 在深色与浅色之间切换
  void toggle() {
    setTheme(state == ThemeMode.dark ? ThemeMode.light : ThemeMode.dark);
  }
}

final themeProvider = NotifierProvider<ThemeNotifier, ThemeMode>(
  ThemeNotifier.new,
);

// ── 语言设置 ─────────────────────────────────────────
const _kLocaleKey = 'locale';
const _kLocaleCountryKey = 'locale_country';

/// 支持的语言列表：与 [MaterialApp.router] 的 `supportedLocales` 一致。
const supportedLanguages = <({String label, Locale locale})>[
  (label: '简体中文', locale: Locale('zh')),
  (label: '繁體中文', locale: Locale('zh', 'TW')),
  (label: 'English', locale: Locale('en')),
  (label: 'हिन्दी', locale: Locale('hi')),
  (label: 'Bahasa Indonesia', locale: Locale('id')),
  (label: '日本語', locale: Locale('ja')),
  (label: '한국어', locale: Locale('ko')),
];

class LocaleNotifier extends Notifier<Locale> {
  @override
  Locale build() {
    final prefs = ref.read(sharedPreferencesProvider);
    final lang    = prefs.getString(_kLocaleKey);
    final country = prefs.getString(_kLocaleCountryKey) ?? '';
    if (lang != null) {
      return country.isNotEmpty ? Locale(lang, country) : Locale(lang);
    }
    return const Locale('zh');
  }

  /// 切换语言，立即生效（无需重启 App）
  void setLocale(Locale locale) {
    state = locale;
    final prefs = ref.read(sharedPreferencesProvider);
    prefs.setString(_kLocaleKey, locale.languageCode);
    prefs.setString(_kLocaleCountryKey, locale.countryCode ?? '');
  }
}

final localeProvider = NotifierProvider<LocaleNotifier, Locale>(
  LocaleNotifier.new,
);

/// [Locale] → 后端 `lang` 参数（与 Dio `lang` Header、`uc/ancillary/more/help` 等一致）
String backendLangFromLocale(Locale locale) {
  switch (locale.languageCode) {
    case 'zh':
      return locale.countryCode == 'TW' ? 'zh_HK' : 'zh_CN';
    case 'en':
      return 'en_US';
    case 'hi':
      return 'hi_IN';
    case 'id':
      return 'id_ID';
    case 'ja':
      return 'ja_JP';
    case 'ko':
      return 'ko_KR';
    default:
      return 'zh_CN';
  }
}
