<script setup lang="ts">
import { ref } from 'vue'
import { RouterLink } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { getApiErrorMessage } from '@/services/api'

const auth = useAuthStore()
const name = ref('')
const email = ref('')
const password = ref('')
const passwordConfirmation = ref('')
const error = ref('')
const loading = ref(false)

async function submit() {
  error.value = ''

  if (password.value.length < 8) {
    error.value = 'Password must be at least 8 characters.'
    return
  }

  if (password.value !== passwordConfirmation.value) {
    error.value = 'Password confirmation does not match.'
    return
  }

  loading.value = true

  try {
    await auth.register({
      name: name.value,
      email: email.value,
      password: password.value,
      password_confirmation: passwordConfirmation.value,
    })
  } catch (registrationError) {
    error.value = getApiErrorMessage(registrationError, 'Registration failed. Check the form and try again.')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <section class="panel form-page">
    <h2>Create Account</h2>
    <p>Start a BizNovia SaaS workspace account.</p>

    <form class="form" @submit.prevent="submit">
      <div class="field">
        <label for="name">Name</label>
        <input id="name" v-model="name" autocomplete="name" type="text" required />
      </div>

      <div class="field">
        <label for="email">Email</label>
        <input id="email" v-model="email" autocomplete="email" type="email" required />
      </div>

      <div class="field">
        <label for="password">Password</label>
        <input id="password" v-model="password" autocomplete="new-password" minlength="8" type="password" required />
      </div>

      <div class="field">
        <label for="password_confirmation">Confirm Password</label>
        <input id="password_confirmation" v-model="passwordConfirmation" autocomplete="new-password" minlength="8" type="password" required />
      </div>

      <p v-if="error" class="error">{{ error }}</p>
      <button class="button primary" type="submit" :disabled="loading || password.length < 8 || password !== passwordConfirmation">
        {{ loading ? 'Creating...' : 'Register' }}
      </button>

      <RouterLink class="muted-link" to="/login">Already have an account?</RouterLink>
    </form>
  </section>
</template>
