<template>
  <q-page padding class="fit row justify-center items-center content-center">
    <q-card class="col-xs-11 col-sm-8 col-md-6 col-lg-4 justify-center items-center content-center">
      <q-toolbar class="bg-primary text-white">
        <q-toolbar-title> Passwort vergessen </q-toolbar-title>
      </q-toolbar>

      <q-card-section>
        <q-form ref="ResetForm" @submit="doReset" class="q-gutter-md">
          <q-input
            filled
            v-model="password"
            type="password"
            label="Passwort"
            :rules="rules"
            hint="Min. 8 Zeichen"
            tabindex="1"
          />
          <q-input
            filled
            v-model="password2"
            type="password"
            label="Passwort Wiederholung"
            :rules="rules"
            tabindex="2"
          />
          <div class="row justify-end">
            <q-btn label="Zurücksetzen" type="submit" color="primary" />
          </div>
        </q-form>
      </q-card-section>
    </q-card>
  </q-page>
</template>

<script lang="ts">
import { defineComponent, ref } from '@vue/composition-api';
import { Loading, Notify } from 'quasar';
import { AxiosResponse } from 'axios';

export default defineComponent({
  // name: 'PageName'
  setup(_, { root }) {
    const password = ref('');
    const password2 = ref('');

    const rules = [
      (val: string) =>
        (val && val.length >= 8) || 'Das Passwort muss mindestens 8 Zeichen lang sein!',
    ];

    function doReset() {
      if (password.value !== password2.value) {
        Notify.create({
          group: false,
          type: 'negative',
          message: 'Die Passwörter stimmen nicht überein!',
          timeout: 10000,
          progress: true,
          actions: [{ icon: 'mdi-close', color: 'white' }],
        });
        password2.value = '';
        return;
      }

      Loading.show({
        message: 'Das Passwort wird zurückgesetzt',
      });
      root.$store
        .dispatch('session/resetPassword', {
          password: password.value,
          token: root.$route.query.token,
        })
        .catch((error: AxiosResponse) => {
          if (error.status == 403) {
            Notify.create({
              group: false,
              type: 'negative',
              message: 'Der Link ist abgelaufen!',
              timeout: 10000,
              progress: true,
              actions: [{ icon: 'mdi-close', color: 'white' }],
            });
          }
        })
        .finally(() => {
          Loading.hide();
          void root.$router.replace({ name: 'login' });
        });
    }

    return { password, password2, doReset, rules };
  },
});
</script>
