<template>
    <div class="mx-auto w-full max-w-lg">
    <span
        class="flex items-center justify-center bg-white text-xl font-bold uppercase text-primary-500 p-4"
    >
        <img src="/malio.png" alt="Logo" class="w-[150px]"/>
    </span>
        <form
            class="mt-8 space-y-6 rounded-lg border border-neutral-200 bg-white p-6 shadow-sm"
            @submit.prevent="handleSubmit"
        >
            <MalioInputText :reserve-message-space="false"
                v-model="username"
                label="Nom d'utilisateur"
                autocomplete="username"
                group-class="mt-2"
            />

            <MalioInputPassword :reserve-message-space="false"
                v-model="password"
                label="Mot de passe"
                autocomplete="current-password"
            />

            <button
                type="submit"
                class="w-full rounded-md bg-primary-500 px-4 py-2 text-base font-semibold text-white transition hover:bg-secondary-500 disabled:cursor-not-allowed disabled:opacity-60"
                :disabled="isSubmitting"
            >
                Se connecter
            </button>
            <p class="font-bold">v{{ version }}</p>
        </form>
    </div>
</template>

<script setup lang="ts">
definePageMeta({layout: 'auth'})
useHead({
    title: 'Connexion'
})

const router = useRouter()
const auth = useAuthStore()
const { version } = useAppVersion()

const username = ref('')
const password = ref('')
const isSubmitting = ref(false)

const handleSubmit = async () => {
    if (isSubmitting.value) return

    isSubmitting.value = true
    try {
        await auth.login(username.value, password.value)

        const isAdmin = auth.user?.roles?.includes('ROLE_ADMIN')
        const isDriver = auth.user?.isDriver
        await router.push(isAdmin ? '/calendar' : isDriver ? '/driver-hours' : '/hours')
    } finally {
        isSubmitting.value = false
    }
}
</script>
