import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:kaer_with_panels/app/utils/kr_log_util.dart';
import 'package:kaer_with_panels/app/services/kr_subscribe_service.dart';
import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart';
import 'package:kaer_with_panels/app/utils/kr_secure_storage.dart';
import '../../../localization/app_translations.dart';
import 'package:kaer_with_panels/app/modules/kr_home/controllers/kr_home_controller.dart';

class HINodeListController extends GetxController with WidgetsBindingObserver {
  /// 订阅服务
  final KRSubscribeService kr_subscribeService = KRSubscribeService();

  /// 首页服务
  final KRHomeController homeController = Get.find<KRHomeController>();

  /// 调试模式状态
  final RxBool isDebugMode = false.obs;

  /// 模式按钮点击计数器
  int modeButtonClickCount = 0;

  /// 最后一次点击时间
  DateTime? lastModeButtonClickTime;

  /// 获取连接类型字符串
  String kr_getConnectionTypeString() {
    final connectionType = KRSingBoxImp.instance.kr_connectionType.value;
    switch (connectionType) {
      case KRConnectionType.global:
        return AppTranslations.kr_setting.connectionTypeGlobal;
      case KRConnectionType.rule:
        return AppTranslations.kr_setting.connectionTypeRule;
    }
  }

  /// 更新连接类型
  void kr_updateConnectionType(KRConnectionType type) {
    if (KRSingBoxImp().kr_connectionType.value != type) {
      KRSingBoxImp.instance.kr_updateConnectionType(type);
      KRLogUtil.kr_i('连接类型已更新为: $type', tag: 'HINodeListController');
      // 这里可以添加其他需要的逻辑
    }
  }

  /// 处理模式按钮点击（用于激活调试模式）
  void kr_handleModeButtonClick() {
    final now = DateTime.now();

    // 检查是否在2秒内连续点击
    if (lastModeButtonClickTime != null &&
        now.difference(lastModeButtonClickTime!).inSeconds > 2) {
      // 超过2秒，重置计数器
      modeButtonClickCount = 0;
    }

    modeButtonClickCount++;
    lastModeButtonClickTime = now;

    KRLogUtil.kr_i('模式按钮点击次数: $modeButtonClickCount',
        tag: 'HINodeListController');

    if (modeButtonClickCount >= 5) {
      // 激活调试模式
      isDebugMode.value = true;
      modeButtonClickCount = 0; // 重置计数器
      KRLogUtil.kr_i('🐛 调试模式已激活！', tag: 'HINodeListController');
    }
  }

  /// 获取要显示的节点列表（根据调试模式过滤）

  /// 重置调试模式
  void kr_resetDebugMode() {
    isDebugMode.value = false;
    modeButtonClickCount = 0;
    lastModeButtonClickTime = null;
    KRLogUtil.kr_i('调试模式已重置', tag: 'HINodeListController');
  }

  Future<void> kr_handleRefresh() async {
    await kr_subscribeService.kr_refreshAll();
    try {
      final savedNode =
          await KRSecureStorage().kr_readData(key: 'SELECTED_NODE_TAG');
      if (savedNode != null && savedNode.isNotEmpty) {
        homeController.kr_currentNodeName.value = savedNode;
        homeController.kr_cutTag.value = savedNode;
        homeController.kr_cutSeletedTag.value = savedNode;
      }
    } catch (_) {}
    if (!homeController.kr_isLatency.value) {
      homeController.kr_urlTest();
    }
  }

  @override
  void onInit() {
    super.onInit();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void onReady() {
    super.onReady();
    if (homeController.kr_isLatency.value) return;
    KRLogUtil.kr_i('🔄 节点列表显示 - 自动触发延迟测试', tag: 'HINodeListView');
    homeController.kr_urlTest();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 当应用从后台切换回前台时
    if (state == AppLifecycleState.resumed) {
      if (homeController.kr_isLatency.value) return;
      KRLogUtil.kr_i('🔄 节点列表显示 - 自动触发延迟测试', tag: 'HINodeListView');
      homeController.kr_urlTest();
    }
  }

  @override
  void onClose() {
    WidgetsBinding.instance.removeObserver(this);
    super.onClose();
  }
}
