import 'package:get/get_rx/src/rx_types/rx_types.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 '../../configs/constants.dart';
import '../transaction/model/payment_method_model.dart';
import 'models/customer_contract_object_model.dart';
import 'models/electric_payment_response_model.dart';

class ElectricPaymentBillViewModel extends RestfulApiViewModel {
  var paymentMethods = RxList<PaymentMethodModel>();
  var selectedPaymentMethodIndex = 0.obs;
  void Function(ElectricPaymentResponseModel data)? customerEvnPaymentGatewayResponse;
  void Function(String message)? onShowAlertError;

  Future<void> getPaymentMethods() async {
    showLoading();
    try {
      final response = await client.getPreviewPaymentMethods();
      hideLoading();
      selectedPaymentMethodIndex.value = 0;
      paymentMethods.value = response.data ?? [];
    } catch (error) {
      hideLoading();
    }
  }

  customerEvnPaymentGatewayRequest(CustomerContractModel bill) async {
    final paymentMethod = paymentMethods.value.safe(selectedPaymentMethodIndex.value ?? 0) ?? paymentMethods.firstOrNull;
    final paymentMethodType = paymentMethod?.type?.methodBillEVN ?? '';
    if (paymentMethodType.isEmpty) {
      onShowAlertError?.call("Vui lòng chọn phương thức thanh toán.");
      return;
    }
    showLoading();
    try {
      final response = await client.customerEvnPaymentGatewayRequest(bill, paymentMethodType);
      hideLoading();
      if (response.isSuccess && response.data != null) {
        customerEvnPaymentGatewayResponse?.call(response.data!);
      } else {
        onShowAlertError?.call(response.errorMessage ?? "Lỗi khi thanh toán, vui lòng thử lại sau.");
      }
    } catch (error) {
      hideLoading();
      onShowAlertError?.call(Constants.commonError);
    }
  }
}
