import 'package:get/get.dart';
import 'package:kaer_with_panels/app/localization/app_translations.dart';
import 'package:kaer_with_panels/app/utils/kr_log_util.dart';
import 'package:kaer_with_panels/app/utils/kr_secure_storage.dart';
import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart';
import 'package:kaer_with_panels/singbox/model/singbox_status.dart';

import '../common/app_config.dart';

/// 支持的国家枚举
enum KRCountry {
  cn('中国'),
  ir('伊朗'),
  af('阿富汗'),
  ru('俄罗斯'),
  id('印度尼西亚'),
  tr('土耳其'),
  br('巴西'),
  other('全局代理');  // ✅ 新增：全局代理模式（所有流量走代理，不添加国家直连规则）

  final String kr_name;
  const KRCountry(this.kr_name);

  /// 获取国家代码
  String get kr_code => name.toLowerCase();

  /// 获取国家名称
  String get kr_countryName => kr_name;

  /// 从代码获取枚举值
  static KRCountry? kr_fromCode(String code) {
    try {
      return KRCountry.values.firstWhere(
            (country) => country.kr_code == code.toLowerCase(),
      );
    } catch (e) {
      return null;
    }
  }
}

/// 国家工具类
class KRCountryUtil {
  /// 存储键
  static const String _kr_countryKey = 'kr_current_country';

  /// 当前选择的国家
  static final Rx<KRCountry> kr_currentCountry = KRCountry.cn.obs;

  /// 存储实例
  static final KRSecureStorage _kr_storage = KRSecureStorage();

  /// 初始化
  static Future<void> kr_init() async {
    try {
      final String? kr_savedCountry =
      await _kr_storage.kr_readData(key: _kr_countryKey);
      if (kr_savedCountry != null) {
        final KRCountry? kr_country = KRCountry.kr_fromCode(kr_savedCountry);
        if (kr_country != null) {
          kr_currentCountry.value = kr_country;
          return;
        }
      }
      if (AppConfig().kr_is_daytime == false) {
        kr_currentCountry.value = KRCountry.ru;
      } else {
        kr_currentCountry.value = KRCountry.cn;
      }

    } catch (err) {
      KRLogUtil.kr_e('初始化国家设置失败: $err', tag: 'CountryUtil');
      kr_currentCountry.value = KRCountry.cn;
    }
  }

  /// 设置当前国家
  static Future<void> kr_setCurrentCountry(KRCountry kr_country) async {
    try {
      await _kr_storage.kr_saveData(
          key: _kr_countryKey, value: kr_country.kr_code);
      kr_currentCountry.value = kr_country;
    } catch (err) {
      KRLogUtil.kr_e('设置国家失败: $err', tag: 'CountryUtil');
      throw err;
    }
  }

  /// 更新国家并重启服务
  static Future<void> kr_updateCountry(KRCountry kr_country) async {
    try {
      // 更新国家设置
      await kr_setCurrentCountry(kr_country);

      // 如果服务正在运行，重启服务
      if (KRSingBoxImp.instance.kr_status.value == SingboxStarted()) {
        await KRSingBoxImp.instance.kr_restart();
      }
    } catch (err) {
      KRLogUtil.kr_e('更新国家失败: $err', tag: 'CountryUtil');
      rethrow;
    }
  }

  /// 获取当前国家代码
  static String kr_getCurrentCountryCode() {
    return kr_currentCountry.value.kr_code;
  }

  static String kr_getCurrentCountryName() {
    return kr_getCountryName(kr_currentCountry.value);

  }

  /// 获取国家名称
  static String kr_getCountryName(KRCountry country) {
    switch (country) {
      case KRCountry.ir:
        return AppTranslations.kr_country.ir;
      case KRCountry.cn:
        return AppTranslations.kr_country.cn;

      case KRCountry.af:
        return AppTranslations.kr_country.af;

      case KRCountry.ru:
        return AppTranslations.kr_country.ru;

      case KRCountry.id:
        return AppTranslations.kr_country.id;
      case KRCountry.tr:
        return AppTranslations.kr_country.tr;
      case KRCountry.br:
        return AppTranslations.kr_country.br;
      case KRCountry.other:
        return '全局代理';  // ✅ 新增：全局代理
    }
  }

  /// 获取所有支持的国家列表
  static List<KRCountry> kr_getSupportedCountries() {
    if (AppConfig().kr_is_daytime == false) {
      return  KRCountry.values.where((element) => element != KRCountry.cn).toList();
    }
    return KRCountry.values;
  }

  /// 获取国家信息列表
  static List<Map<String, String>> kr_getCountryInfoList() {
    return KRCountry.values
        .map((country) => {
      'code': country.kr_code,
      'name': country.kr_countryName,
    })
        .toList();
  }
}
