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 {
  final Rxn<MembershipInfoResponse> membershipInfo = Rxn<MembershipInfoResponse>();
  final RxInt selectedTab = 0.obs;
  MembershipLevelModel? selectedLevel;
  void Function(String message)? onShowAlertError;

  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 {
    await callApi<MembershipInfoResponse>(
      request: () => client.getMembershipLevelInfo(),
      onSuccess: (data, _) {
        membershipInfo.value = data;
        _makeSelectedLevel();
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg);
      },
    );
  }
}
