<template>
  <div class="h-full w-full flex flex-col gap-5 justify-center items-center">
    <brand-header />
    <n-card segmented class="w-[380px]">
      <template #header>
        <div class="text-center">Sign in</div>
        <div class="text-center text-xs font-normal">With your email</div>
      </template>

      <n-form @submit.prevent="submit">
        <n-form-item label="Email">
          <n-input v-model:value="payload.email" placeholder="Your email" />
        </n-form-item>
        <n-form-item label="Password">
          <n-input v-model:value="payload.password" type="password" placeholder="Your password" />
        </n-form-item>
        <n-button :loading="loading" attr-type="submit" class="w-full" type="primary">Login</n-button>
      </n-form>
    </n-card>

    <div class="flex w-[360px] justify-between">
      <nuxt-link>Haven't an account?</nuxt-link>
      <helpful-links />
    </div>
  </div>
</template>

<script setup lang="ts">
import { NCard, NForm, NFormItem, NInput, NButton } from "naive-ui";
import { useMessage } from "naive-ui";
import { ref } from "vue";

const client = useSupabaseClient();
const message = useMessage();

const loading = ref(false);
const payload = ref({
  email: "",
  password: "",
});

async function submit() {
  if (!payload.value.email || !payload.value.password) return;

  try {
    loading.value = true;
    const { error } = await client.auth.signInWithPassword({
      email: payload.value.email,
      password: payload.value.password,
    });
    if (error) throw error;
    message.success("Welcome back!");
    navigateTo("/");
  } catch (err: any) {
    message.error(err.error_description || err.message);
  } finally {
    loading.value = false;
  }
}
</script>
