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

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

import VnLogo from 'components/ui/VnLogo.vue';
import VnInput from 'src/components/common/VnInput.vue';
import axios from 'axios';

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;
        const {
            data: { multimediaToken },
        } = await axios.get('VnUsers/ShareToken', {
            headers: { Authorization: data.token },
        });

        if (!multimediaToken) return;

        await session.login(data.token, multimediaToken.id, 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" />
        <VnInput
            v-model="username"
            :label="t('login.username')"
            lazy-rules
            :rules="[(val) => (val && val.length > 0) || t('login.fieldRequired')]"
            color="primary"
        />
        <VnInput
            type="password"
            v-model="password"
            :label="t('login.password')"
            lazy-rules
            :rules="[(val) => (val && val.length > 0) || t('login.fieldRequired')]"
            class="red"
        />
        <div>
            <QBtn
                :label="t('login.submit')"
                type="submit"
                color="primary"
                class="full-width"
                rounded
                unelevated
            />
        </div>
        <QToggle v-model="keepLogin" :label="t('login.keepLogin')" />
    </QForm>
</template>

<style lang="scss" scoped>
.formCard {
    max-width: 350px;
    min-width: 300px;
}

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