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

const router = useRouter()
const route = useRoute()
const { resetPassword } = useAuth()

if (!route.query.email) {
  router.push('/')
}

const toast = useToast()

const state = ref<ResetPasswordCredentials>({
  email: route.query.email as string,
  password: '',
  password_confirmation: '',
  token: route.params.token as string,
})

const status = ref(
  (route.query.reset ?? '').length > 0 ? atob(route.query.reset as string) : '',
)

const form = ref()

const {
  submit,
  inProgress,
  validationErrors,
} = useSubmit(
  () => {
    status.value = ''
    return resetPassword(state.value)
  },
  {
    onSuccess: () => router.push('/'),
    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>
            <h1 class="text-center text-2xl font-bold">
              Reset Password
            </h1>
          </template>

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

            <UFormGroup label="Password" name="password">
              <UInput v-model="state.password" type="password" />
            </UFormGroup>

            <UFormGroup label="Confirm Password" name="password_confirmation">
              <UInput v-model="state.password_confirmation" type="password" />
            </UFormGroup>

            <UButton block size="md" type="submit" :loading="inProgress" icon="i-heroicon-lock-closed">
              Change Password
            </UButton>
          </UForm>

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

<style scoped></style>
