<script setup>
import { ref, onMounted } from 'vue';
import { useQuasar } from 'quasar';
import { useI18n } from 'vue-i18n';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';

import VnInput from 'components/common/VnInput.vue';
import VnOutForm from 'components/ui/VnOutForm.vue';

const quasar = useQuasar();
const router = useRouter();
const route = useRoute();
const { t } = useI18n();

const newPassword = ref();
const repeatPassword = ref();
const passRequirements = ref({});

onMounted(async () => {
    passRequirements.value = (await axios('UserPasswords/findOne')).data;
});

async function onSubmit() {
    if (newPassword.value != repeatPassword.value)
        return quasar.notify({
            message: t('resetPassword.passwordNotMatch'),
            type: 'negative',
        });

    const headers = {
        Authorization: route.query.access_token,
    };

    try {
        await axios.post(
            'VnUsers/reset-password',
            { newPassword: newPassword.value },
            { headers }
        );
        router.push('Login');
        quasar.notify({
            message: t('resetPassword.passwordChanged'),
            type: 'positive',
        });
    } catch (e) {
        quasar.notify({
            message: e.response?.data?.error.message,
            type: 'negative',
        });
    }
}
</script>
<template>
    <VnOutForm @submit="onSubmit" :title="t('globals.pageTitles.resetPassword')">
        <template #default>
            <VnInput
                type="password"
                :label="t('login.password')"
                v-model="newPassword"
                :info="
                    t('passwordRequirements', {
                        length: passRequirements.length,
                        nAlpha: passRequirements.nAlpha,
                        nUpper: passRequirements.nUpper,
                        nDigits: passRequirements.nDigits,
                        nPunct: passRequirements.nPunct,
                    })
                "
                required
            >
                <template #prepend>
                    <QIcon name="password" />
                </template>
            </VnInput>
            <VnInput
                type="password"
                :label="t('resetPassword.repeatPassword')"
                v-model="repeatPassword"
                required
            >
                <template #prepend>
                    <QIcon name="password" />
                </template>
            </VnInput>
        </template>
        <template #buttons>
            <QBtn
                :label="t('globals.pageTitles.resetPassword')"
                type="submit"
                color="primary"
                class="full-width q-mt-md"
                rounded
                unelevated
            />
        </template>
    </VnOutForm>
</template>
