import 'package:get/get.dart';
import 'package:uco_mobile_poc/app/core/constants/translation_keys.dart';
import 'package:uco_mobile_poc/app/core/utils/SessionCache.dart';
import 'package:uco_mobile_poc/app/core/utils/app_utils.dart';
import 'package:uco_mobile_poc/app/custom_widgets/Fields/input_field.dart';
import 'package:uco_mobile_poc/app/models/chanange_password_params.dart';

import '../../../core/config/server_response.dart';
import '../../../core/data/repositories/app_repositories.dart';
import '../../../custom_widgets/Fields/field_validations.dart';
import '../../../custom_widgets/custom_dialog.dart';
import '../../../custom_widgets/custom_toasty.dart';

class ChangePasswordController extends GetxController {
  final AppRepositories repository = Get.find<AppRepositories>();
  late InputField oldPasswordField;
  late InputField newPasswordField;
  late InputField confirmNewPasswordField;

  bool validate() {
    bool isValid = FieldValidation.validateAll([oldPasswordField, newPasswordField, confirmNewPasswordField]);
    return isValid;
  }

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

    bool otherValidation = true;
    if (!AppUtils.isPasswordValid(oldPasswordField.getCustomText(), 8)) {
      oldPasswordField.setError(TranslationKeys.makeTranslation(TranslationKeys.textPasswordPattern));
      otherValidation = false;
    }
    if (!AppUtils.isPasswordValid(newPasswordField.getCustomText(), 8)) {
      newPasswordField.setError(TranslationKeys.makeTranslation(TranslationKeys.textPasswordPattern));
      otherValidation = false;
    }
    if (!AppUtils.isPasswordValid(confirmNewPasswordField.getCustomText(), 8)) {
      confirmNewPasswordField.setError(TranslationKeys.makeTranslation(TranslationKeys.textPasswordPattern));
      otherValidation = false;
    }
    if (!otherValidation) {
      return;
    }

    if (newPasswordField.getCustomText() != confirmNewPasswordField.getCustomText()) {
      Toasty.error("Passwords didn't match");
      return;
    }

    ServerResponse response = await repository.changePassword(
      ChangePasswordParams(
        newPassword: newPasswordField.getCustomText(),
        oldPassword: oldPasswordField.getCustomText(),
        email: SessionCache.instance.userInfo.cmpUserId,
      ),
    );
    if (response.isError) {
      Toasty.error(response.errorMsg);
      return;
    }

    CustomDialog.showSuccessDialog(
       title: "Change Password",
        description: " Password has been changed successfully",
        onTapPositive: () {
          clearFields();
          Get.back();
        });
  }

  void clearFields() {
    oldPasswordField.clear();
    newPasswordField.clear();
    confirmNewPasswordField.clear();
  }
}
