<template>
  <v-container grid-list-md text-xs-center class="auth-form">
    <v-layout row wrap justify-center class="auth-form">
      <v-flex v-if="!emailSent" xs6>
        <v-form
          ref="form"
          lazy-validation>
          <div class="display-1 primary--text font-weight-thin mb-5">Reset Password</div>

          <v-text-field
            v-model="email"
            :rules="[rules.required]"
            :error-messages="errorMessages.email"
            label="Email"
            name="email"
            placeholder="isabl"
            autofocus
            required
            @keyup.esc="clear"
            @keyup.enter="sendResetEmail"/>
          <v-btn @click="goToLogin">go back</v-btn>

          <v-btn
            class="password-loading"
            color="primary"
            @click="sendResetEmail">
            <v-progress-circular
              v-if="loading"
              :width="3"
              :size="20"
              indeterminate
              color="primary"/>
            <span v-else>send email</span>
          </v-btn>

        </v-form>
      </v-flex>

      <v-flex v-else xs6>
        <div class="display-1 primary--text font-weight-thin mb-3">Password Reset Email Sent</div>
        <div class="title font-weight-thin">
          Check your inbox for a link to reset your password. If an email doesn't appear within a few
          minutes, check your spam folder.
        </div>
      </v-flex>

    </v-layout>
  </v-container>
</template>

<script>
import { resetPassword } from '@/utils/api'
import rules from '@/utils/rules'

export default {
  name: 'PasswordReset',
  data () {
    return {
      loading: false,
      email: '',
      emailSent: false,
      errorMessages: {},
      rules
    }
  },
  methods: {
    sendResetEmail () {
      this.loading = true
      if (this.$refs.form.validate()) {
        const { email } = this
        resetPassword({ email })
          .then(() => {
            this.emailSent = true
          })
          .catch((error) => {
            this.emailSent = false
            this.errorMessages = error
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        this.loading = false
      }
    },
    clear () {
      this.$refs.form.reset()
    },
    goToLogin () {
      this.$router.push({ name: 'login' })
    }
  }
}
</script>
