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

const router = useRouter();
const route = useRoute();
const auth = useAuthStore();
const form = ref();

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

const { refresh: onSubmit, status: resetStatus } = useFetch<any>("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: "emerald",
      });

      if (auth.isLoggedIn) {
        await auth.fetchUser();
        await router.push("/");
      } else {
        await router.push("/login");
      }
    }
  }
});
</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="onSubmit">
            <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="resetStatus === 'pending'" icon="i-heroicon-lock-closed">
              Change Password
            </UButton>
          </UForm>

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

<style scoped></style>
