<script setup>
import { ref } from 'vue';
import { Notify, 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';

import VnLogo from 'components/ui/VnLogo.vue';

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

const username = ref('');
const password = ref('');
const keepLogin = ref(true);

async function onSubmit() {
    const params = {
        user: username.value,
        password: password.value,
    };
    try {
        const { data } = await axios.post('Accounts/login', params);

        if (!data) return;

        await session.login(data.token, keepLogin.value);

        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 (res) {
        if (res.response?.data?.error?.code === 'REQUIRES_2FA') {
            Notify.create({
                message: t('login.twoFactorRequired'),
                icon: 'phonelink_lock',
                type: 'warning',
            });
            params.keepLogin = keepLogin.value;
            loginCache.setUser(params);
            return router.push({
                name: 'TwoFactor',
                query: router.currentRoute.value?.query,
            });
        }
        Notify.create({
            message: t('login.loginError'),
            type: 'negative',
        });
    }
}
</script>

<template>
    <QForm @submit="onSubmit" class="q-gutter-y-md q-pa-lg formCard">
        <VnLogo alt="Logo" fit="contain" :ratio="16 / 9" class="q-mb-md" />
        <QInput
            v-model="username"
            :label="t('login.username')"
            lazy-rules
            :rules="[(val) => (val && val.length > 0) || t('login.fieldRequired')]"
        />
        <QInput
            type="password"
            v-model="password"
            :label="t('login.password')"
            lazy-rules
            :rules="[(val) => (val && val.length > 0) || t('login.fieldRequired')]"
        />
        <QToggle v-model="keepLogin" :label="t('login.keepLogin')" />

        <div>
            <QBtn
                :label="t('login.submit')"
                type="submit"
                color="primary"
                class="full-width"
                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>
