<template>
  <ElForm
    ref="forgotPasswordForm"
    :model="forgotPasswordForm"
    :rules="rules"
    label-position="top"
    class="auth-form forgot-password"
    @submit.native.prevent="submitForgotPassword"
  >
    <AuthPageHeader title="Forgot Password" />
    <p>Enter your email address below to be sent a temporary password.</p>
    <div class="inputs-container">
      <ElFormItem
        :class="{'not-invited-error' : notInvited }"
        for="email-input"
        prop="email"
        class="email-container"
        label="Company email"
        size="medium"
      >
        <ElInput
          v-model="forgotPasswordForm.email"
          name="email-input"
          placeholder="Enter email"
          data-test="enter email"
        />
      </ElFormItem>
      <div class="btn-group">
        <slot name="ctaSubmit">
          <AppButton
            :is-disabled="!forgotPasswordForm.email || btnDisable"
            name="submit-button"
            type="primary"
            native-type="submit"
            text="Email temporary password"
            no-branding
            data-test="submit form"
          />
        </slot>
      </div>
      <ul class="links-container">
        <RouterLink
          tag="li"
          :to="linkLogin"
        >
          <AppButton
            type="primary"
            size="text"
            text="Sign in"
            no-branding
          />
        </RouterLink>
      </ul>
    </div>
    <AuthPageFooter />
  </ElForm>
</template>

<script>
  export default {
    name: 'AppForgotPasswordForm',
    props: {
      accountService: {
        type: Object,
        default: () => ({}),
      },
      checkInvited: {
        type: Boolean,
        default: false,
      },
      documentId: {
        type: String,
        default: null,
      },
      linkLogin: {
        type: [String, Object],
        required: true,
      },
      projectId: {
        type: [String, Number],
        default: null,
      },
      userInfo: {
        type: Object,
        required: true,
      },
    },
    data: (vm) => ({
      btnDisable: false,
      forgotPasswordForm: {
        email: '',
      },
      notInvited: false,
      rules: {
        email: [
          {
            required: true,
            type: 'email',
            message: 'Please enter your company email.',
            trigger: 'blur',
          },
          {
            validator: vm.validateEmail,
            trigger: 'none',
          },
          {
            validator: vm.clearError,
            trigger: 'change',
          },
        ],
      },
    }),
    watch: {
      /**
       * Watching the email field - and updating the vuex store with the new email
       *
       * @param {string} email
       */
      'forgotPasswordForm.email': function (email) {
        this.$emit('setUserEmail', email);
        this.$emit('update:email', email);
        this.notInvited = false;
      },
    },
    created() {
      // We want the email address to persist across all login/forgotPW/registration forms
      this.forgotPasswordForm.email = this.userInfo.email;
    },
    methods: {
      /* eslint-disable-next-line jsdoc/require-param */
      /**
       * Clear out any displayed errors
       */
      clearError(rule, value, callback) {
        callback();
      },

      /* eslint-disable-next-line jsdoc/require-param */
      /**
       * Method to validate the email address and see if this user was invited to the project
       */
      validateEmail(rule, value, callback) {
        if (!this.forgotPasswordForm.email || !this.checkInvited) {
          callback();

          return;
        }

        this.accountService
          .checkInvitedToProject(this.forgotPasswordForm.email, this.projectId)
          .then(() => {
            callback();
          })
          .catch((error) => {
            this.notInvited = true;
            this.btnDisable = false;
            const errorMessage = error.response && error.response.status === 404
              ? 'Sorry, this email doesn\'t exist in our system. Ensure you\'re using the company email you registered with, or contact support@threeflow.com.'
              : 'This email is not invited. Ensure you’re using your company email and that it has been invited, or contact support@threeflow.com.';
            callback(new Error(errorMessage));
          });
      },

      /**
       * On form submission we should validate and call the service to update the password (if valid).
       */
      submitForgotPassword() {
        this.btnDisable = true;

        this.$refs.forgotPasswordForm.validate((valid) => {
          if (!this.accountService.passwordReset) {
            return valid;
          }

          if (valid) {
            const data = {
              email: this.forgotPasswordForm.email,
              projectId: this.projectId,
            };

            // Attach documentId if present
            if (this.documentId) {
              data.documentId = this.documentId;
            }

            this.accountService.passwordReset(data).then(() => {
              /* We should set a flag to show the success message on
             the login screen and then redirect to the login form */
              this.$emit('setTempPasswordStatus', true);
              const redirectURL = this.$route.query.redirect || this.linkLogin;
              this.btnDisable = false;
              this.$router.push(redirectURL);
            });
          }

          this.btnDisable = false;

          return valid;
        });
      },
    },
  };
</script>

<style lang="scss" scoped>
  .btn-group {
    justify-content: center;
  }
</style>
