import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../core/config/server_response.dart';
import '../../../core/constants/app_contants.dart';
import '../../../core/data/repositories/app_repositories.dart';
import '../../../core/enums/request_constants.dart';
import '../../../core/utils/SessionCache.dart';
import '../../../core/utils/logs_utils.dart';
import '../../../custom_widgets/Fields/field_validations.dart';
import '../../../custom_widgets/Fields/input_field.dart';
import '../../../custom_widgets/custom_dropdown.dart';
import '../../../custom_widgets/custom_toasty.dart';
import '../../../models/DepositAccountResponse.dart';
import '../../../models/ExchangeRate.dart';
import '../../../models/SendTransactionStep1ResponseModel.dart';
import '../../../models/TransactionPinRequestModel.dart';
import '../../../models/TransactionSubmitRequestModel.dart';
import '../../../routes/app_pages.dart';


class InternalAccountTransController extends GetxController {
  TextEditingController pinPutController = TextEditingController();
  final AppRepositories repository = Get.find<AppRepositories>();
  BuildContext context = Get.context as BuildContext;

  //drop down
  RxList<DropDown> allFromAccounts = RxList.empty();
  Rx<DepositAccount> selectedFromAccount = DepositAccount.empty().obs;

  RxList<DropDown> allToAccounts = RxList.empty();
  Rx<DepositAccount> selectedToAccount = DepositAccount.empty().obs;
  ExchangeRate? selectedExchangeRate;

  TextEditingController referenceCodeController = TextEditingController();

  // fields
  late InputField fromAccountField;
  late InputField toAccountField;
  late InputField sendingAmountField;
  late InputField exchangeRateField;
  late InputField messageField;
  late InputField userTransactionPinField;
  late InputField referenceCodeField;

  @override
  void onInit() {
    super.onInit();
    for (int i = 0; i < SessionCache.instance.depositAccountList.length; i++) {
      DepositAccount depositAccount = SessionCache.instance.depositAccountList.elementAt(i);
      allFromAccounts.add(DropDown(depositAccount.mbmBkmsnumber, "${depositAccount.mbmBkmstitle} - ${depositAccount.mbmBkmsnumber}", depositAccount));
    }
  }

  @override
  Future<void> onReady() async {
    super.onReady();
    disposeAllResources();
    onFromAccountSelection(allFromAccounts.elementAt(0));
    fromAccountField.setText((allFromAccounts.first.label));
  }

  void onFromAccountSelection(DropDown value) {
    if (value.id == selectedToAccount.value.mbmBkmsnumber) {
      Toasty.error('This account is already selected');
      fromAccountField.setText("");
      selectedFromAccount.value = DepositAccount.empty();
    } else {
      selectedFromAccount.value = value.data as DepositAccount;
    }
  }

  void onToAccountSelection(DropDown value) {
    if (value.id == selectedFromAccount.value.mbmBkmsnumber) {
      Toasty.error('This account is already selected');
      toAccountField.setText("");
      selectedToAccount.value = DepositAccount.empty();
    } else {
      selectedToAccount.value = value.data as DepositAccount;
    }

    if (selectedToAccount.value.mbmBkmsnumber.isEmpty) {
      return;
    }
    for (int i = 0; i < SessionCache.instance.exchangeRateList.length; i++) {
      if (SessionCache.instance.exchangeRateList.elementAt(i).pcrCurrcode == selectedToAccount.value.pcrCurrcode) {
        selectedExchangeRate = SessionCache.instance.exchangeRateList.elementAt(i);
        exchangeRateField.setText(selectedExchangeRate!.perEratrateact.toString());
        break;
      }
    }
  }

  void disposeAllResources() {
    fromAccountField.clear();
    toAccountField.clear();
    sendingAmountField.clear();
    exchangeRateField.clear();
    messageField.clear();
    userTransactionPinField.clear();
    referenceCodeField.clear();
    referenceCodeController.clear();
  }

