<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 { useAuth } from '@/composables/useAuth'
import AuthLayout from '@/layouts/AuthLayout.vue'
import { resetPasswordSchema } from '@/validation/auth'

const props = defineProps<{
  email: string
  token: string
}>()

const { config } = useAuth()

const form = useForm('ResetPasswordForm', {
  token: props.token,
  email: props.email,
  password: '',
  password_confirmation: '',
})

const fields: AuthFormField[] = [
  {
    name: 'email',
    type: 'email',
    label: 'Email',
    placeholder: 'Enter your email',
    required: true,
  },
  {
    name: 'password',
    type: 'password',
    label: 'New password',
    placeholder: 'Enter your new password',
    required: true,
  },
  {
    name: 'password_confirmation',
    type: 'password',
    label: 'Confirm password',
    placeholder: 'Confirm your new password',
    required: true,
  },
]

const schema = resetPasswordSchema

type Schema = v.InferOutput<typeof schema>

function onSubmit(event: FormSubmitEvent<Schema>) {
  form.email = event.data.email
  form.password = event.data.password
  form.password_confirmation = event.data.password_confirmation

  form.post('/reset-password')
}

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: config.resetPassword.submit_label, 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">
          Remember your password?
          <ULink to="/login" class="text-primary font-medium">
            Sign in
          </ULink>
        </span>
      </template>
    </UAuthForm>
  </AuthLayout>
</template>
