import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/configs/constants.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../../networking/restful_api_viewmodel.dart';
import '../../mobile_card/models/usable_voucher_model.dart';
import '../models/my_product_status_type.dart';

class MyMobileCardListViewModel extends RestfulApiViewModel {
  final RxInt selectedTabIndex = 0.obs;
  var myCardModels = <UsableVoucherModel>[].obs;
  void Function(String message)? onShowAlertError;
  void Function(UsableVoucherModel data)? onRedeemProductMobileSuccess;

  @override
  void onInit() {
    super.onInit();
    freshData(isRefresh: true);
  }

  void selectTab(int index) {
    selectedTabIndex.value = index;
    freshData(isRefresh: true);
  }

  Future<void> freshData({bool isRefresh = false}) async {
    if (isRefresh) {
      showLoading();
    }
    final body = {
      "index": (isRefresh ? 0 : myCardModels.length).toString(),
      "size": '20',
    };
    final status = selectedTabIndex.value == 0 ? MyProductStatusType.waiting : MyProductStatusType.used;
    final response = await client.getMyMobileCards(status, body);
    if (!response.isSuccess) {
      onShowAlertError?.call(response.errorMessage ?? Constants.commonError);
    }
    final result = response.data?.listItems ?? [];
    if (isRefresh) {
      hideLoading();
      myCardModels.clear();
    }
    myCardModels.addAll(result);
  }

  Future<void> getMobileCardDetail(String itemId) async {
    showLoading();
    final response = await client.getMobileCardCode(itemId);
    final data = response.data?.item;
    if (response.isSuccess && data != null) {
      hideLoading();
      onRedeemProductMobileSuccess?.call(data);
      return;
    }
    hideLoading();
    onShowAlertError?.call(response.message ?? Constants.commonError);
  }
}