import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:string_validator/string_validator.dart';
import 'package:uco_mobile_poc/app/core/config/server_response.dart';
import 'package:uco_mobile_poc/app/core/constants/app_contants.dart';
import 'package:uco_mobile_poc/app/core/constants/translation_keys.dart';
import 'package:uco_mobile_poc/app/core/data/repositories/app_repositories.dart';
import 'package:uco_mobile_poc/app/core/enums/request_constants.dart';
import 'package:uco_mobile_poc/app/core/utils/app_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_toasty.dart';
import 'package:uco_mobile_poc/app/models/RegisterRequest.dart';
import 'package:uco_mobile_poc/app/routes/app_pages.dart';

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

class SignUpScreenStep1Controller extends GetxController {
  final AppRepositories repository = Get.find<AppRepositories>();
  BuildContext context = Get.context as BuildContext;

  late InputField firstNameField;

  late InputField lastNameField;
  late InputField passwordField;
  late InputField confirmPasswordField;
  late InputField emailField;
  late InputField phoneNumberField;

  /// map for country wise phone number length
  final RxString selectedCountryCode = 'US'.obs;
  final Map<String, int> countryPhoneMap = {
    'US': 10,
    'PK': 11,
    'It': 11,
  };


  bool validatePhoneNumber(String countryCode, String phoneNumber) {
    if (countryPhoneMap.containsKey(countryCode)) {
      return phoneNumber.length == countryPhoneMap[countryCode];
    }
    return false;
  }

  bool validate() {
    bool isValid = FieldValidation.validateAll([firstNameField, passwordField, confirmPasswordField, emailField, phoneNumberField]);
    return isValid;
  }

  void validateAndSendRequest() async {
    hideKeyBoard();
    if (!validate()) {
      Toasty.error("Please input and then proceed");
      return;
    }
    bool otherValidation = true;
    if (!AppUtils.isPasswordValid(passwordField.getCustomText(), 8)) {
      passwordField.setError(TranslationKeys.makeTranslation(TranslationKeys.textPasswordPattern));
      otherValidation = false;
    }
    if (!AppUtils.isPasswordValid(confirmPasswordField.getCustomText(), 8)) {
      confirmPasswordField.setError(TranslationKeys.makeTranslation(TranslationKeys.textPasswordPattern));
      otherValidation = false;
    }
    if (!isEmail(emailField.getCustomText())) {
      emailField.setError("Invalid email");
      otherValidation = false;
    }
    if (!otherValidation) {
      return;
    }
    if (passwordField.getCustomText() != confirmPasswordField.getCustomText()) {
      Toasty.error("Passwords didn't matched");
      return;
    }

    if (!validatePhoneNumber(selectedCountryCode.value, phoneNumberField.getCustomText())) {
      Toasty.error("Invalid phone number length");
      return;
    }

    RegisterRequest request = RegisterRequest(
      email: emailField.getCustomText(),
      password: passwordField.getCustomText(),
      username: firstNameField.getCustomText(),
      phone: phoneNumberField.getCustomText(isPrefixRequired: true, isCountryCodeRequired: true),
      name: "",
      channelCode: RequestConstants.channelCode,
      userRole: AppConstants.ROLE_USER,
      porOrgacode: RequestConstants.porOrgacode,
      isOtpRequired: false,
    );
    ServerResponse response = await repository.signupStep1(request);

    if (response.errorCode == "ERR_USER_0007") {
      Get.toNamed(Routes.SIGN_UP_SCREEN_OTP, arguments: {
        AppConstants.SIGN_UP_FIRST_STEP_DATA: request,
      });
      return;
    }
    if (response.isError) {
      Toasty.error(response.errorMsg);
      return;
    }
    Get.toNamed(Routes.SIGN_UP_SCREEN_OTP,
        arguments: {
      AppConstants.SIGN_UP_FIRST_STEP_DATA: request,
    }
    );
  }
  clearTextControllerStep1() {
    firstNameField.clear();
    passwordField.clear();
    confirmPasswordField.clear();
    emailField.clear();
    phoneNumberField.clear();
  }
  @override
  void onClose() {
    FormFieldConstants.instance().clearKeysForScreen("SignUpScreenStep1View");
    super.onClose();
  }
}
