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

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

const toast = useToast()

const form = ref()

const state = ref<LoginCredentials>({
  email: '',
  password: '',
  remember: false,
})

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

const {
  submit,
  inProgress,
  validationErrors,
} = useSubmit(
  () => {
    status.value = ''
    return login(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">
              Login
            </h1>
          </template>

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

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

            <div class="flex items-center justify-between">
              <UCheckbox id="remember-me" v-model="state.remember" label="Remember me" name="remember-me" />

              <div class="text-sm leading-6">
                <NuxtLink to="/forgot-password" class="text-primary hover:text-primary-300 font-semibold">
                  Forgot
                  password?
                </NuxtLink>
              </div>
            </div>

            <UButton block size="md" type="submit" :loading="inProgress" icon="i-heroicons-arrow-right-on-rectangle">
              Login
            </UButton>
          </UForm>

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

<style scoped></style>
