<script setup lang="ts">
import type { AuthFormField, FormSubmitEvent } from '@nuxt/ui'
import type * as v from 'valibot'
import { useForm } from '@inertiajs/vue3'
import { computed } from 'vue'
import AuthLayout from '@/layouts/AuthLayout.vue'
import { completeProfileSchema } from '@/validation/auth'

const props = defineProps<{
  socialiteUser: {
    email: string
    first_name: string
    last_name: string
    suggested_username: string
    provider: string
  }
}>()

const form = useForm({
  username: props.socialiteUser.suggested_username,
  first_name: props.socialiteUser.first_name,
  last_name: props.socialiteUser.last_name,
})

const fields: AuthFormField[] = [
  {
    name: 'username',
    type: 'text',
    label: 'Username',
    placeholder: 'Choose a unique username',
    required: true,
    hint: 'The suggested username was already taken. Please choose a different one.',
  },
  {
    name: 'first_name',
    type: 'text',
    label: 'First name',
    placeholder: 'Enter your first name',
    required: true,
  },
  {
    name: 'last_name',
    type: 'text',
    label: 'Last name',
    placeholder: 'Enter your last name',
    required: true,
  },
]

const schema = completeProfileSchema

type Schema = v.InferOutput<typeof schema>

function onSubmit(event: FormSubmitEvent<Schema>) {
  form.username = event.data.username
  form.first_name = event.data.first_name
  form.last_name = event.data.last_name

  form.post('/complete-profile')
}

const hasErrors = computed(() => Object.keys(form.errors).length > 0)
const firstError = computed(() => Object.values(form.errors)[0])
</script>

<template>
  <AuthLayout>
    <UAuthForm
      :schema="schema"
      :fields="fields"
      :submit="{ label: 'Complete registration', loading: form.processing }"
      :disabled="form.processing"
      :ui="{ header: 'hidden' }"
      @submit="onSubmit"
    >
      <template v-if="hasErrors" #validation>
        <UAlert
          color="error"
          icon="i-lucide-alert-circle"
          :title="firstError"
        />
      </template>

      <template #footer>
        <span class="text-muted">
          Signing up with {{ socialiteUser.email }}
        </span>
      </template>
    </UAuthForm>
  </AuthLayout>
</template>
