<script setup>
  import { ref, reactive, computed } from 'vue'
  import { postBook, postSignup } from './api.js'
  import { useRouter, useRoute } from 'vue-router'

  const router = useRouter();

  const user = ref({
    username: "",
    password: ""
  });
  const errors = ref(null)
  const userError = computed(() => {
    return extractErrorFromField("Username");
  })
  const passwordError = computed(() => {
    return extractErrorFromField("Password");
  })

  function extractErrorFromField(fieldName) {
    if (errors.value === null) {
     return "";
    }
    const titleErr = errors.value.find((e) => e["field"] === fieldName);
    if (typeof titleErr !== 'undefined') {
      return titleErr.error
    } else {
      return "";
    }
  }

  function onSubmit(e) {
    postSignup(user)
      .then((res) => {
        if (res.ok) {
          router.push('/');
          return;
        } else {
          res.json().then((json) => (errors.value = json));
        }
      })
  }
</script>

<template>
  <form @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">Submit</button>
      </div>
    </div>
  </form>
</template>

<style scoped></style>
