import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../../config/translations/strings_enum.dart';
import '../../../constants/iconfont/iconfont.dart';
import '../../../controllers/api_controller.dart';
import '../../../controllers/core_controller.dart';
import '../../../data/models/launch/groups.dart';
import '../../../data/sp/ix_sp.dart';

class NodeController extends GetxController {
  final coreController = Get.find<CoreController>();
  final ApiController _apiController = Get.find<ApiController>();
  // Groups 数据
  final _groups = Rxn<Groups>();
  Groups? get groups => _groups.value;
  set groups(Groups? value) => _groups.value = value;

  // 游戏tab列表
  final _tabTextList = <String>[].obs;
  List<String> get tabTextList => _tabTextList;
  set tabTextList(List<String> value) => _tabTextList.assignAll(value);

  // 当前选中的 Tab 索引
  final _currentTabIndex = 0.obs;
  int get currentTabIndex => _currentTabIndex.value;
  set currentTabIndex(int value) => _currentTabIndex.value = value;

  // 保存每个 tab 中每个国家的展开/收缩状态
  // key 格式: "tabIndex_countryCode"
  final Map<String, bool> expandedStates = {};

  // 当前选中的tab
  String getCurrentTab() {
    return tabTextList[currentTabIndex];
  }

  // 列表刷新状态
  final _isRefreshing = false.obs;
  bool get isRefreshing => _isRefreshing.value;

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

  /// 加载 Groups 数据
  void _loadGroups() {
    final launch = IXSP.getLaunch();
    if (launch?.groups != null) {
      groups = launch!.groups;
      _updateTabList();
    }
  }

  void updateGroups(Groups? groups) {
    this.groups = groups;
    _updateTabList();
  }

  /// 更新 Tab 列表
  void _updateTabList() {
    final tabs = <String>[];

    // 添加 Normal tab
    if (groups?.normal != null && groups!.normal!.list?.isNotEmpty == true) {
      tabs.add(Strings.tabAll.tr);
    }

    // 添加 Streaming tab
    if (groups?.streaming != null &&
        groups!.streaming!.list?.isNotEmpty == true) {
      tabs.add(Strings.tabStreaming.tr);
    }

    tabTextList = tabs;
  }

  /// 根据 tab 索引获取对应的数据
  Normal? getDataByTabIndex(int tabIndex) {
    if (tabIndex == 0) {
      return groups?.normal;
    } else if (tabIndex == 1) {
      return groups?.streaming;
    }
    return null;
  }

  IconData getTabIcon(int tabIndex) {
    if (tabIndex == 0) {
      return IconFont.icon24;
    } else if (tabIndex == 1) {
      return IconFont.icon25;
    }
    return IconFont.icon24;
  }

  /// 获取国家的展开状态
  bool getExpandedState(int tabIndex, String countryCode) {
    final key = '${tabIndex}_$countryCode';
    return expandedStates[key] ?? false; // 默认收缩
  }

  /// 设置国家的展开状态
  void setExpandedState(int tabIndex, String countryCode, bool expanded) {
    final key = '${tabIndex}_$countryCode';
    expandedStates[key] = expanded;
  }

  /// 当 Launch 数据更新时刷新节点
  void refreshOnLaunchChanged() {
    _loadGroups();
  }

  // 设置tab选中状态
  void setTabSelected(int tabIndex) {
    currentTabIndex = tabIndex;
    coreController.locationSelectionType = tabTextList[tabIndex];
  }

  /// 主动刷新列表
  void refreshLocations() async {
    try {
      _isRefreshing.value = true;
      // 保持至少2秒的刷新过程
      final results = await Future.wait([
        _apiController.getLocations(),
        Future.delayed(const Duration(milliseconds: 1500)),
      ]);
      final groups = results[0] as Groups;
      updateGroups(groups);
      _isRefreshing.value = false;
    } catch (_) {
      // TODO: 捕捉异常写入日志
      Future.delayed(const Duration(milliseconds: 1500), () {
        _isRefreshing.value = false;
      });
    }
  }
}
