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

const config = useRuntimeConfig()
const router = useRouter()
const auth = useAuthStore()
const form = ref()

interface Provider {
  name: string
  icon: string
  color: string
  loading?: boolean
}

const state = reactive({
  email: '',
  password: '',
  remember: false,
})

const { refresh: onSubmit, status: loginStatus } = useFetch<any>('login', {
  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) {
      auth.token = response._data.token

      await auth.fetchUser()
      await router.push('/')
    }
  },
})

const providers = ref<{ [key: string]: Provider }>(config.public.providers)

async function handleMessage(event: { data: any }): Promise<void> {
  const provider = event.data.provider as string

  if (Object.keys(providers.value).includes(provider) && event.data.token) {
    providers.value[provider].loading = false
    auth.token = event.data.token

    await auth.fetchUser()
    await router.push('/')
  }
  else if (event.data.message) {
    useToast().add({
      icon: 'i-heroicons-exclamation-circle-solid',
      color: 'red',
      title: event.data.message,
    })
  }
}
</script>

<template>
  <UMain>
    <UPage>
      <div class="mx-auto flex min-h-screen w-full items-center justify-center">
        <UCard class="w-96">
          <template #header>
            <div class="text-center text-4xl font-bold">
              <Logo />
            </div>
          </template>

          <UForm ref="form" :state="state" class="space-y-4" @submit="onSubmit">
            <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="loginStatus === 'pending'" icon="i-heroicons-arrow-right-on-rectangle">
              Login
            </UButton>
          </UForm>

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

<style scoped></style>
