import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/extensions/collection_extension.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../networking/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;
    }
    final level = levels!.safe(selectedTab.value);
    return level?.conditions;
  }

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

  void _makeSelectedLevel() {
    if (levels == null || levels!.isEmpty) {
      selectedLevel = null;
      return;
    }
    try {
      selectedLevel = levels!.firstWhere(
        (e) => e.levelStartAtDate?.isNotEmpty == true, 
        orElse: () => levels!.first
      );
    } catch (e) {
      if (kDebugMode) {
        print('Failed to select level: $e');
      }
      selectedLevel = levels!.isNotEmpty ? levels!.first : null;
    }
  }

  Future<void> getMembershipLevelInfo() async {
    showLoading();
    try {
      final response = await client.getMembershipLevelInfo();
      if (response.isSuccess && response.data != null) {
        membershipInfo.value = response.data;
        _makeSelectedLevel();
      } else {
        if (kDebugMode) {
          print("Failed to get membership info: ${response.errorMessage}");
        }
      }
    } catch (e) {
      if (kDebugMode) {
        print("Error fetching membership level info: $e");
      }
    } finally {
      hideLoading();
    }
  }
}
