<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { useSessionStore } from "../stores/session";

const error = ref("");
const login = ref({ email: "", password: "", name: "" });
const router = useRouter(); // has to be called in setup

onMounted(() => {
    useSessionStore().setTitle("Login");
});

function formSubmit(e: MouseEvent) {
    e.preventDefault();
    useSessionStore().register(login.value)
        .then(x => {
            error.value = "";
            router.replace("/dashboard");
            return x;
        })
        .catch(x => error.value = "The entered credentials are invalid!");

    // TODO display invalidCredentials
    // TODO redirect to dashboard on success
}
</script>

<template>
    <div>
        <input type="text" v-model="login.name"
            placeholder="Name"
            class="border-2 border-black rounded-lg block px-2 my-2 w-48" />
        <input type="text" v-model="login.email"
            placeholder="Email"
            class="border-2 border-black rounded-lg block px-2 my-2 w-48" />
        <input type="password" v-model="login.password"
            placeholder="Password"
            class="border-2 border-black rounded-lg block px-2 my-2 w-48" />
    </div>
    <div>{{ error }}</div>
    <button type="submit" @click="formSubmit" class="bg-blue-300 rounded-lg p-2 w-48">Register</button>
    <p>
        Existing user?
        <router-link to="/login">Login</router-link> instead!
    </p>
</template>