<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';

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

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

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

    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' });
    }
}
</script>

<template>
    <q-layout>
        <q-page-container>
            <q-page>
                <div id="login">
                    <q-card class="login q-pa-xl">
                        <q-img src="~/assets/logo.svg" alt="Logo" fit="contain" :ratio="16 / 9" class="q-mb-md" />
                        <q-form @submit="onSubmit" class="q-gutter-md">
                            <q-input
                                filled
                                color="orange"
                                v-model="username"
                                :label="t('login.username')"
                                lazy-rules
                                :rules="[(val) => (val && val.length > 0) || 'Please type something']"
                            />
                            <q-input
                                filled
                                color="orange"
                                type="password"
                                v-model="password"
                                :label="t('login.password')"
                                lazy-rules
                                :rules="[(val) => (val && val.length > 0) || 'Please type something']"
                            />
                            <q-toggle v-model="keepLogin" :label="t('login.keepLogin')" color="orange" />

                            <div>
                                <q-btn :label="t('login.submit')" type="submit" color="orange" />
                            </div>
                        </q-form>
                    </q-card>
                </div>
            </q-page>
        </q-page-container>
    </q-layout>
</template>

<style lang="scss" scoped>
#login {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: inherit;
}

.login {
    width: 400px;
}
</style>
