import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:uco_mobile_poc/app/modules/add_money/controllers/payment_method_controller.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 '../../../custom_widgets/Fields/field_validations.dart';
import '../../../custom_widgets/Fields/input_field.dart';
import '../../../custom_widgets/custom_dialog.dart';
import '../../../custom_widgets/custom_toasty.dart';
import '../../../models/DepositAccountResponse.dart';
import '../../../models/GLACCAddMoneyRequestModel.dart';
import '../../../models/TransactionPinRequestModel.dart';
import '../../../models/evaluated_cuency_model.dart';
import '../../../models/product_model.dart';
import '../../../routes/app_pages.dart';
import '../views/shared/account_list_screen.dart';

class AddMoneyController extends GetxController {
  final repository = Get.find<AppRepositories>();
  var paymnetController = Get.put<PaymentMethodController>(PaymentMethodController());
  TextEditingController recipientController = TextEditingController();
  TextEditingController pinPutController = TextEditingController();

  Rx<DepositAccount> selectRecepientAccount = Rx(DepositAccount.empty());

  List<ProductDepositModel> currencyList = [];
  List<ProductDepositModel> allCurrencyList = [];
  Rx<ProductDepositModel> selectedFromAccountCurrency = Rx(ProductDepositModel(porOrgacode: "", dmpProdcode: "", dmpProddesc: "", dmpProdshort: "", pcrCurrcode: "", dmpProdactive: false));

  Rx<EvaluatedCurrencyModel> evaluatedCurrencyModel = EvaluatedCurrencyModel.empty().obs;

  late InputField amountFeild;

  late InputField convertedFeild;

  late InputField searchCurrency;

  late InputField searchAccount;

  late InputField userTransactionPinField = InputField();

  List<DepositAccount> accountList = List.from(SessionCache.instance.depositAccountList);

  List<DepositAccount> allAccountList = List.from(SessionCache.instance.depositAccountList);

  @override
  void onInit() {
    getCurrencyList();
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();

    update();

    amountFeild.clear();
  }

  @override
  void dispose() {
    amountFeild.clear();
    super.dispose();
  }

  searchCurrencyM() {
    Future.delayed(const Duration(seconds: 1)).then(
      (value) {
        searchCurrency.clear();
        update();
        searchCurrency.controller!.addListener(
          () {
            searchCurrencyMethod();
          },
        );
      },
    );
  }

  searchAccountInit() {
    Future.delayed(const Duration(seconds: 1)).then(
      (value) {
        searchAccount.clear();
        update();
        searchAccount.controller!.addListener(
          () {
            searchAccountMethod();
          },
        );
      },
    );
  }

  void updateReceipentAccount(DepositAccount e) {
    selectRecepientAccount.value = e;
    update();
  }

  void updateFromAccountCurrency(ProductDepositModel fromAccountCurrecncy) {
    selectedFromAccountCurrency.value = fromAccountCurrecncy;
    update();
  }

  void showDialog(BuildContext context) {
    CustomDialog.showSuccessDialog(
        description: "Thank you so much, your payment has been added.",
        onTapPositive: () {
          Navigator.of(context, rootNavigator: true).pop();
          Get.offAndToNamed(Routes.DASHBOARD_SCREEN);
        });
  }

  String getFlagWithCurrencyCode(String currencyCode) {
    int currencyCodeInt = int.tryParse(currencyCode) ?? 0;

    if (currencyCodeInt == 586) {
      return "assets/uco/icons/ic_pakistan.png";
    } else if (currencyCodeInt == 997) {
      return "assets/uco/icons/usa.png";
    } else if (currencyCodeInt == 978) {
      return "assets/uco/icons/euro_flag.png";
    } else {
      return "";
    }
  }

  getConversionAmount() async {
    if (!validate()) {
      return;
    }

    if (selectRecepientAccount.value.pcrCurrcode.isEmpty) {
      Toasty.error("Please select recipient currency");
      return;
    }

    var converionResponce = await repository.getConvertedCurrency(
      selectedFromAccountCurrency.value.pcrCurrcode,
      selectRecepientAccount.value.pcrCurrcode,
      amountFeild.getCustomText(),
    );

    if (converionResponce.isError) {
      Toasty.error(converionResponce.errorMsg);
      return;
    }
    evaluatedCurrencyModel.value = EvaluatedCurrencyModel.fromMap(converionResponce.response);
    recipientController.text = evaluatedCurrencyModel.value.sgtGntramtfc.toStringAsFixed(2);
  }

