import 'package:flutter/material.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/config/server_response.dart';
import 'package:uco_mobile_poc/app/core/constants/app_assets.dart';
import 'package:uco_mobile_poc/app/core/constants/translation_keys.dart';
import 'package:uco_mobile_poc/app/core/extensions/build_context_ext.dart';
import 'package:uco_mobile_poc/app/core/utils/SessionCache.dart';
import 'package:uco_mobile_poc/app/core/utils/logs_utils.dart';
import 'package:uco_mobile_poc/app/custom_widgets/Fields/input_field.dart';
import 'package:uco_mobile_poc/app/custom_widgets/custom_button.dart';
import 'package:uco_mobile_poc/app/custom_widgets/custom_dropdown.dart';
import 'package:uco_mobile_poc/app/custom_widgets/custom_toasty.dart';
import 'package:uco_mobile_poc/app/models/DepositAccountResponse.dart';
import 'package:uco_mobile_poc/app/models/accept_receive_transaction.dart';
import 'package:uco_mobile_poc/app/res/app_colors.dart';
import 'package:uco_mobile_poc/app/routes/app_pages.dart';

import '../../../core/data/repositories/app_repositories.dart';
import '../../../models/reverse_transaction_model.dart';
import '../../../models/u_recived_responce_model.dart';
import '../../dashboard/controllers/dashboard_screen_controller.dart';

class UReceivedController extends GetxController {
  final AppRepositories repository = Get.find<AppRepositories>();
  BuildContext context = Get.context as BuildContext;
  UReceivedResponseData? selectedTransaction;
  RxList<UReceivedResponseData> uReceivedData = RxList.empty();
  String className = "";
  late InputField depositAccountField;
  late InputField referenceCodeField;
  TextEditingController pinPutController = TextEditingController();

  TextEditingController referenceCodeController = TextEditingController();

  late InputField userTransactionPinField;
  RxList<DropDown> allDepositAccounts = RxList.empty();

  Rx<DepositAccount> selectedDepositAccount = DepositAccount.empty().obs;

  @override
  Future<void> onReady() async {
    super.onReady();

    Future.delayed(Duration.zero).then((value) {
      selectedDepositAccount.value = allDepositAccounts.first.data as DepositAccount;

      depositAccountField.setText(allDepositAccounts.first.label);

      getPendingTransition();
    });
  }

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

    for (int i = 0; i < SessionCache.instance.depositAccountList.length; i++) {
      DepositAccount depositAccount = SessionCache.instance.depositAccountList.elementAt(i);

      allDepositAccounts.add(
        DropDown(i.toString(), "${depositAccount.mbmBkmstitle} - ${depositAccount.mbmBkmsnumber}", depositAccount),
      );
    }
  }

  void updateSelectedDeposit(DropDown item) {
    selectedDepositAccount.value = item.data as DepositAccount;
    getPendingTransition();

    dp("Data update", item);
  }

  Future<void> getPendingTransition() async {
    ServerResponse response = await repository.getPendingTransition(selectedDepositAccount.value.mbmBkmsnumber);
    dp("=========== u received request ", response.toString());
    if (response.isError) {
      Toasty.error(response.errorMsg);
      return;
    }

    uReceivedData.assignAll(List<UReceivedResponseData>.from(((response.response ?? []) as List<dynamic>).map((x) => UReceivedResponseData.fromMap(x))));

    transitionUpdate.value++;

    dp("=========== u received request ", uReceivedData.toString());
  }

  void transactionPinDialog(BuildContext context, UReceivedController controller) {
    clearController();
    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,
                              textInputAction: TextInputAction.done,
                              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,
                              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),
                        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.pinPutController.text.length != 6) {
                                  Toasty.error("Please input 6 digit transaction pin");
                                  return;
                                }
                                if (controller.referenceCodeController.text.length != 6) {
                                  Toasty.error("Please input 6 digit reference number");
                                  return;
                                }

                                Navigator.of(context, rootNavigator: true).pop();
                                sendAcceptTransactionRequest(controller.pinPutController.text, controller.referenceCodeController.text);
                              },
                              buttonText: TranslationKeys.makeTranslation(TranslationKeys.textContinue),
                              buttonPadding: const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
                              buttonColor: AppColors.colorButton),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
      barrierDismissible: false,
    );
  }

  Future<void> acceptTransaction(UReceivedResponseData data) async {
    selectedTransaction = data;
    transactionPinDialog(context, this);
  }

  Future<void> sendAcceptTransactionRequest(String pin, String referanceCode) async {
    AcceptReceiveTransactionModel request = AcceptReceiveTransactionModel(
      porOrgacode: SessionCache.instance.userInfo.porOrgacode,
      cmpCustcode: SessionCache.instance.userInfo.cmpCustcode,
      cmpTranpin: pin,
      cmpRefcode: referanceCode,
      id: selectedTransaction!.id,
      isAccepted: true,
    );

    ServerResponse response = await repository.acceptReceiveTransaction(request);
    if (response.isError) {
      Toasty.error(response.errorMsg);
      return;
    }

    showCongratulationDialogOtp(context);
  }

  /// Reverse transaction method
  Future<void> reverseTransactionRequest(String sgtSentGntrnumber, String sgtSentNodeId) async {
    ReverseTransactionModel request = ReverseTransactionModel(
      porOrgacode: SessionCache.instance.userInfo.porOrgacode,
      nodeId: sgtSentNodeId,
      sgtGntrnumber: sgtSentGntrnumber,
    );

    ServerResponse response = await repository.reverseTransaction(sgtSentNodeId, sgtSentGntrnumber);
    if (response.isError) {
      Toasty.error(response.errorMsg);
      return;
    }
    showCongratulationDialogOtp(context);
  }

  void clearController() {
    pinPutController.clear();
    referenceCodeController.clear();
  }

  void showCongratulationDialogOtp(BuildContext context) {
    Get.dialog(
      responsiveWidget(
        SizedBox(
          width: context.getWidth,
          child: Dialog(
            backgroundColor: Colors.transparent,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(10.0)),
              ),
              child: Padding(
                padding: const EdgeInsets.all(20),
                child: ListView(
                  physics: const NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  children: [
                    Container(
                      height: 60,
                      width: 60,
                      padding: const EdgeInsets.only(bottom: 5),
                      decoration: const BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(50)),
                      ),
                      child: SvgPicture.asset(
                        AppAssets.ic_congratulations,
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 10.0),
                      child: Text(
                        TranslationKeys.makeTranslation(TranslationKeys.textCongratulations),
                        style: Theme.of(context).textTheme.titleSmall,
                        textAlign: TextAlign.center,
                      ),
                    ),
                    const SizedBox(height: 20),
                    Text(
                      "Your transaction reverse successfully!",
                      style: Theme.of(context).textTheme.bodySmall,
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 20),
                    Padding(
                      padding: const EdgeInsets.only(left: 60.0, right: 60.0),
                      child: CustomButton(
                        onPressed: () {
                          onPressDone(context);
                        },
                        buttonText: TranslationKeys.makeTranslation(TranslationKeys.textContinue),
                        buttonPadding: const EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                        buttonColor: AppColors.colorButton,
                        sideBorder: const BorderSide(color: AppColors.colorBorderSkipBtn, width: 1.0),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
      barrierDismissible: false,
    );
  }

  void onPressDone(BuildContext context) {
    Navigator.of(context, rootNavigator: true).pop();
    clearController();
    getPendingTransition();
    transitionUpdate.value++;
  }
}
