import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:uco_mobile_poc/app/core/constants/app_contants.dart';
import 'package:uco_mobile_poc/app/core/data/repositories/app_repositories.dart';
import 'package:uco_mobile_poc/app/core/dialogs/custom_loading.dart';
import 'package:uco_mobile_poc/app/core/utils/logs_utils.dart';
import 'package:uco_mobile_poc/app/custom_widgets/Fields/field_validations.dart';
import 'package:uco_mobile_poc/app/custom_widgets/Fields/input_field.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/RegisterRequest.dart';
import 'package:uco_mobile_poc/app/models/SignupStep3RequestModel.dart';
import 'package:uco_mobile_poc/app/models/product_model.dart';
import 'package:uco_mobile_poc/app/routes/app_pages.dart';

import '../../../core/constants/form_field_constants.dart';
import '../../../core/constants/translation_keys.dart';
import '../../../core/utils/fields_utils.dart';

class SignUpScreenStep2Controller extends GetxController {
  final String IDEN_NUMBER = "01";
  final String IDEN_TAX_PAYER_ID = "02";
  final String IDEN_PASSPORT = "03";

  String dpmcode = '';

  final AppRepositories repository = Get.find<AppRepositories>();
  BuildContext context = Get.context as BuildContext;

  late InputField firstNameField;
  late InputField lastNameField;
  late InputField nameAddressField;
  late InputField selectIdentityTypeField;
  late InputField identityNumberField;
  late InputField taxPayerIdField;
  late InputField passportField;
  String? selectedCountryCode;


  RxList<DropDown> identityDropdownList = <DropDown>[].obs;
  DropDown? currentIdentityValue;

  RegisterRequest firstStepData = RegisterRequest.empty();

  late InputField countryFeild;

  late InputField provinceFeild;

  late InputField cityFeild;

  late InputField currencyCodesFelid;

  var countryList = [
    {"name": "Pakistan", "code": "PK"},
    {"name": "United States of America", "code": "USA"}
  ].map((e) => DropDown(e["code"]!, e["code"]!)).toList();

  List<DropDown> provinceList = [
    {
      "country": "PK",
      "province": ["Sindh", "Punjab", "Gilgit Baltistan", "KPK", "Baluchistan"]
    },
    {
      "country": "USA",
      "province": ["California", "Florida", "Hawaii"]
    },
  ]
      .expand(
        (Map e) => (e["province"] as List)
        .map((e1) => DropDown(e["country"]!, e1)),
  )
      .toList();


  List<ProductDepositModel> currencyList = [];
  List<DropDown> currencyListDropDown = [];

  List<DropDown> getProvinceList(String country) {
    return provinceList
        .where((element) => element.id == country)
        .toList();
  }

  // getProvinceList(String country) {
  //   return provinceList
  //       .where((DropDown? element) => element!.id == country)
  //       .toList();
  // }

  List<DropDown> cityList = [
    {
      "province": "Sindh",
      "city": ["Karachi", "Ladkana"]
    },
    {
      "province": "Punjab",
      "city": ["Lahore"]
    },
    {
      "province": "Gilgit Baltistan",
      "city": ["Gilgit"]
    },
    {
      "province": "California",
      "city": ["California"]
    },
    {
      "province": "Florida",
      "city": ["Florida"]
    },
    {
      "province": "Hawaii",
      "city": ["Hawaii"]
    },
  ]
      .expand(
        (Map e) => (e["city"] as List)
        .map((e1) => DropDown(e["province"]!, e1)),
  )
      .toList();

  @override
  void onInit() {
    super.onInit();
    identityDropdownList.value = <DropDown>[
      DropDown(IDEN_NUMBER, TranslationKeys.makeTranslation(TranslationKeys.textIdentityNumber)),
      DropDown(IDEN_TAX_PAYER_ID, TranslationKeys.makeTranslation(TranslationKeys.textSSNTaxPayerID)),
      DropDown(IDEN_PASSPORT, TranslationKeys.makeTranslation(TranslationKeys.textPassportAlienID)),
    ];
  }

