import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:uco_mobile_poc/app/core/constants/app_assets.dart';
import 'package:uco_mobile_poc/app/core/constants/form_field_constants.dart';
import 'package:uco_mobile_poc/app/core/constants/translation_keys.dart';
import 'package:uco_mobile_poc/app/core/utils/fields_utils.dart';
import 'package:uco_mobile_poc/app/custom_widgets/Fields/input_field.dart';
import 'package:uco_mobile_poc/app/custom_widgets/custom_app_bar.dart';
import 'package:uco_mobile_poc/app/custom_widgets/custom_button.dart';
import 'package:uco_mobile_poc/app/custom_widgets/custom_toasty.dart';
import 'package:uco_mobile_poc/app/models/AccountInquiryResponseModel.dart';
import 'package:uco_mobile_poc/app/res/app_colors.dart';
import 'package:uco_mobile_poc/app/routes/app_pages.dart';

import '../controllers/u_send_controller.dart';

class USendView extends GetView<USendController> {
  const USendView({Key? key, this.showAppBar = true}) : super(key: key);

  final bool showAppBar;

  @override
  Widget build(BuildContext context) {
    Get.put(USendController());

    String className = runtimeType.toString().split('.').last;

    return Scaffold(
      appBar: showAppBar
          ? DashBoardAppBar(
              title: TranslationKeys.makeTranslation(TranslationKeys.textUSend),
              onBackButtonPressed: () {
                Get.back();
              },
            )
          : null,
      body: Obx(() {
        return Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
                  child: Card(
                    color: AppColors.colorGrey50,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          controller.depositAccountField = InputField(
                            enableInteractiveSelection: false,
                            refKey: FormFieldConstants.instance().getFormKey("${className}depositAccountField"),
                            controller: FormFieldConstants.instance().getController("${className}depositAccountField"),
                            labelText: "Select From Account",
                            isDropDown: true,
                            hintText: "Select from account",
                            dropDownType: DropDownType.SPECIAL,
                            isRequired: true,
                            items: controller.allDepositAccounts,
                            onItemSelected: (item) {
                              controller.updateSelectedDeposit(item!);
                            },
                          ),
                          controller.selectRecipientDetailField = InputField(
                            refKey: FormFieldConstants.instance().getFormKey("${className}selectRecipientDetailField"),
                            controller: FormFieldConstants.instance().getController("${className}selectRecipientDetailField"),
                            labelText: "Recipient Detail",
                            isDropDown: true,
                            hintText: "Select recipient detail",
                            dropDownType: DropDownType.SPECIAL,
                            items: controller.allRecipientDetailOptions,
                            onItemSelected: (item) {
                              controller.updateRecipientDetail(item);
                            },
                          ),
                          Column(
                            children: [
                              Visibility(
                                visible: controller.selectedRecipientDetailOption.value.id == controller.OPTION_PHONE,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Expanded(
                                        flex: 8,
                                        child: controller.identityPhoneNumberField = InputField(
                                          enableInteractiveSelection: false,
                                          maxLines: 1,
                                          keyboardType: TextInputType.phone,
                                          refKey: FormFieldConstants.instance().getFormKey("${className}identityPhoneNumberField"),
                                          controller: FormFieldConstants.instance().getController("${className}identityPhoneNumberField"),
                                          labelText: TranslationKeys.makeTranslation(TranslationKeys.textPhoneNumber),
                                          hintText: "Select phone number",
                                          onChanged: (val) {
                                            controller.recipientCardNameField.clear();
                                          },
                                          isCountryPicker: true,
                                          suffixIcon: SizedBox(
                                            width: 70,
                                            child: Row(
                                              children: [
                                                GestureDetector(
                                                    onTap: () {
                                                      controller.scanQr();
                                                    },
                                                    child: const Icon(Icons.qr_code, size: 25, color: AppColors.colorPrimary)),
                                                const SizedBox(
                                                  width: 8,
                                                ),
                                                InkWell(
                                                  customBorder: RoundedRectangleBorder(
                                                    borderRadius: BorderRadius.circular(50),
                                                  ),
                                                  onTap: () {
                                                    controller.selectContact();
                                                  },
                                                  child: Padding(
                                                    padding: const EdgeInsets.all(5.0),
                                                    child: SvgPicture.asset(AppAssets.ic_select_contact, height: 25, width: 25),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                          // readOnly: true,
                                          showCursor: false,
                                          onClick: () {
                                            controller.selectContact();
                                          },
                                        )),
                                    const SizedBox(width: 10),
                                    Expanded(
                                      flex: 2,
                                      child: Column(
                                        children: [
                                          const SizedBox(height: 35),
                                          CustomButton(
                                              onPressed: () {
                                                FocusScope.of(context).requestFocus(FocusNode());
                                                controller.verifyAccountAgainstIt();
                                              },
                                              textStyle: context.textTheme.bodyMedium!.copyWith(fontSize: 11, fontWeight: FontWeight.w500, color: Colors.white),
                                              buttonText: TranslationKeys.makeTranslation(TranslationKeys.textVerify),
                                              buttonPadding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
                                              buttonColor: AppColors.colorButton),
                                        ],
                                      ),
                                    )
                                  ],
                                ),
                              ),
                              Visibility(
                                visible: controller.selectedRecipientDetailOption.value.id == controller.OPTION_EMAIL,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Expanded(
                                        flex: 8,
                                        child: controller.identityEmailField = InputField(
                                          enableInteractiveSelection: false,
                                          maxLines: 1,
                                          textInputAction: TextInputAction.done,
                                          keyboardType: TextInputType.emailAddress,
                                          refKey: FormFieldConstants.instance().getFormKey("${className}identityEmailField"),
                                          controller: FormFieldConstants.instance().getController("${className}identityEmailField"),
                                          labelText: TranslationKeys.makeTranslation(TranslationKeys.textEmail),
                                          hintText: "Enter your email",
                                          onChanged: (val) {
                                            controller.recipientCardNameField.clear();
                                          },
                                          // readOnly: true,
                                          showCursor: false,
                                          onClick: () {
                                            controller.selectContact();
                                          },
                                        )),
                                    const SizedBox(width: 10),
                                    Expanded(
                                      flex: 2,
                                      child: Column(
                                        children: [
                                          const SizedBox(height: 35),
                                          CustomButton(
                                              onPressed: () {
                                                FocusScope.of(context).requestFocus(FocusNode());
                                                controller.verifyAccountAgainstIt();
                                              },
                                              textStyle: context.textTheme.bodyMedium!.copyWith(fontSize: 11, fontWeight: FontWeight.w500, color: Colors.white),
                                              buttonText: TranslationKeys.makeTranslation(TranslationKeys.textVerify),
                                              buttonPadding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
                                              buttonColor: AppColors.colorButton),
                                        ],
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            ],
                          ),
                          controller.recipientCardNameField = InputField(
                            enableInteractiveSelection: false,
                            refKey: FormFieldConstants.instance().getFormKey("${className}recipientCardNameField"),
                            controller: FormFieldConstants.instance().getController("${className}recipientCardNameField"),
                            labelText: TranslationKeys.makeTranslation("Account Title"),
                            hintText: "Account title",
                            readOnly: true,
                            showCursor: false,
                          ),
                          controller.selectCurrencyField = InputField(
                            refKey: FormFieldConstants.instance().getFormKey("${className}selectCurrencyField"),
                            controller: FormFieldConstants.instance().getController("${className}selectCurrencyField"),
                            labelText: "Select Currency",
                            isDropDown: true,
                            hintText: "Select currency field",
                            dropDownType: DropDownType.SPECIAL,
                            items: controller.allCurrencieList,
                            onItemSelected: (item) {
                              controller.updateSelectedCurrency(item);
                            },
                            suffixIcon: SizedBox(
                              width: 100,
                              height: 25,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  Image.asset(AppAssets.ic_arrow_down_icon, height: 15, width: 15, color: AppColors.colorGrey500),
                                  const SizedBox(width: 10),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    children: [
                                      Container(
                                        width: 50,
                                        decoration: const BoxDecoration(
                                          color: AppColors.colorPrimary,
                                          borderRadius: BorderRadius.only(
                                            topRight: Radius.circular(50),
                                            bottomRight: Radius.circular(50),
                                          ),
                                        ),
                                        child: Center(
                                          child: Text(
                                            controller.currencySymbol.value,
                                            style: const TextStyle(color: AppColors.white, fontSize: 12, fontWeight: FontWeight.w600),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),
                          Row(
                            children: [
                              Expanded(
                                flex: 1,
                                child: controller.sendingAmountField = InputField(
                                  enableInteractiveSelection: false,
                                  maxLines: 1,
                                  textInputAction: TextInputAction.done,
                                  refKey: FormFieldConstants.instance().getFormKey("${className}sendingAmountField"),
                                  controller: FormFieldConstants.instance().getController("${className}sendingAmountField"),
                                  labelText: TranslationKeys.makeTranslation(TranslationKeys.textSendingAmount),
                                  hintText: TranslationKeys.makeTranslation(TranslationKeys.textSendingAmount),
                                  isRequired: true,
                                  keyboardType: const TextInputType.numberWithOptions(decimal: true),
                                  inputFormatters: InputType.maxValueFilter(InputType.INT_MAX_VALUE_, true, 2),
                                ),
                              ),
                              const SizedBox(width: 10),
                              Expanded(
                                flex: 1,
                                child: controller.exchangeRateField = InputField(
                                  enableInteractiveSelection: false,
                                  refKey: FormFieldConstants.instance().getFormKey("${className}exchangeRateField"),
                                  controller: FormFieldConstants.instance().getController("${className}exchangeRateField"),
                                  hintText: TranslationKeys.makeTranslation(TranslationKeys.textExchangeRate),
                                  labelText: TranslationKeys.makeTranslation(TranslationKeys.textExchangeRate),
                                  readOnly: true,
                                  showCursor: false,
                                ),
                              ),
                            ],
                          ),
                          controller.userTransactionPinField = InputField(
                            enableInteractiveSelection: false,
                            refKey: FormFieldConstants.instance().getFormKey("${className}userTransactionPinField"),
                            controller: FormFieldConstants.instance().getController("${className}userTransactionPinField"),
                            hintText: "Enter transaction pin",
                            labelText: "Transaction Pin",
                            readOnly: true,
                            showCursor: false,
                            requiredPasswordIcon: true,
                            isRequired: true,
                            isPassword: true,
                            inputFormatters: [LengthLimitingTextInputFormatter(FieldUtils.transactionPinLength), InputType.NUMBER],
                            onClick: () {
                              transactionPinDialog(context, controller);
                            },
                          ),
                          controller.referenceCodeField = InputField(
                            enableInteractiveSelection: false,
                            readOnly: true,
                            showCursor: false,
                            requiredPasswordIcon: true,
                            isRequired: true,
                            isPassword: true,
                            refKey: FormFieldConstants.instance().getFormKey("${className}referenceCodeField"),
                            controller: FormFieldConstants.instance().getController("${className}referenceCodeField"),
                            hintText: "Enter reference code",
                            labelText: TranslationKeys.makeTranslation(TranslationKeys.textReferenceCode),
                            inputFormatters: [LengthLimitingTextInputFormatter(FieldUtils.transactionPinLength), InputType.NUMBER],
                            onClick: () {
                              referenceCodeDialog(context, controller);
                            },
                          ),
                          controller.messageField = InputField(
                            enableInteractiveSelection: false,
                            maxLines: 1,
                            refKey: FormFieldConstants.instance().getFormKey("${className}messageField"),
                            controller: FormFieldConstants.instance().getController("${className}messageField"),
                            hintText: "Enter message",
                            labelText: TranslationKeys.makeTranslation(TranslationKeys.textMessageMemo),
                            onSubmitted: (value) {
                              controller.sendTransaction();
                            },
                          ),
                          const SizedBox(height: 20),
                          Row(
                            children: [
                              Expanded(
                                flex: 1,
                                child: CustomButton(
                                  onPressed: () {
                                    FocusScope.of(context).requestFocus(FocusNode());
                                    controller.sendTransaction();
                                  },
                                  buttonText: TranslationKeys.makeTranslation(TranslationKeys.textSend),
                                  buttonPadding: const EdgeInsets.symmetric(vertical: 11),
                                  textStyle: Theme.of(context).textTheme.titleSmall?.copyWith(color: AppColors.white),
                                  buttonColor: AppColors.colorButton,
                                ),
                              ),
                              const SizedBox(width: 10),
                              Expanded(
                                flex: 1,
                                child: CustomButton(
                                  onPressed: () {
                                    FocusScope.of(context).requestFocus(FocusNode());
                                    controller.clearTransaction();
                                  },
                                  buttonPadding: const EdgeInsets.symmetric(vertical: 11),
                                  buttonText: TranslationKeys.makeTranslation(TranslationKeys.textClear),
                                  buttonColor: AppColors.colorSkipBtn,
                                  textStyle: Theme.of(context).textTheme.titleSmall?.copyWith(color: AppColors.black),
                                  sideBorder: const BorderSide(color: AppColors.colorBorderSkipBtn, width: 1),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        );
      }),
    );
  }

  /// Pin Dialog...........Transactions
  void transactionPinDialog(BuildContext context, USendController controller) {
    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: [
                        const SizedBox(height: 10),
                        Text(TranslationKeys.makeTranslation(TranslationKeys.textTransactionPin), style: Theme.of(context).textTheme.titleMedium),
                        const SizedBox(height: 20),
                        Wrap(
                          children: [
                            PinCodeTextField(
                              autoDisposeControllers: false,
                              keyboardType: TextInputType.number,
                              controller: controller.pinPutController,
                              showCursor: true,
                              autoDismissKeyboard: false,
                              enablePinAutofill: true,
                              length: 6,
                              hintCharacter: "0",
                              appContext: context,
                              hintStyle: Theme.of(context).textTheme.bodySmall!.copyWith(
                                    fontSize: 35,
                                    fontWeight: FontWeight.w600,
                                    color: AppColors.colorGrey350,
                                  ),
                              mainAxisAlignment: MainAxisAlignment.center,
                              cursorColor: Colors.black.withOpacity(0.8),
                              obscureText: false,
                              animationType: AnimationType.fade,
                              textInputAction: TextInputAction.done,
                              pinTheme: PinTheme(
                                selectedColor: AppColors.colorGrey350,
                                /*Colors.black.withOpacity(0.6),*/
                                inactiveColor: AppColors.colorGrey350,
                                /*Colors.black.withOpacity(0.6),*/
                                activeColor: AppColors.colorGrey350,
                                fieldOuterPadding: const EdgeInsets.all(5),
                                shape: PinCodeFieldShape.box,
                                borderRadius: BorderRadius.circular(5),
                                fieldHeight: 50,
                                inactiveFillColor: AppColors.white,
                                selectedFillColor: AppColors.white,
                                fieldWidth: 40,
                                activeFillColor: Colors.white,
                              ),
                              animationDuration: const Duration(milliseconds: 100),
                              backgroundColor: Colors.transparent,
                              enableActiveFill: true,
                              onCompleted: (v) {},
                              onChanged: (value) {},
                              beforeTextPaste: (text) {
                                return true;
                              },
                            ),
                          ],
                        ),
                        const SizedBox(height: 20),
                        Padding(
                          padding: const EdgeInsets.only(left: 80.0, right: 80.0),
                          child: CustomButton(
                              onPressed: () async {
                                if (controller.pinPutController.text.length != 6) {
                                  Toasty.error("Please input 6 digit transaction pin");
                                  return;
                                }
                                controller.userTransactionPinField.setText(controller.pinPutController.text);
                                Navigator.of(context, rootNavigator: true).pop();
                              },
                              buttonText: TranslationKeys.makeTranslation(TranslationKeys.textContinue),
                              buttonPadding: const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
                              buttonColor: AppColors.colorButton),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
      barrierDismissible: false,
    );
  }

  /// Reference Dialog...........Transactions
  void referenceCodeDialog(BuildContext context, USendController controller) {
    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: [
                        const SizedBox(height: 10),
                        Text(TranslationKeys.makeTranslation(TranslationKeys.textReferenceCode), style: Theme.of(context).textTheme.titleMedium),
                        const SizedBox(height: 20),
                        Wrap(
                          children: [
                            PinCodeTextField(
                              autoDisposeControllers: false,
                              keyboardType: TextInputType.number,
                              controller: controller.referenceCodeController,
                              showCursor: true,
                              autoDismissKeyboard: false,
                              enablePinAutofill: true,
                              length: 6,
                              hintCharacter: "0",
                              appContext: context,
                              hintStyle: Theme.of(context).textTheme.bodySmall!.copyWith(
                                    fontSize: 35,
                                    fontWeight: FontWeight.w600,
                                    color: AppColors.colorGrey350,
                                  ),
                              mainAxisAlignment: MainAxisAlignment.center,
                              cursorColor: Colors.black.withOpacity(0.8),
                              obscureText: false,
                              animationType: AnimationType.fade,
                              textInputAction: TextInputAction.done,
                              pinTheme: PinTheme(
                                selectedColor: AppColors.colorGrey350,
                                /*Colors.black.withOpacity(0.6),*/
                                inactiveColor: AppColors.colorGrey350,
                                /*Colors.black.withOpacity(0.6),*/
                                activeColor: AppColors.colorGrey350,
                                fieldOuterPadding: const EdgeInsets.all(5),
                                shape: PinCodeFieldShape.box,
                                borderRadius: BorderRadius.circular(5),
                                fieldHeight: 50,
                                inactiveFillColor: AppColors.white,
                                selectedFillColor: AppColors.white,
                                fieldWidth: 40,
                                activeFillColor: Colors.white,
                              ),
                              animationDuration: const Duration(milliseconds: 100),
                              backgroundColor: Colors.transparent,
                              enableActiveFill: true,
                              onCompleted: (v) {},
                              onChanged: (value) {},
                              beforeTextPaste: (text) {
                                return true;
                              },
                            ),
                          ],
                        ),
                        const SizedBox(height: 20),
                        Padding(
                          padding: const EdgeInsets.only(left: 80.0, right: 80.0),
                          child: CustomButton(
                              onPressed: () async {
                                if (controller.referenceCodeController.text.length != 6) {
                                  Toasty.error("Please input 6 digit transaction pin");
                                  return;
                                }
                                controller.referenceCodeField.setText(controller.referenceCodeController.text);
                                Navigator.of(context, rootNavigator: true).pop();
                              },
                              buttonText: TranslationKeys.makeTranslation(TranslationKeys.textContinue),
                              buttonPadding: const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
                              buttonColor: AppColors.colorButton),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
      barrierDismissible: false,
    );
  }
}
