import 'package:get/get.dart';
import 'package:mypoint_flutter_app/extensions/collection_extension.dart';
import 'package:mypoint_flutter_app/networking/restful_api_request.dart';
import '../../base/restful_api_viewmodel.dart';
import 'models/membership_info_response.dart';
import 'models/membership_level_model.dart';
import 'models/membership_level_term_and_condition_model.dart';

class MembershipViewModel extends RestfulApiViewModel {
  var isLoading = false.obs;
  var membershipInfo = Rxn<MembershipInfoResponse>();
  var selectedTab = 0.obs;
  MembershipLevelModel? selectedLevel;

  List<MembershipLevelModel>? get levels {
    return membershipInfo.value?.levels;
  }

  List<MembershipLevelTermAndConditionModel>? get conditions {
    if (levels == null || levels!.isEmpty) {
      return null;
    }
    return levels?.safe(selectedTab.value)?.conditions;
  }

  @override
  onInit() {
    super.onInit();
    getMembershipLevelInfo();
  }

  _makeSelectedLevel() {
    if (levels == null || levels!.isEmpty) {
      selectedLevel = null;
      return;
    }
    selectedLevel = levels!.firstWhere((e) => e.levelStartAtDate?.isNotEmpty == true, orElse: () => levels!.first);
  }

  getMembershipLevelInfo() async {
    showLoading();
    try {
      final response = await client.getMembershipLevelInfo();
      membershipInfo.value = response.data;
      _makeSelectedLevel();
      hideLoading();
    } catch (e) {
      hideLoading();
      print("Error fetching membership level info: $e");
    }
  }
}