  @override
  Future<void> onReady() async {
    super.onReady();
    getCurrencyList();
    var arguments = Get.arguments;
    firstStepData = (arguments != null ? arguments[AppConstants.SIGN_UP_FIRST_STEP_DATA] ?? RegisterRequest.empty() : RegisterRequest.empty());
  }

  updateIdentityValue(DropDown? identityDropDowModel) {
    currentIdentityValue = identityDropDowModel;
    update();
  }

  bool validate() {
    bool isValid = FieldValidation.validateAll([firstNameField, lastNameField, nameAddressField, selectIdentityTypeField,
      currencyCodesFelid,
    ]);

    if (currentIdentityValue != null) {
      if (currentIdentityValue!.id == IDEN_NUMBER) {
        isValid = isValid && FieldValidation.validateAll([identityNumberField]);
      } else if (currentIdentityValue!.id == IDEN_TAX_PAYER_ID) {
        isValid = isValid && FieldValidation.validateAll([taxPayerIdField]);
      } else if (currentIdentityValue!.id == IDEN_PASSPORT) {
        isValid = isValid && FieldValidation.validateAll([passportField]);
      }
    }

    return isValid;
  }

  String getIdentification() {
    if (currentIdentityValue!.id == IDEN_NUMBER) {
      return identityNumberField.getCustomText();
    } else if (currentIdentityValue!.id == IDEN_TAX_PAYER_ID) {
      return taxPayerIdField.getCustomText();
    } else if (currentIdentityValue!.id == IDEN_PASSPORT) {
      return passportField.getCustomText();
    }
    return "";
  }

  void validateAndSendRequest() async {
    hideKeyBoard();
    if (!validate()) {
      Toasty.error("Please input and then proceed");
      return;
    }

    SignupStep3RequestModel signupStep3RequestModel =
    SignupStep3RequestModel(username: firstStepData.username,
        email: firstStepData.email, phone: firstStepData.phone,
        channelCode: firstStepData.channelCode, porOrgacode: firstStepData.porOrgacode,
        address: nameAddressField.getCustomText(),
        name: '${firstNameField.getCustomText()} ${lastNameField.getCustomText()}',
        identificationType: currentIdentityValue!.id, identificationNumber: getIdentification(),
        userRole: AppConstants.ROLE_USER, isKycAdded: false, kycType: "",
        kycDocumentId1: "", kycDocumentId2: "", dmpProdcode: dpmcode);
    Get.toNamed(Routes.SIGN_UP_SCREEN_STEP3,
        arguments: {
      AppConstants.SIGN_UP_SECOND_STEP_DATA: signupStep3RequestModel,
    }
    );
  }
  clearTextControllerStep2() {
    firstNameField.clear();
    lastNameField.clear();
    nameAddressField.clear();
    selectIdentityTypeField.clear();
    identityNumberField.clear();
    taxPayerIdField.clear();
    passportField.clear();
    update();
  }

  void updateCurrency(DropDown? item) {
    dpmcode = item!.id;
    update();
  }

  getCurrencyList() async {
    try {
      var productResponce = await repository.getCurrencyList();

      if (productResponce.isError) {
        hideLoader();

        Toasty.error(productResponce.errorMsg);
        return;
      }

      currencyList = ProductDepositModel.productListFromJson(productResponce.response);

      currencyListDropDown = currencyList.map((e) => DropDown(e.dmpProdcode, e.dmpProddesc, e)).toList();

      hideLoader();

      update();
    } catch (e, s) {
      dp("Error in get product $e", s);
      hideLoader();
      Toasty.error("Something went worng please try again");
    }
  }
  @override
  void onClose() {
    FormFieldConstants.instance().clearKeysForScreen("SignUpScreenStep2View");
    super.onClose();
  }
}
