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

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

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

function formSubmit(e: MouseEvent) {
    e.preventDefault();
    useSessionStore().login(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
      v-model="login.user"
      type="text"
      placeholder="Username"
      class="border-2 border-black rounded-lg block px-2 my-2 w-48"
    />
    <Input
      v-model="login.password"
      type="password"
      placeholder="Password"
      class="border-2 border-black rounded-lg block px-2 my-2 w-48"
    />
  </div>
  <div>{{ error }}</div>
  <button
    type="submit"
    class="bg-blue-300 rounded-lg p-2 w-48"
    @click="formSubmit"
  >
    Login
  </button>
  <p>
    New user?
    <router-link to="/register">
      Register
    </router-link> instead!
  </p>
</template>
