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

const router = useRouter()
const route = useRoute()
const auth = useAuthStore()
const form = useTemplateRef('form')

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

const { refresh: onSubmit, status: resetStatus } = useFetch<IAccountResetPasswordResponse>('reset-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',
      })

      if (auth.isLoggedIn) {
        await auth.fetchUser()
        await router.push('/')
      }
      else {
        await router.push('/login')
      }
    }
  },
})
</script>

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

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

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

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