import 'dart:convert';

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


import '../../../core/config/server_response.dart';
import '../../../core/constants/app_contants.dart';
import '../../../core/constants/translation_keys.dart';
import '../../../core/data/repositories/app_repositories.dart';
import '../../../core/utils/SessionCache.dart';
import '../../../core/utils/app_utils.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_dropdown.dart';
import '../../../custom_widgets/custom_toasty.dart';
import '../../../models/AccountInquiryResponseModel.dart';
import '../../../models/BeneficiaryAccountModel.dart';
import '../../../models/ExchangeRate.dart';
import '../../../res/app_colors.dart';
import '../../../routes/app_pages.dart';
import '../../qr_setting/controllers/qr_setting_controller.dart';
import '../../qr_setting/views/qr_scan_screen.dart';

class NewBeneficiaryController extends GetxController {
  String OPTION_PHONE = "01";
  String OPTION_EMAIL = "02";
  final AppRepositories repository = Get.find<AppRepositories>();
  BuildContext context = Get.context as BuildContext;

  RxList<DropDown> allRecipientDetailOptions = RxList.empty();
  Rx<DropDown> selectedRecipientDetailOption = DropDown.empty().obs;

  String className = "";
  late InputField selectRecipientDetailField;
  late InputField identityPhoneNumberField;
  late InputField identityEmailField;
  late InputField recipientCardNameField;
  late InputField accountNumberField;
  late InputField nickNameField;
  late InputField accountTitleField;

  late InputField emailIDField;
  late InputField phoneNumberField;

  String receiverAccountNumber = "";
  String receiverAccountTitle = "";
  RxString currencySymbol = "".obs;
  Contact? selectedContact;
  ExchangeRate? selectedExchangeRate;

  @override
  void onInit() {
    super.onInit();
    allRecipientDetailOptions.value = <DropDown>[
      DropDown(OPTION_PHONE, TranslationKeys.makeTranslation(TranslationKeys.textPhoneNumber)),
      DropDown(OPTION_EMAIL, TranslationKeys.makeTranslation(TranslationKeys.textEmail)),
    ];
  }

  /// Validate Method
  bool validate() {
    bool isValid = FieldValidation.validateAll([
      accountTitleField,
      accountNumberField,
      nickNameField,
      selectRecipientDetailField,
      identityEmailField,
      accountNumberField,
      emailIDField,
      phoneNumberField,
    ]);

    if (selectedRecipientDetailOption.value.id == OPTION_PHONE) {
      isValid = FieldValidation.validateAll([identityPhoneNumberField]);
    } else if (selectedRecipientDetailOption.value.id == OPTION_EMAIL) {
      isValid = FieldValidation.validateAll([identityEmailField]);
    }
    return isValid;
  }

  /// Request Method
  Future<void> addToNewBeneficiary({navigate = true}) async {
    if (!validate()) {
      Toasty.error("Please input and then proceed");
      return;
    }
    BeneficiaryAccountModel beneficiaryAccountModel = BeneficiaryAccountModel(
      porOrgacode: SessionCache.instance.userInfo.porOrgacode,
      email: SessionCache.instance.userInfo.cmpUserId,
      pcrCurrcode: selectedExchangeRate!.pcrCurrcode,
      pcrCurrdesc: selectedExchangeRate!.pcrCurrdesc,
      pcrCurrshort: selectedExchangeRate!.pcrCurrshort,
      mbmBkmstitleRef: receiverAccountTitle,
      mbmBkmsnumberRef: receiverAccountNumber,
      refPhoneNumber: "",
      refEmail: "",
      refNickName: nickNameField.getCustomText(),
    );
    ServerResponse response = await repository.addNewBeneficiary(beneficiaryAccountModel);
    if (response.isError) {
      Toasty.error(response.errorMsg);
      return;
    }
    CustomDialog.showSuccessDialog(
        description: "You are successfully add new Beneficiary",
        onTapPositive: () {
          Get.back(result: true);
        });
    clearNewBeneficiaryControllers();
  }

  void updateRecipientDetail(DropDown? item) {
    selectedRecipientDetailOption.value = item!;
  }

  Future<void> selectContact() async {
    dynamic result = await Get.toNamed(Routes.CONTACTS_SCREEN);

    if ((result != null && result[AppConstants.SELECTED_CONTACT] != null)) {
      selectedContact = result[AppConstants.SELECTED_CONTACT];
      identityPhoneNumberField.setText(AppUtils.formatPhoneNumber(selectedContact!.phones.first.number) /*"${selectedContact!.displayName} (${AppUtils.formatPhoneNumber(selectedContact!.phones.first.number + ")")}"*/);
    }
  }

  void scanQr() async {
    Get.put(QrSettingController());
    var scanResult = await Get.to(() => const QrScanScreen());
    var resultJson = jsonDecode(scanResult);
    var accNumber = resultJson["phoneNumber"];
    identityPhoneNumberField.setText(accNumber);
    verifyAccountAgainstIt();
  }

