<script setup lang="ts">
const { loggedIn, user, fetch: refreshSession } = useUserSession();
import * as z from 'zod'
import type { FormSubmitEvent, AuthFormField } from '@nuxt/ui'

const toast = useToast()

// create data model for the form
const credentials = reactive({
  email: '',
  password: '',
})

const providers = [{
  label: 'Google',
  icon: 'i-simple-icons-google',
  onClick: () => {
    toast.add({ title: 'Google', description: 'Login with Google' })
  }
}, {
  label: 'GitHub',
  icon: 'i-simple-icons-github',
  onClick: () => {
    toast.add({ title: 'GitHub', description: 'Login with GitHub' })
  }
}]


const fields: AuthFormField[] = [{
  name: 'email',
  type: 'email',
  label: 'Email',
  placeholder: 'Enter your email',
  required: true
}, {
  name: 'password',
  label: 'Password',
  type: 'password',
  placeholder: 'Enter your password',
  required: true
}, {
  name: 'remember',
  label: 'Remember me',
  type: 'checkbox'
}]

type Schema = z.output<typeof credentials>

function formSubmit(payload: FormSubmitEvent<Schema>) {
  console.log(payload);
}

async function sendLogin() {
  try {
    await $fetch("/api/login", {
      method: "POST",
      body: credentials
    })

    await refreshSession()
    await navigateTo('/dashboard') // user home page

  } catch {
    alert("Login failed.")
  }
}
</script>

<template>
    <div class="flex flex-col items-center justify-center gap-4 p-4">
      <UPageCard class="w-full max-w-md">
        <UAuthForm
            :schema="credentials"
            title="Login"
            description="Enter your credentials to access your account."
            icon="i-lucide-user"
            :fields="fields"
            :providers="providers"
            @submit="onSubmit"
        />
      </UPageCard>
    </div>
</template>

<style scoped>

</style>