<script setup>
  import { ref, computed } from 'vue'
  import { postLogin, extractFromErrorFromField, extractGlobalFormError } from './api.js'
  import { useRouter } from 'vue-router'
  import { useAuthStore } from './auth.store.js'

  const router = useRouter();

  const user = ref({
    username: "",
    password: ""
  });

  const errors = ref(null)

  const formError = computed(() => {
    return extractGlobalFormError(errors.value);
  })
  const userError = computed(() => {
    return extractFromErrorFromField("Username", errors.value);
  })
  const passwordError = computed(() => {
    return extractFromErrorFromField("Password", errors.value);
  })

  function onSubmit(e) {
    postLogin(user)
      .then((res) => {
        if (res.ok) {
          res.json().then((json) => login(user.value.username, json));
          router.push('/');
          return;
        } else {
          res.json().then((json) => (errors.value = json));
        }
      })
  }

  function login(username, json) {
    useAuthStore().login({username: username, token: json["token"]})
  }
</script>


<template>
  <div v-if="formError" class="notification is-danger">
    <p>{{formError}}</p>
  </div>
  <form class="box" @submit.prevent="onSubmit">
    <div class="field">
      <label class="label">Username</label>
      <div class="control">
        <input :class="'input ' + (userError ? 'is-danger' : '')" type="text" minlength="2" maxlength="20"
        required v-model="user.username" placeholder="Username">
      </div>
      <p v-if="userError" class="help is-danger">{{userError}}</p>
    </div>
    <div class="field">
      <label class="label">Password</label>
      <div class="control">
        <input :class="'input ' + (passwordError ? 'is-danger' : '')" type="password" minlength="6"
        maxlength="100" v-model="user.password" required placeholder="Password">
      </div>
      <p v-if="passwordError" class="help is-danger">{{passwordError}}</p>
    </div>
    <div class="field">
      <div class="control">
        <button class="button is-link">Log In</button>
      </div>
    </div>
  </form>
</template>

<style scoped></style>
