<template>
  <v-card :loading="loading" flat outlined class="light-shadow">
    <v-card-title class="display-1 font-weight-light mb-2">
      Alterar minha senha
    </v-card-title>
    <v-card-text>
      <v-text-field
        v-model="oldPassword"
        :type="showPassword ? 'text' : 'password'"
        outlined
        autofocus
        name="password"
        label="Senha atual"
        :append-icon="showPassword ? 'mdi-eye-outline' : 'mdi-eye-off-outline'"
        @click:append="showPassword = !showPassword"
      />
      <NewPasswordFields v-model="newPassword" />

      <v-alert color="error" :value="!!errors.length" icon="mdi-alert-circle">
        <p v-for="(error, index) in errors" :key="index">{{ error }}</p>
      </v-alert>
    </v-card-text>
    <v-card-actions>
      <v-spacer />
      <v-btn text large to="/">Cancelar</v-btn>
      <v-btn
        :disabled="!oldPassword || !newPassword"
        color="primary"
        large
        @click="onNewPassword"
        >Atualizar senha</v-btn
      >
    </v-card-actions>
  </v-card>
</template>

<script>
import gql from 'graphql-tag'
import NewPasswordFields from './NewPasswordFields'
import { onLogin } from '../plugins/vue-apollo'

export default {
  name: 'UpdatePasswordForm',
  components: { NewPasswordFields },
  data: () => ({
    oldPassword: '',
    showPassword: false,
    newPassword: '',
    errors: [],
    loading: false
  }),

  methods: {
    async onNewPassword() {
      this.loading = true
      this.errors = []

      try {
        const { data } = await this.$apollo.mutate({
          mutation: gql`
            mutation ($oldPassword: String!, $newPassword: String!) {
              updatePassword(
                data: { oldPassword: $oldPassword, newPassword: $newPassword }
              ) {
                token
                expiresIn
              }
            }
          `,
          variables: {
            oldPassword: this.oldPassword,
            newPassword: this.newPassword
          }
        })

        const token = data.updatePassword.token

        await onLogin(this.$apollo.getClient(), token)

        await this.$router.push({
          name: 'home',
          params: { message: 'Sua senha foi atualizada!' }
        })
      } catch (e) {
        this.errors = e.graphQLErrors.map(e => e.message)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped></style>
