<template>
  
    <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 
                class="bg-[#18A058]" 
                type="success" 
                @click="onClickLogin"
                :disabled="!form.password || !form.username"
            >Anmelden</n-button>
        </div>
    </n-form>
</template>

<script setup>
    import { ref, reactive, watch } from 'vue'
    import { useMessage } from 'naive-ui'
    import { router } from '@inertiajs/vue3'
    import LoginLayout from '@/layouts/LoginLayout.vue'

    defineOptions({ layout: LoginLayout })
    const message = useMessage()
    const props = defineProps(['errors'])
    const flashErrors = ref(props.errors)

    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",
        }
    })

    watch(props, async(newVal, oldVal) => {
        flashErrors.value = props.errors

        if(flashErrors.value?.login) {
            message.error(translateLoginError(flashErrors.value.login),{
                closable: true
            })
        }
    })

    function translateLoginError(errorMsg) {
        switch(errorMsg.split(":")[0]) {
            case 'E_INVALID_AUTH_PASSWORD':
                return "Falsches Passwort eingegeben."
            case 'E_INVALID_AUTH_UID':
                return "Benutzername nicht gefunden"
        }
    }

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