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

import { useSession } from 'src/composables/useSession';
import { useLogin } from 'src/composables/useLogin';

const quasar = useQuasar();
const session = useSession();
const router = useRouter();
const loginCache = useLogin();
const { t } = useI18n();

const code = ref('');
const params = loginCache.getUser().value;
if (!params.user) {
    router.push({ name: 'Login' });
}

async function onSubmit() {
    try {
        params.code = code.value;
        const { data } = await axios.post('VnUsers/validate-auth', params);

        if (!data) return;

        await session.login(data.token, params.keepLogin);
        quasar.notify({
            message: t('login.loginSuccess'),
            type: 'positive',
        });

        const currentRoute = router.currentRoute.value;
        if (currentRoute.query && currentRoute.query.redirect) {
            router.push(currentRoute.query.redirect);
        } else {
            router.push({ name: 'Dashboard' });
        }
    } catch (e) {
        quasar.notify({
            message: e.response?.data?.error.message,
            type: 'negative',
        });
    }
}
</script>
<template>
    <QForm @submit="onSubmit" class="q-gutter-y-md q-pa-lg formCard">
        <div class="column items-center">
            <QIcon name="phonelink_lock" size="xl" color="primary" />
            <h5 class="text-center q-my-md">{{ t('twoFactor.insert') }}</h5>
        </div>
        <VnInput
            v-model="code"
            :hint="t('twoFactor.explanation')"
            mask="# # # # # #"
            fill-mask
            unmasked-value
            autofocus
        >
            <template #prepend>
                <QIcon name="lock" />
            </template>
        </VnInput>
        <div class="q-mt-xl">
            <QBtn
                :label="t('twoFactor.validate')"
                type="submit"
                color="primary"
                class="full-width q-mt-md"
                rounded
                unelevated
            />
        </div>
    </QForm>
</template>
<style lang="scss" scoped>
.formCard {
    max-width: 350px;
    min-width: 300px;
}

@media (max-width: $breakpoint-xs-max) {
    .formCard {
        min-width: 100%;
    }
}
</style>
