import 'dart:convert';

import 'package:get/get.dart';

import '../../../../utils/event_bus.dart';
import '../../../../utils/log/logger.dart';
import 'package:nomo/app/data/sp/ix_sp.dart';
import '../../../routes/app_pages.dart';
import '../selectapp/controllers/splittunneling_selectapp_controller.dart';

class SplittunnelingController extends GetxController with EventBusMixin {
  static const String TAG = 'SplittunnelingController';

  // 当前选中的分流隧道模式
  final selectedMode = SplitTunnelingMode.none.obs;

  // 缓存键
  static const String _selectedModeKey = 'splittunneling_selected_mode';

  @override
  void onInit() {
    super.onInit();
    _loadSelectedMode();
    // 监听 PageVisibleEvent
    listenEvent<SplitTunnelingPageEvent>((event) {
      final selectApps = getSelectedApps(event.mode);
      if (selectApps.isNotEmpty) {
        selectedMode.value = event.mode;
        _saveSelectedMode();
        refreshSelectedApps();
      } else {
        if (selectedMode.value == event.mode) {
          selectedMode.value = SplitTunnelingMode.none;
          _saveSelectedMode();
          refreshSelectedApps();
        }
      }
    });
  }

  /// 刷新选中应用显示
  void refreshSelectedApps() {
    // 触发UI更新
    selectedMode.refresh();
  }

  /// 加载选中的模式
  void _loadSelectedMode() {
    final modeString = IXSP.getString(_selectedModeKey);
    if (modeString != null) {
      try {
        selectedMode.value = SplitTunnelingMode.values.firstWhere(
          (mode) => mode.toString() == modeString,
          orElse: () => SplitTunnelingMode.none,
        );
      } catch (e) {
        log(TAG, '加载选中模式失败: $e');
      }
    }
  }

  /// 保存选中的模式
  void _saveSelectedMode() {
    IXSP.setString(_selectedModeKey, selectedMode.value.toString());
  }

  /// 选择分流隧道模式
  void selectMode(SplitTunnelingMode mode) {
    if (mode == SplitTunnelingMode.none) {
      selectedMode.value = SplitTunnelingMode.none;
      _saveSelectedMode();
      refreshSelectedApps();
    } else {
      final selectedApps = getSelectedApps(mode);
      if (selectedApps.isNotEmpty) {
        if (selectedMode.value == mode) {
          selectedMode.value = SplitTunnelingMode.none;
        } else {
          selectedMode.value = mode;
        }
        _saveSelectedMode();
        refreshSelectedApps();
      } else {
        Get.toNamed(Routes.SPLITTUNNELING_SELECTAPP, arguments: mode);
      }
    }
  }

  void toSelectAppPage(SplitTunnelingMode mode) {
    Get.toNamed(Routes.SPLITTUNNELING_SELECTAPP, arguments: mode);
  }

  /// 获取当前模式选中的应用（最多3个）
  List<Map<String, dynamic>> getSelectedApps(SplitTunnelingMode mode) {
    if (mode == SplitTunnelingMode.none) {
      return [];
    }

    try {
      final key = mode == SplitTunnelingMode.exclude
          ? 'splittunneling_exclude_selected_apps'
          : 'splittunneling_include_selected_apps';

      final selectedAppsJson = IXSP.getString(key);
      if (selectedAppsJson != null) {
        final selectedPackageNames =
            jsonDecode(selectedAppsJson) as List<dynamic>;

        // 获取缓存的应用数据
        final cachedAppsJson = IXSP.getString('splittunneling_cached_apps');
        if (cachedAppsJson != null) {
          final cachedApps = jsonDecode(cachedAppsJson) as List;

          // 按照保存的顺序重建列表
          final selectedApps = <Map<String, dynamic>>[];
          for (final packageName in selectedPackageNames) {
            if (selectedApps.length >= 3) break; // 最多取3个

            final app = cachedApps.firstWhere(
              (app) => app['packageName'] == packageName,
              orElse: () => null,
            );
            if (app != null) {
              selectedApps.add({
                'name': app['name'],
                'packageName': app['packageName'],
                'icon': app['icon'],
              });
            }
          }
          return selectedApps;
        }
      }
    } catch (e) {
      log(TAG, '获取选中应用失败: $e');
    }
    return [];
  }
}
