import 'package:get/get.dart';
import '../../../../utils/log/logger.dart';
import '../../../base/base_controller.dart';
import '../../../controllers/core_controller.dart';
import '../../../data/models/launch/groups.dart';
import '../../../data/sp/ix_sp.dart';

/// 主页控制器
class HomeController extends BaseController {
  final coreController = Get.find<CoreController>();
  final TAG = 'HomeController';

  final _isOn = false.obs;
  bool get isOn => _isOn.value;
  set isOn(bool value) => _isOn.value = value;

  final _currentIndex = 0.obs;
  int get currentIndex => _currentIndex.value;
  set currentIndex(int value) => _currentIndex.value = value;

  final _lastIndex = 0.obs;
  int get lastIndex => _lastIndex.value;
  set lastIndex(int value) => _lastIndex.value = value;

  // 最近位置是否展开
  final _isRecentLocationsExpanded = false.obs;
  bool get isRecentLocationsExpanded => _isRecentLocationsExpanded.value;
  set isRecentLocationsExpanded(bool value) =>
      _isRecentLocationsExpanded.value = value;

  // 统计信息
  final _uplinkBytes = 0.obs;
  final _downlinkBytes = 0.obs;
  int get uplinkBytes => _uplinkBytes.value;
  int get downlinkBytes => _downlinkBytes.value;

  // 延迟信息
  final _currentDelay = 0.obs;
  int get currentDelay => _currentDelay.value;

  // 当前选择的位置
  final _selectedLocation = Rxn<Locations>();
  Locations? get selectedLocation => _selectedLocation.value;
  set selectedLocation(Locations? value) => _selectedLocation.value = value;

  // 最近使用的位置列表
  final _recentLocations = <Locations>[].obs;
  List<Locations> get recentLocations =>
      _recentLocations.where((loc) => loc.id != selectedLocation?.id).toList();

  // 是否是会员
  final _isPremium = false.obs;
  bool get isPremium => _isPremium.value;
  set isPremium(bool value) => _isPremium.value = value;

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

  /// 初始化位置数据
  void _initializeLocations() {
    // 从 SharedPreferences 加载保存的节点数据
    _loadSavedLocations();
  }

  /// 从 SharedPreferences 加载保存的节点数据
  void _loadSavedLocations() {
    try {
      // 加载当前选中的节点
      final selectedLocationData = IXSP.getSelectedLocation();
      if (selectedLocationData != null) {
        selectedLocation = Locations.fromJson(selectedLocationData);
      } else {
        // 如果没有保存的节点，选中第一个可用节点
        _selectFirstAvailableLocation();
      }

      // 加载最近选择的节点列表
      final recentLocationsData = IXSP.getRecentLocations();
      if (recentLocationsData.isNotEmpty) {
        _recentLocations.assignAll(
          recentLocationsData.map((e) => Locations.fromJson(e)).toList(),
        );
      }
    } catch (e) {
      log(TAG, 'Error loading saved locations: $e');
    }
  }

  /// 选中第一个可用节点
  void _selectFirstAvailableLocation() {
    try {
      final launch = IXSP.getLaunch();
      final normalList = launch?.groups?.normal?.list;

      if (normalList != null && normalList.isNotEmpty) {
        // 遍历找到第一个有可用节点的国家
        for (var locationList in normalList) {
          if (locationList.locations != null &&
              locationList.locations!.isNotEmpty) {
            // 选中第一个节点
            final firstLocation = locationList.locations!.first;
            selectLocation(firstLocation);
            break;
          }
        }
      }
    } catch (e) {
      log(TAG, 'Error selecting first available location: $e');
    }
  }

  /// 选择位置
  void selectLocation(Locations location) {
    selectedLocation = location;

    // 更新最近使用列表
    _updateRecentLocations(location);

    // 保存到 SharedPreferences
    _saveLocationsToStorage();
  }

  void handleConnect({bool delay = false}) {
    if (delay) {
      // 延迟300ms
      Future.delayed(const Duration(milliseconds: 300), () {
        coreController.selectLocationConnect();
      });
    } else {
      coreController.selectLocationConnect();
    }
  }

  /// 更新最近使用的位置列表
  void _updateRecentLocations(Locations location) {
    // 移除已存在的位置
    _recentLocations.removeWhere((loc) => loc.id == location.id);

    // 添加到列表开头
    _recentLocations.insert(0, location);

    // 保持最多4个最近使用的位置（过滤掉当前选中后能显示3个）
    if (_recentLocations.length > 4) {
      _recentLocations.removeRange(4, _recentLocations.length);
    }
  }

  /// 保存位置数据到 SharedPreferences
  void _saveLocationsToStorage() {
    try {
      // 保存当前选中的节点
      if (selectedLocation != null) {
        IXSP.saveSelectedLocation(selectedLocation!.toJson());
      }

      // 保存最近选择的节点列表
      final recentLocationsJson = _recentLocations
          .map((e) => e.toJson())
          .toList();
      IXSP.saveRecentLocations(recentLocationsJson);
    } catch (e) {
      log(TAG, 'Error saving locations to storage: $e');
    }
  }
}
