import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/app/config/constants.dart';
import 'package:mypoint_flutter_app/core/network/api/product_api.dart' deferred as product_api;
import '../../../core/network/restful_api_viewmodel.dart';
import '../../mobile_card/models/usable_voucher_model.dart';
import '../models/my_product_status_type.dart';
import '../../../shared/widgets/base_view/base_response_model.dart';

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

  Future<void> _ensureProductApiLoaded() async {
    if (_productApiLoaded) return;
    await product_api.loadLibrary();
    _productApiLoaded = true;
  }

  Future<BaseResponseModel<T>> _callProductApi<T>(Future<BaseResponseModel<T>> Function(dynamic api) fn) async {
    await _ensureProductApiLoaded();
    final api = product_api.ProductApi(client);
    return fn(api);
  }

  @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 {
    isLoading.value = true;
    if (isRefresh) {
      showLoading();
    }
    final body = {
      "index": (isRefresh ? 0 : myCardModels.length).toString(),
      "size": '20',
    };
    final status = selectedTabIndex.value == 0 ? MyProductStatusType.waiting : MyProductStatusType.used;
    try {
      final response = await _callProductApi((api) => api.getMyMobileCards(status, body));
      if (!response.isSuccess) {
        onShowAlertError?.call(response.errorMessage ?? Constants.commonError);
      }
      final result = response.data?.listItems ?? [];
      if (isRefresh) {
        myCardModels.clear();
      }
      myCardModels.addAll(result);
    } catch (error) {
      if (isRefresh) {
        myCardModels.clear();
      }
      onShowAlertError?.call(Constants.commonError);
    } finally {
      if (isRefresh) {
        hideLoading();
      }
      isLoading.value = false;
    }
  }

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