<script setup lang="ts">
definePageMeta({ middleware: ['guest'] })

const router = useRouter()
const { forgotPassword } = useAuth()

const form = ref()

const toast = useToast()

const state = ref({
  email: '' as string,
})

const status = ref('')

const {
  submit,
  inProgress,
  validationErrors,
} = useSubmit(
  () => {
    status.value = ''
    return forgotPassword(state.value.email)
  },
  {
    onSuccess: () => router.push('/login'),
    onError: error => toast.add({ title: 'Error', description: error.message, color: 'red' }),
  },
)

watch(validationErrors, async (errors) => {
  if (errors.length > 0) {
    await form.value?.setErrors(errors)
  }
})
</script>

<template>
  <UMain>
    <UPage>
      <div class="mx-auto flex min-h-screen w-full items-center justify-center">
        <UCard class="w-96">
          <template #header>
            <div class="space-y-4 text-center ">
              <h1 class="text-2xl font-bold">
                Forgot Password
              </h1>
              <p class="text-sm">
                Remember your password? <NuxtLink to="/login" class="text-primary hover:text-primary-300 font-semibold">
                  Login here
                </NuxtLink>
              </p>
            </div>
          </template>

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

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

          <!-- <UDivider label="OR" class=" my-4"/> -->
        </UCard>
      </div>
    </UPage>
  </UMain>
</template>
