<template>
  <v-card>
    <v-toolbar color="primary" class="white--text" flat>
      <v-toolbar-title text-center>Forgot Password</v-toolbar-title>
    </v-toolbar>
    <v-card-text>
      <v-alert type="error" v-if="!!forgotPasswordError">{{forgotPasswordError}}</v-alert>
      <v-alert type="success" v-if="!!forgotPasswordMessage">{{forgotPasswordMessage}}</v-alert>
      <v-form ref="forgotPassword" v-on:submit.prevent="resetPassword">
        <v-text-field
          label="Your Registered Email"
          type="email"
          class="textfield-border"
          ref="email"
          v-model="email"
          :rules="emailRules"
          prepend-icon="mdi-email-outline"
        >
        </v-text-field>

        <div class="mt-5 text-center">
           <v-hover v-slot:default="{ hover }">
            <v-btn
              large
              block
              :outlined="hover ? false:true"
              :color="hover ? 'primary' : 'primary'"
              class="mt-6 body"
              tile
              @click="resetPassword"
              :disabled="inProgress"
            ><v-progress-circular :size="20" color="primary" indeterminate v-if="inProgress"></v-progress-circular>Reset Password</v-btn>
          </v-hover>
        </div>
      </v-form>
      <v-row>
        <v-col cols="12">
          Already have a account sign in here
          <v-hover v-slot:default="{ hover }">
          <router-link class="text-decoration-none" :to="{name:'LoginPage'}" :class="hover ? 'content-link-hover-color' : 'primary--text'">Sign In</router-link>
          </v-hover>
        </v-col>
      </v-row>
    </v-card-text>
  </v-card>
</template>
<script>
import { createHelpers } from "vuex-map-fields";
const { mapFields } = createHelpers({
  getterType: "registration/getField",
  mutationType: "registration/updateField"
});

export default {
  name: "ForgotPasswordComponent",
  data: () => ({
    valid: true,
    emailRules: [
      v => !!v || "E-mail is required",
      v => /.+@.+\..+/.test(v) || "E-mail must be valid"
    ]
  }),
  computed: {
  ...mapFields([
      "forgotOne",
      "forgotOne.email",
      "spinLogin",
      "forgotPasswordError",
      "forgotPasswordMessage",
      "inProgress"
    ])
  },
  methods: {
    resetPassword(e) {
      e.preventDefault();
      if (this.$refs.forgotPassword.validate()) {
        this.$store
          .dispatch("registration/forgotPassword")
          .then(data => {
            if (data) {
              this.$store.dispatch(
                "auth/prepare",
                "If there is an account associated with" +' '+ this.email +' '+ "you will receive an email with a link to reset your password."
              );
              this.$router.push({
                name: "SignInPage"
              });
            }
          });
      }
    }
  },
  created() {
    this.$store.dispatch("registration/newForgotPassword");
    this.$store.dispatch("registration/resetState");
  }
};
</script>
