
<script setup lang="ts">
import Input from "@/components/Input.vue";
import {onMounted, ref, watch} from "vue";
import {API} from "@/services/api";
import {Auth} from "@/services/auth";

const props = defineProps<{
    active: boolean
}>()

const emit = defineEmits(["success"])

onMounted(() => {
    window.addEventListener("keydown", ev => {
        if(props.active && ev.key == "Enter") {
            attemptLogin()
        }
    })
})

const username = ref("")
const password = ref("")
const invalid = ref(false)

watch(props, (value, oldValue, onCleanup) => {
    if(!value.active) {
        username.value = ""
        password.value = ""
        invalid.value = false
    }
})

async function attemptLogin() {
    let login = await Auth.login(username.value, password.value)
    if(login.success){
        console.log("success", login)
        emit("success", login)
    }else{
        invalid.value = true
    }
}
</script>

<template>

    <div class="container">
        <span class="title">Anmelden</span>
        <Input class="input" v-model:value="username" label="Nutzername"/>
        <Input class="input" v-model:value="password" label="Passwort" type="password"/>
        <span v-if="invalid" style="color: red; text-align: center; margin-bottom: 10px">Benutzername oder<br> Passwort falsch.</span>
        <button @click="attemptLogin"><i>login</i>Anmelden</button>
    </div>

</template>

<style scoped lang="less">

.container{
    background: #ffffff;
    padding: 20px 32px;
    border-radius: 8px;
    box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
    display: flex;
    align-items: center;
    flex-direction: column;
    pointer-events: auto;

    .title{
        display: inline-block;
        font-size: 24px;
        margin-bottom: 24px;
    }

    .input {
        margin-bottom: 16px;
    }
    button{
        margin-top: 8px;
    }
}

</style>
