<template>
  <v-container fluid class="d-flex fill-height">
    <v-row align="center" justify="center">
      <v-col :cols="width">
        <v-card class="elevation-12">
          <v-toolbar dark color="primary">
            <v-toolbar-title>{{appName}} - Reset Password</v-toolbar-title>
          </v-toolbar>
          <v-card-text>
            <p class="subheading">Enter your new password below</p>
            <v-form @keyup.enter="submit" v-model="valid" ref="form" @submit.prevent="" lazy-validation>
              <v-text-field type="password" ref="password" :label="$t('password')" v-model="password1" :rules="password1Rules">
              </v-text-field>
              <v-text-field type="password" :label="$t('confirmPassword')" v-model="password2" :rules="password2Rules">
              </v-text-field>
            </v-form>
          </v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn @click="cancel">{{ t("cancel") }}</v-btn>
            <v-btn @click="reset">{{ t("clear") }}</v-btn>
            <v-btn @click="submit" :disabled="!valid">{{ t("save") }}</v-btn>
          </v-card-actions>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script setup lang="ts">
import { appName } from '@/env';
import type { IUserProfileUpdate } from '@/interfaces';
import { ref, computed } from 'vue';
import router from '@/router';
import { useMainStore } from '@/stores/main';
import { password1Rules, usePassword2Rules } from '@/utils';
import { useDisplay } from 'vuetify';
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const valid = ref(true);
const password1 = ref('');
const password2 = ref('');
const form = ref(null);

const mainStore = useMainStore();

const password2Rules = usePassword2Rules(password1);

const { name } = useDisplay();
const width = computed(() => {
        // name is reactive and
        // must use .value
        switch (name.value) {
          case 'xs': return 12
          case 'sm': return 8
          case 'md': return 4
        }

        return 4
      })

function reset() {
  password1.value = '';
  password2.value = '';
  (form as any).value.reset();
}

function cancel() {
  router.back();
}

function checkToken() {
  const token = (router.currentRoute.value.query.token as string);
  if (!token){
    mainStore.addNotification({
      content: 'No token provided in the URL, start a new password recovery',
      color: 'error',
    });
    router.push('/recover-password');
  } else {
    return token;
  }
}

async function submit(){
  await (form as any).value.validate()
  if (valid.value) {
    const token = checkToken();
    if (token) {
      await mainStore.resetPassword(token, password1.value);
      router.push('/');
    }
  }
}

</script>