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

definePageMeta({
  layout: "notLoggedIn"
})

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

const state = reactive({
  email: '',
  password: '',
  rememberMe: true
})

const loading = ref(false)

const doLogin = async (event: FormSubmitEvent<typeof state>) => {
  loading.value = true
  try {
    await auth.login(event.data.email, event.data.password, event.data.rememberMe)
    toast.add({title:"Einloggen erfolgreich"})
    await router.push("/")
  } catch (err: any) {
    toast.add({title:"Zugangsdaten falsch. Bitte überprüfen Sie Ihre Eingaben",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">Login</h1>
        <p class="text-sm text-muted">
          Geben Sie Ihre Anmeldedaten ein um Zugriff auf Ihren Account zu erhalten.
        </p>
      </div>

      <UAlert
          v-if="auth.sessionExpired"
          color="warning"
          variant="soft"
          icon="i-heroicons-clock"
          title="Deine Sitzung ist abgelaufen"
          description="Bitte melde dich erneut an, um weiterzuarbeiten."
      />

      <UForm :state="state" class="space-y-4" @submit="doLogin">
        <UFormField label="E-Mail" name="email">
          <UInput
              v-model="state.email"
              type="email"
              class="w-full"
              placeholder="Deine E-Mail Adresse"
              autocomplete="email"
          />
        </UFormField>

        <UFormField label="Passwort" name="password">
          <template #hint>
            <NuxtLink to="/password-reset" class="text-primary font-medium">Passwort vergessen?</NuxtLink>
          </template>
          <UInput
              v-model="state.password"
              type="password"
              class="w-full"
              placeholder="Dein Passwort"
              autocomplete="current-password"
          />
        </UFormField>

        <UCheckbox
            v-model="state.rememberMe"
            name="rememberMe"
            label="Angemeldet bleiben"
        />

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