import 'package:get/get.dart';
import 'package:kaer_with_panels/app/localization/app_translations.dart';
import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart';
import 'package:kaer_with_panels/app/mixins/kr_app_bar_opacity_mixin.dart';

import '../../../common/app_config.dart';
import '../../../common/app_run_data.dart';
import '../../../services/api_service/kr_api.user.dart';
import '../../../utils/kr_common_util.dart';
import '../../../utils/kr_event_bus.dart';
import '../../../utils/kr_log_util.dart';

/// 网格项类型枚举
/// 用于区分不同的功能入口类型
enum KRGridItemType {
  /// VPN官网入口
  vpnWebsite,

  /// 推特社交入口
  telegram,

  /// 邮箱联系入口
  mail,

  /// 电话联系入口
  phone,

  /// 人工客服支持入口
  customerService,

  /// 客服人员联系入口
  contactService,
}

/// 网格项数据模型
/// 用于统一管理功能入口的展示数据
class KRGridItem {
  /// 功能图标
  final String icon;

  /// 功能标题
  final String title;

  /// 功能描述
  final String subtitle;

  /// 功能类型
  final KRGridItemType type;

  const KRGridItem({
    required this.icon,
    required this.title,
    required this.subtitle,
    required this.type,
  });
}

/// 用户信息页面的控制器
/// 负责管理用户信息页面的状态和业务逻辑
class KRUserInfoController extends GetxController with KRAppBarOpacityMixin {
  /// 广告拦截开关状态
  /// true: 开启拦截, false: 关闭拦截
  final RxBool kr_isAdBlockEnabled = true.obs;

  /// NDS解锁开关状态
  /// true: 已解锁, false: 未解锁
  final RxBool kr_isNDSUnlockEnabled = true.obs;

  /// 订阅状态
  /// true: 有效订阅, false: 无效订阅
  final RxBool kr_hasValidSubscription = false.obs;

  /// 是否显示绑定提示
  final RxBool kr_showBindingTip = false.obs;

  /// 用户余额
  RxDouble kr_balance = 0.0.obs;

  /// 功能入口网格项列表
  /// 包含所有可用的功能入口配置
  final kr_gridItems = <KRGridItem>[
    KRGridItem(
      icon: "my_net_index",
      title: AppTranslations.kr_userInfo.vpnWebsite,
      subtitle: AppConfig.getInstance().kr_official_website,
      type: KRGridItemType.vpnWebsite,
    ),
    KRGridItem(
      icon: "my_telegram",
      title: AppTranslations.kr_userInfo.telegram,
      subtitle: "telegram",
      type: KRGridItemType.telegram,
    ),
    KRGridItem(
      icon: "my_email",
      title: AppTranslations.kr_userInfo.mail,
      subtitle: AppConfig.getInstance().kr_official_email,
      type: KRGridItemType.mail,
    ),
    KRGridItem(
      icon: "my_phone",
      title: AppTranslations.kr_userInfo.phone,
      subtitle: AppConfig.getInstance().kr_official_telephone,
      type: KRGridItemType.phone,
    ),
    KRGridItem(
      icon: "my_kf",
      title: AppTranslations.kr_userInfo.customerService,
      subtitle: "",
      type: KRGridItemType.customerService,
    ),
    KRGridItem(
      icon: "my_kf_msg",
      title: AppTranslations.kr_userInfo.contactService,
      subtitle: "",
      type: KRGridItemType.contactService,
    ),
  ].obs;

  @override
  void onInit() {
    super.onInit();
    kr_initData();
  }

  /// 页面进入时的处理
  void kr_onPageEnter() {
    KRLogUtil.kr_i('进入用户信息页面', tag: 'UserInfo');
    _loadUserInfo();
  }

  @override
  void onReady() {
    super.onReady();
    // 每次进入页面时执行
    KRLogUtil.kr_i('进入用户信息页面', tag: 'UserInfo');
    // 刷新用户信息
    _loadUserInfo();
  }

  @override
  void onClose() {
    super.onClose();
  }

  /// 初始化控制器数据
  /// 从服务器获取用户配置信息
  void kr_initData() {
    ever(KRAppRunData.getInstance().kr_isLogin, (bool isLogin) {
      if (isLogin) {
        _loadUserInfo();
      } else {
        kr_balance.value = 0.0;
      }
    });

    ever(KRSingBoxImp().kr_blockAds, (bool bl) {
      kr_isAdBlockEnabled.value = bl;
    });

    kr_isAdBlockEnabled.value = KRSingBoxImp().kr_blockAds.value;
    // 监听所有支付相关消息
    KREventBus().kr_listenMessages(
      [KRMessageType.kr_payment, KRMessageType.kr_subscribe_update],
      _kr_handleMessage,
    );
  }

  /// 处理消息
  void _kr_handleMessage(KRMessageData message) {
    switch (message.kr_type) {
      case KRMessageType.kr_payment:
        _loadUserInfo();
        break;
      case KRMessageType.kr_subscribe_update:
        break;

      // TODO: Handle this case.
    }
  }

  /// 处理广告拦截开关状态变化
  /// [value] 新的开关状态
  void kr_toggleAdBlock(bool value) {
    kr_isAdBlockEnabled.value = value;

    KRSingBoxImp().kr_updateAdBlockEnabled(value);
  }

  /// 处理NDS解锁开关状态变化
  /// [value] 新的开关状态
  void kr_toggleNDSUnlock(bool value) {
    kr_isNDSUnlockEnabled.value = value;
    // TODO: 实现保存设置到服务器的逻辑
  }

  /// 初始化用户信息
  Future<void> _loadUserInfo() async {
    if (!KRAppRunData.getInstance().kr_isLogin.value) {
      return;
    }
    final either0 = await KRUserApi().kr_getUserInfo();
    either0.fold(
      (error) {
        KRLogUtil.kr_e(error.msg, tag: 'AppRunData');
      },
      (userInfo) async {
        kr_balance.value = userInfo.balance.toDouble() / 100;
      },
    );
  }

  /// 处理用户退出登录
  /// 清理用户数据并返回登录页面
  void kr_handleLogout() {
    KRAppRunData.getInstance().kr_loginOut();
  }

  /// 重置流量使用量
  /// 调用服务器API重置用户的流量使用量
  Future<void> kr_resetTraffic() async {
    try {
      // TODO: 调用服务器API重置流量
      KRCommonUtil.kr_showToast(
          AppTranslations.kr_userInfo.resetTrafficSuccess);
    } catch (e) {
      KRCommonUtil.kr_showToast(AppTranslations.kr_userInfo.resetTrafficFailed);
    }
  }

  String getTitle(KRGridItemType type) {
    switch (type) {
      case KRGridItemType.vpnWebsite:
        return AppTranslations.kr_userInfo.vpnWebsite;
      case KRGridItemType.telegram:
        return AppTranslations.kr_userInfo.telegram;
      case KRGridItemType.mail:
        return AppTranslations.kr_userInfo.mail;
      case KRGridItemType.phone:
        return AppTranslations.kr_userInfo.phone;
      case KRGridItemType.customerService:
        return AppTranslations.kr_userInfo.customerService;
      case KRGridItemType.contactService:
        return AppTranslations.kr_userInfo.contactService;
    }
  }
}
