<template>
    <n-message-provider>
        <FlashMessages 
            :messages="props.flashMessages"
        />
    </n-message-provider>
    <n-form  
        label-placement="top"
        :model="form"
        @submit.prevent="onClickLogin"
        :rules="rules"
        ref="formRef"
    >
        <n-form-item 
            label="Benutzername" 
            path="username"
        >
            <n-input 
                v-model:value="form.username" 
                placeholder="Benutzername" 
                @keydown.enter="onClickLogin"
            />
        </n-form-item>

        <n-form-item 
            label="Passwort" 
            path="password"
        >
            <n-input 
                v-model:value="form.password" 
                placeholder="Passwort"
                @keydown.enter="onClickLogin"
                type="password"
                show-password-on="click"
            />
        </n-form-item>

        <div class="flex justify-center">
            <n-button 
                type="success" 
                @click="onClickLogin"
                :disabled="!form.password || !form.username"
            >Anmelden</n-button>
        </div>
    </n-form>
</template>

<script setup>
    import { ref } from 'vue'
    import { router } from '@inertiajs/vue3'
    import LoginLayout from '@/layouts/LoginLayout.vue'
    import FlashMessages from '@/components/FlashMessages.vue'

    defineOptions({ layout: LoginLayout })
    const props = defineProps(['flashMessages'])

    const form = ref({
        username: '',
        password: '',
    })

    const formRef = ref(null)

    const rules = ref({
        username: {
            required: true,
            message: "Benutzername erforderlich",
            trigger: "input",
        },
        password: {
            required: true,
            message: "Passwort erforderlich",
            trigger: "input",
        }
    })

    function onClickLogin(){
        formRef.value?.validate((errors) => {
            if(!errors) router.post('login', form.value)
        })
    }
</script>