  bool validate() {
    bool isValid = FieldValidation.validateAll([
      fromAccountField,
      toAccountField,
      sendingAmountField,
      exchangeRateField,
      userTransactionPinField,
      referenceCodeField,
    ]);
    if (pinPutController.text.isEmpty) {
      return false;
    }
    if (referenceCodeController.text.isEmpty) {
      return false;
    }
    return isValid;
  }

  /// Send Transaction function
  Future<void> sendTransaction() async {
    if (!validate()) {
      Toasty.error("Please input and then proceed");
      return;
    }

    TransactionSubmitRequestModel transactionSubmitRequestModel = TransactionSubmitRequestModel(
      porOrgacode: RequestConstants.porOrgacode,
      pctCstycode: RequestConstants.pctCstycode,
      channelCode: RequestConstants.channelCode,
      cmpCustcode: SessionCache.instance.userInfo.cmpCustcode,
      drMbmBkmsnumber: selectedFromAccount.value.mbmBkmsnumber,
      drMbmBkmstitle: selectedFromAccount.value.mbmBkmstitle,
      drPcrCurrcode: selectedFromAccount.value.pcrCurrcode,
      drPcrCurrdesc: selectedFromAccount.value.pcrCurrdesc,
      drPcrCurrshort: selectedFromAccount.value.pcrCurrshort,
      crMbmBkmsnumber: selectedToAccount.value.mbmBkmsnumber,
      crMbmBkmstitle: selectedToAccount.value.mbmBkmstitle,
      crPcrCurrcode: selectedExchangeRate!.pcrCurrcode,
      crPcrCurrdesc: selectedExchangeRate!.pcrCurrdesc,
      crPcrCurrshort: selectedExchangeRate!.pcrCurrshort,
      sgtGntrnarration: "",
      dmpProdCode: selectedFromAccount.value.dmpProdcode,
      transType: "DR",
      notificationId: "",
      transMode: "Online",
      sgtGntramtfc: double.parse(sendingAmountField.getCustomText().isEmpty ? "0.0" : sendingAmountField.getCustomText()),
      otdTrancomment: messageField.getCustomText(),
      isOtpRequired: false,
      cmpRefcode: referenceCodeField.getCustomText(),
    );

    dp("********************>>>>>>>>>>>>******************", transactionSubmitRequestModel);
    TransactionPinRequestModel transactionPinRequestModel = TransactionPinRequestModel(
      porOrgacode: RequestConstants.porOrgacode,
      pctCstycode: RequestConstants.pctCstycode,
      channelCode: RequestConstants.channelCode,
      cmpCustcode: SessionCache.instance.userInfo.cmpCustcode,
      email: SessionCache.instance.userInfo.cmpUserId,
      pinType: "TRAN",
      transPincode: userTransactionPinField.getCustomText(),
      isOtpRequired: false,
    );

    ServerResponse response = await repository.sendTransactionStep1(transactionPinRequestModel);
    if (response.isError) {
      Toasty.error(response.errorMsg);
      return;
    }
    SendTransactionStep1ResponseModel step1responseModel = SendTransactionStep1ResponseModel.fromMap(response.response);
    transactionSubmitRequestModel.notificationId = step1responseModel.notificationId.toString();
    Get.toNamed(Routes.INTERNAL_TRANSACTION_OPT,
    arguments: {
      AppConstants.SEND_TRANS_STEP1_DATA: transactionSubmitRequestModel,
      AppConstants.INTERNAL_TRANSACTION_PIN_REQUEST: transactionPinRequestModel,
      AppConstants.EXCHANGE_RATE: exchangeRateField.getCustomText(),
    });
  }

  void clearTransaction() {
    toAccountField.clear();
    sendingAmountField.clear();
    exchangeRateField.clear();
    messageField.clear();
    userTransactionPinField.clear();
    pinPutController.clear();
    referenceCodeField.clear();
    referenceCodeController.clear();
  }
}