  getCurrencyList() async {
    var responce = await repository.getCurrencyList();
    if (responce.isError) {
      Toasty.error(responce.errorMsg);
      return;
    }
    currencyList = ProductDepositModel.productListFromJson(responce.response);
    allCurrencyList.addAll(currencyList);
    selectedFromAccountCurrency.value = currencyList.first;

    selectRecepientAccount.value = accountList.first;
    update();
  }

  bool validate() {
    if (selectRecepientAccount.value.pcrCurrcode.isEmpty || paymnetController.paymentMethod.value.title.isEmpty || paymnetController.paymentMethod.value.title.isEmpty) {
      return false;
    }
    return FieldValidation.validateAll([amountFeild]);
  }

  bool checkForNull() {
    if (evaluatedCurrencyModel.value.pcrCurrcode == null || evaluatedCurrencyModel.value.serviceCharges == null || evaluatedCurrencyModel.value.sgtGntramtfc == null || evaluatedCurrencyModel.value.targetPerEratrateact == null) {
        return true;
    }
    return false;
  }

  Future<void> navigateToNextScreen() async {
    if (!validate()) {
      if (amountFeild.getCustomText().trim().isEmpty) {
        Toasty.error("Please Input amount and then proceed");
        return;
      }
      if (paymnetController.paymentMethod.value.title.isEmpty) {
        Toasty.error("Please select payment method and then proceed");
        return;
      }
    }
    await getConversionAmount();
    GLACCAddMoneyRequestModel requestModel = GLACCAddMoneyRequestModel(
      porOrgacode: RequestConstants.porOrgacode,
      pctCstycode: RequestConstants.pctCstycode,
      channelCode: RequestConstants.channelCode,
      cmpCustcode: SessionCache.instance.userInfo.cmpCustcode,
      drPcaGlaccode: "",
      drPcaGlacdesc: "",
      crMbmBkmsnumber: selectRecepientAccount.value.mbmBkmsnumber,
      crMbmBkmstitle: selectRecepientAccount.value.mbmBkmstitle,
      crPcrCurrcode: selectRecepientAccount.value.pcrCurrcode,
      crPcrCurrdesc: selectRecepientAccount.value.pcrCurrdesc,
      crPcrCurrshort: selectRecepientAccount.value.pcrCurrshort,
      sgtGntrnarration: "",
      dmpProdCode: selectRecepientAccount.value.dmpProdcode,
      notificationId: "",
      transMode: "Online",
      sgtGntramtfc: double.parse(recipientController.text.isEmpty ? "0.0" : recipientController.text),
      otdTrancomment: "",
      obpPincode: "",
      transType: "",
      pinType: "",
    );

    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,
    );

    Get.toNamed(
      Routes.GENERAL_LEDGER,
      arguments: {
        AppConstants.SEND_TRANS_STEP1_DATA: requestModel,
        AppConstants.EXCHANGE_RATE: evaluatedCurrencyModel.value,
      },
    );
  }

  void selectFromAccountCurrency() {
    Get.to(() => AccountListScreen())!.then(
      (value) {
        getConversionAmount();
      },
    );
  }

  void searchCurrencyMethod() async {
    var search = searchCurrency.getCustomText().toLowerCase();
    currencyList.clear();
    update();
    await Future.delayed(Duration(milliseconds: 100));
    if (search.isNotEmpty) {
      currencyList = allCurrencyList
          .where(
            (element) => element.dmpProddesc.toLowerCase().contains(search) || element.dmpProdshort.toLowerCase().contains(search) || element.dmpProddesc.toLowerCase().contains(search),
          )
          .toList();
    } else {
      currencyList.addAll(allCurrencyList);
    }

    update();
  }

  void searchAccountMethod() async {
    var accountText = searchAccount.getCustomText().toLowerCase();

    accountList.clear();

    update();

    if (accountText.isNotEmpty) {
      accountList = allAccountList
          .where(
            (element) => element.mbmBkmsnumber.toLowerCase().contains(accountText) || element.dmpProddesc.toLowerCase().contains(accountText) || element.pcrCurrcode.toLowerCase().contains(accountText) || element.mbmBkmstitle.toLowerCase().contains(accountText),
          )
          .toList();
    } else {
      accountList.addAll(allAccountList);
    }

    update();
  }
}
