<script setup lang="ts">
import { AuthenticationAPIClient } from '@/api/auth'
import { useAuthStore } from '@/stores/auth'
import { ref, type Ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

interface Credentials {
  username: string
  password: string
}

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const credentials: Ref<Credentials> = ref({ username: '', password: '' })
const apiClient = new AuthenticationAPIClient(authStore)

async function doLogin() {
  const user = await apiClient.login(credentials.value.username, credentials.value.password).handleErrorsWithAlert()
  if (user) {
    authStore.logIn(credentials.value.username, credentials.value.password, user)
    if ('next' in route.query && typeof (route.query.next) === 'string') {
      await router.replace(route.query.next)
    } else {
      await router.replace('/')
    }
  }
}
</script>
<template>
  <main class="centered-content">
    <h1 class="align-center">Login to Teacher-Tools</h1>
    <form>
      <div class="login-input-row">
        <label for="username-input">Username</label>
        <input id="username-input" name="username" type="text" v-model="credentials.username" />
      </div>
      <div class="login-input-row">
        <label for="password-input">Password</label>
        <input id="password-input" name="password" type="password" v-model="credentials.password" />
      </div>
      <div class="button-bar align-center">
        <button type="button" @click="doLogin" style="font-size: large;">Login</button>
      </div>
      <div>
        <p>
          If you forgot your password or would like to create an account, please contact <a class="link link-ext"
            href="https://andrewlalis.com/contact">Andrew Lalis</a> for assistance.
        </p>
        <p>
          For security purposes, refreshing this site or closing your browser will log you out.
        </p>
      </div>
    </form>
  </main>
</template>
<style scoped>
.login-input-row {
  max-width: 30ch;
  margin-left: auto;
  margin-right: auto;
}

.login-input-row>input {
  width: 100%;
  font-size: medium;
  padding: 0.5em;
}

.login-input-row+.login-input-row {
  margin-top: 1em;
}
</style>
