<script setup lang="ts">
import type { IForgotPasswordResponse } from '~/types/account'

const form = useTemplateRef('form')

const state = reactive({
  email: '',
})

const { refresh: onSubmit, status: forgotStatus } = useFetch<IForgotPasswordResponse>('forgot-password', {
  method: 'POST',
  body: state,
  immediate: false,
  watch: false,
  async onResponse({ response }) {
    if (response?.status === 422) {
      form.value.setErrors(response._data?.errors)
    }
    else if (response._data?.ok) {
      useToast().add({
        title: 'Success',
        description: response._data.message,
        color: 'primary',
      })
    }
  },
})
</script>

<template>
  <UForm
    ref="form"
    :state="state"
    class="space-y-8"
    @submit="onSubmit"
  >
    <UFormField
      label="Email"
      name="email"
    >
      <UInput
        v-model="state.email"
        class="w-full"
      />
    </UFormField>

    <UButton
      block
      size="md"
      type="submit"
      :loading="forgotStatus === 'pending'"
      icon="i-heroicons-envelope"
    >
      Reset Password
    </UButton>
  </UForm>
</template>
