import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pin_code_fields/pin_code_fields.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/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_button.dart';
import '../../../custom_widgets/custom_dropdown.dart';
import '../../../custom_widgets/custom_toasty.dart';
import '../../../models/GLACCAddMoneyRequestModel.dart';
import '../../../models/GlsResponseModel.dart';
import '../../../models/SendTransactionStep1ResponseModel.dart';
import '../../../models/TransactionPinRequestModel.dart';
import '../../../models/evaluated_cuency_model.dart';
import '../../../res/app_colors.dart';
import '../../../routes/app_pages.dart';

class GeneralLedgerController extends GetxController {
  final AppRepositories repository = Get.find<AppRepositories>();
  late InputField messageField;
  late InputField glsAccounts;
  late InputField userTransactionPinField;
  TextEditingController pinPutController = TextEditingController();

  RxList<DropDown> allGlsAccounts = RxList.empty();
  Rx<DropDown?> selectedGlAccount = Rx<DropDown?>(null);
  GLACCAddMoneyRequestModel transactionSubmitRequestModel = GLACCAddMoneyRequestModel.empty();
  Rx<EvaluatedCurrencyModel> evaluatedCurrencyModel = EvaluatedCurrencyModel.empty().obs;

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

    var arguments = Get.arguments;

    transactionSubmitRequestModel = (arguments != null ? arguments[AppConstants.SEND_TRANS_STEP1_DATA] ?? GLACCAddMoneyRequestModel.empty() : GLACCAddMoneyRequestModel.empty());

    evaluatedCurrencyModel.value = (arguments != null ? arguments[AppConstants.EXCHANGE_RATE] ?? EvaluatedCurrencyModel.empty() : EvaluatedCurrencyModel.empty());
    fetchAllGlsAccounts();
  }

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

  void updateSelectedDeposit(DropDown item) {
    selectedGlAccount.value = item;
  }

  clearAll() {
    messageField.clear();
    glsAccounts.clear();
    userTransactionPinField.clear();
    pinPutController.clear();
    selectedGlAccount = Rx<DropDown?>(null);
  }

  Future<void> fetchAllGlsAccounts() async {
    ServerResponse response = await repository.fetchGlsAccounts();
    if (response.isError) {
      Toasty.error(response.errorMsg);
      return;
    }
    List<GlsResponseModel> list = List<GlsResponseModel>.from(((response.response ?? []) as List<dynamic>).map((x) => GlsResponseModel.fromMap(x)) ?? []);
    SessionCache.instance.glsAccountsList.value = list;
    allGlsAccounts.clear();
    for (int i = 0; i < list.length; i++) {
      GlsResponseModel glsResponseModel = list.elementAt(i);
      allGlsAccounts.add(
        DropDown(i.toString(), "${glsResponseModel.pcaGlaccode} - ${glsResponseModel.pcaGlacdesc}", glsResponseModel),
      );
    }
    allGlsAccounts.refresh();
  }

  /// Pin Dialog...........Transactions
  void transactionPinDialog(BuildContext context, GeneralLedgerController 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,
                              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),
                        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,
    );
  }

  bool validate() {
    bool isValid = FieldValidation.validateAll([glsAccounts, userTransactionPinField]);
    return isValid;
  }

  Future<void> handleNextClick() async {
    if (!validate()) {
      Toasty.error("Please input and then proceed");
      return;
    }

    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.sendAddMoneyOtp(transactionPinRequestModel);
    if (response.isError) {
      Toasty.error(response.errorMsg);
      return;
    }
    SendTransactionStep1ResponseModel step1responseModel = SendTransactionStep1ResponseModel.fromMap(response.response);
    transactionSubmitRequestModel.notificationId = step1responseModel.notificationId.toString();

    GlsResponseModel responseModel = selectedGlAccount.value!.data as GlsResponseModel;
    transactionSubmitRequestModel.drPcaGlaccode = responseModel.pcaGlaccode;
    transactionSubmitRequestModel.drPcaGlacdesc = responseModel.pcaGlacdesc;

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