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/api/product_api.dart' deferred as product_api;
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../networking/restful_api_viewmodel.dart';
import '../transaction/model/payment_method_model.dart';
import 'models/customer_contract_object_model.dart';
import 'models/electric_payment_response_model.dart';
import '../../base/base_response_model.dart';

class ElectricPaymentBillViewModel extends RestfulApiViewModel {
  final RxList<PaymentMethodModel> paymentMethods = <PaymentMethodModel>[].obs;
  final RxInt selectedPaymentMethodIndex = 0.obs;
  void Function(ElectricPaymentResponseModel data)? customerEvnPaymentGatewayResponse;
  void Function(String message)? onShowAlertError;
  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);
  }

  Future<void> getPaymentMethods() async {
    await callApi<List<PaymentMethodModel>>(
      request: () => _callProductApi((api) => api.getPreviewPaymentMethods()),
      onSuccess: (data, _) {
        selectedPaymentMethodIndex.value = 0;
        paymentMethods.assignAll(data);
      },
      onFailure: (_, _, _) async {},
    );
  }

  Future<void> customerEvnPaymentGatewayRequest(CustomerContractModel bill) async {
    final paymentMethod = paymentMethods.safe(selectedPaymentMethodIndex.value) ?? 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;
    }
    await callApi<ElectricPaymentResponseModel>(
      request: () => client.customerEvnPaymentGatewayRequest(bill, paymentMethodType),
      onSuccess: (data, _) {
        customerEvnPaymentGatewayResponse?.call(data);
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg);
      },
      defaultError: "Lỗi khi thanh toán, vui lòng thử lại sau.",
    );
  }
}
