<template>
  <PrimeCard>
    <template #content>
      <form @submit.prevent="submit">
        <div class="flex flex-col gap-3">
          <PrimeFloatLabel variant="on">
            <PrimeInputText id="username" v-model="username" size="large" autocomplete="off" fluid autofocus />
            <label for="username">Username</label>
          </PrimeFloatLabel>

          <PrimeFloatLabel variant="on">
            <PrimePassword id="password" v-model="password" size="large" autocomplete="off" toggle-mask fluid :feedback="false" />
            <label for="password">Password</label>
          </PrimeFloatLabel>

          <PrimeFloatLabel variant="on">
            <PrimePassword id="repeatPassword" v-model="repeatPassword" size="large" autocomplete="off" toggle-mask fluid :feedback="false" />
            <label for="repeatPassword">Repeat password</label>
          </PrimeFloatLabel>
        </div>

        <PrimeButton
          class="mt-6"
          size="large"
          label="Register"
          :loading="submitting"
          :disabled="!valid"
          type="submit"
          fluid
        />
      </form>
    </template>
  </PrimeCard>
</template>

<script lang="ts" setup>
definePageMeta({
  name: 'Register',
  layout: 'auth',
  auth: 'guest',
})

const { register } = useAuth()

const submitting = ref(false)

const username = ref<string>()
const password = ref<string>()
const repeatPassword = ref<string>()

const valid = computed(() => {
  if (!username.value)
    return false

  if (!password.value)
    return false

  if (repeatPassword.value !== password.value)
    return false

  return true
})

async function submit() {
  if (!valid.value)
    return

  submitting.value = true

  await register(username.value!, password.value!)

  submitting.value = false
}
</script>
