<script setup lang="ts">
import type { FormSubmitEvent } from '#ui/types'

definePageMeta({
  layout: "notLoggedIn"
})

const auth = useAuthStore()
const toast = useToast()

const state = reactive({
  oldPassword: '',
  newPassword: ''
})

const loading = ref(false)

const doChange = async (event: FormSubmitEvent<typeof state>) => {
  loading.value = true
  try {
    await useNuxtApp().$api("/api/auth/password/change", {
      method: "POST",
      body: {
        old_password: event.data.oldPassword,
        new_password: event.data.newPassword,
      }
    })

    toast.add({title:"Ändern erfolgreich"})
    await auth.logout()
    return navigateTo("/login")
  } catch (err: any) {
    toast.add({title:"Es gab ein Problem beim ändern",color:"error"})
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <UCard class="max-w-sm w-full mx-auto mt-5">

    <UColorModeImage
        light="/Logo.png"
        dark="/Logo_Dark.png"
    />

    <div class="mt-6 space-y-5">
      <div class="space-y-1">
        <h1 class="text-xl font-semibold">Passwort ändern</h1>
        <p class="text-sm text-muted">
          Geben Sie Ihr aktuelles und Ihr neues Passwort ein.
        </p>
      </div>

      <UForm :state="state" class="space-y-4" @submit="doChange">
        <UFormField label="Altes Passwort" name="oldPassword">
          <UInput
              v-model="state.oldPassword"
              type="password"
              class="w-full"
              placeholder="Dein altes Passwort"
              autocomplete="current-password"
          />
        </UFormField>

        <UFormField label="Neues Passwort" name="newPassword">
          <UInput
              v-model="state.newPassword"
              type="password"
              class="w-full"
              placeholder="Dein neues Passwort"
              autocomplete="new-password"
          />
        </UFormField>

        <UButton type="submit" block class="w-full" :loading="loading">
          Ändern
        </UButton>
      </UForm>
    </div>
  </UCard>
</template>
