<script setup>
  import { ref, computed } from 'vue'
  import { postSignUp, extractFormErrorFromField, extractGlobalFormError } from './api.js'
  import { useRouter } from 'vue-router'

  const router = useRouter();

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

  const errors = ref(null)

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

  function onSubmit() {
    postSignUp(user)
      .then((res) => {
        if (res.ok) {
          router.push('/');
          return;
        } else {
          res.json().then((json) => (errors.value = json));
        }
      })
  }
</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">{{$t('signup.username')}}</label>
      <div class="control">
        <input :class="'input ' + (userError ? 'is-danger' : '')" type="text" minlength="2" maxlength="20"
        required v-model="user.username" :placeholder="$t('signup.username')">
      </div>
      <p v-if="userError" class="help is-danger">{{userError}}</p>
    </div>
    <div class="field">
      <label class="label">{{ $t('signup.password') }}</label>
      <div class="control">
        <input :class="'input ' + (passwordError ? 'is-danger' : '')" type="password" minlength="6"
        maxlength="100" v-model="user.password" required :placeholder="$t('signup.password')">
      </div>
      <p v-if="passwordError" class="help is-danger">{{passwordError}}</p>
    </div>
    <div class="field">
      <div class="control">
        <button class="button is-link">{{ $t('signup.signup') }}</button>
      </div>
    </div>
  </form>
</template>

<style scoped></style>