  Future<void> verifyAccountAgainstIt() async {
    String valua = selectedRecipientDetailOption.value.id == OPTION_PHONE ? identityPhoneNumberField.getCustomText() : (selectedRecipientDetailOption.value.id == OPTION_EMAIL ? identityEmailField.getCustomText() : "");
    bool isValid = true;
    if (selectedRecipientDetailOption.value.id == OPTION_PHONE) {
      isValid = FieldValidation.validateAll([identityPhoneNumberField]);
    } else if (selectedRecipientDetailOption.value.id == OPTION_EMAIL) {
      isValid = FieldValidation.validateAll([identityEmailField]);
    }
    if (!isValid) {
      Toasty.error("Please input and then proceed");
      return;
    }

    ServerResponse response = await repository.fetchAccountInquiry(selectedRecipientDetailOption.value.id, valua);

    if (response.isError) {
      if (selectedRecipientDetailOption.value.id == OPTION_PHONE) {
        identityPhoneNumberField.setError(response.errorMsg);
      } else {
        identityEmailField.setError(response.errorMsg);
      }
      return;
    }
    List<dynamic> responseData = response.response ?? [];
    List<AccountInquiryResponseModel> accountInquiryList;
    accountInquiryList = AccountInquiryResponseModel.fromList(responseData);

    accountsDialog(accountInquiryList);
    AccountInquiryResponseModel transactionSubmitRequestModel = AccountInquiryResponseModel.fromMap(((response.response ?? {}) as Map<Object?, Object?>).map((key, value) => MapEntry(key.toString(), value)));
  }

  void updateSelectedCurrency(/*DropDown? item*/ AccountInquiryResponseModel model) {
    print("************************model>> $model");

    for (int i = 0; i < SessionCache.instance.exchangeRateList.length; i++) {
      print("************************elementAt(i).pcrCurrcode>> ${SessionCache.instance.exchangeRateList.elementAt(i).pcrCurrcode}");
      if (SessionCache.instance.exchangeRateList.elementAt(i).pcrCurrcode == model.pcrCurrcode) {
        currencySymbol.value = SessionCache.instance.exchangeRateList.elementAt(i).pcrCurrshort;
        selectedExchangeRate = SessionCache.instance.exchangeRateList.elementAt(i);
        // exchangeRateField.setText(selectedExchangeRate!.perEratrateact.toString());
        break;
      }
    }
  }

  void accountsDialog(List<AccountInquiryResponseModel> accountInquiryList) {
    if (accountInquiryList.length == 1) {
      receiverAccountTitle = accountInquiryList.first.mbmBkmstitle;
      receiverAccountNumber = accountInquiryList.first.mbmBkmsnumber;
      recipientCardNameField.setText(receiverAccountTitle);
      updateSelectedCurrency(accountInquiryList.first);
      return;
    }
    Get.dialog(
      responsiveWidget(
        Dialog(
          backgroundColor: Colors.transparent,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          child: Container(
            decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10.0)),
            ),
            child: SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.all(10),
                child: ListView(
                  physics: const NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  children: [
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(TranslationKeys.makeTranslation(TranslationKeys.textSelectAccount), style: Theme.of(context).textTheme.titleMedium),
                        const SizedBox(height: 20),
                        ListView.separated(
                            shrinkWrap: true,
                            itemBuilder: (context, index) {
                              return GestureDetector(
                                onTap: () {
                                  receiverAccountTitle = accountInquiryList[index].mbmBkmstitle;
                                  receiverAccountNumber = accountInquiryList[index].mbmBkmsnumber;
                                  recipientCardNameField.setText(receiverAccountTitle);
                                  updateSelectedCurrency(accountInquiryList[index]);
                                  Get.back();
                                },
                                child: Column(children: [
                                  Container(
                                    height: 40,
                                    width: double.infinity,
                                    decoration: const BoxDecoration(
                                      color: AppColors.colorGrey100,
                                      borderRadius: BorderRadius.all(Radius.circular(8.0)),
                                    ),
                                    child: Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text("${accountInquiryList[index].mbmBkmstitle} (${accountInquiryList[index].pcrCurrshort})", style: Theme.of(context).textTheme.titleSmall),
                                          Text(accountInquiryList[index].mbmBkmsnumber, style: Theme.of(context).textTheme.titleSmall),
                                        ],
                                      ),
                                    ),
                                  ),
                                ]),
                              );
                            },
                            separatorBuilder: (BuildContext context, int index) {
                              return const Padding(padding: EdgeInsets.symmetric(vertical: 5));
                            },
                            itemCount: accountInquiryList.length),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
      barrierDismissible: false,
    );
  }

  /// Clear Controllers Method
  void clearNewBeneficiaryControllers() {
    accountTitleField.clear();
    nickNameField.clear();
    selectRecipientDetailField.clear();
    identityPhoneNumberField.clear();
    recipientCardNameField.clear();
    identityEmailField.clear();
    accountNumberField.clear();
    emailIDField.clear();
    phoneNumberField.clear();
  }
}
