<template>
  <section class="container-page grid min-h-[70vh] place-items-center py-10">
    <div class="card w-full max-w-md p-6">
      <h1 class="text-2xl font-extrabold">Selamat Datang Kembali!</h1>
      <p class="mt-2 text-sm text-slate-600">Masuk dan lanjutkan jualanmu.</p>

      <form class="mt-6 grid gap-4" @submit.prevent="login">
        <p v-if="errorMessage" class="rounded-xl bg-red-50 px-4 py-3 text-sm font-semibold text-red-700">
          {{ errorMessage }}
        </p>
        <div>
          <label class="label">Email</label>
          <input v-model="email" type="email" class="input mt-2" placeholder="nama@email.com" required />
        </div>
        <div>
          <label class="label">Password</label>
          <input v-model="password" type="password" class="input mt-2" placeholder="••••••••" required />
        </div>
        <button class="btn-primary w-full" :disabled="loading">
          {{ loading ? "Memproses..." : "Masuk" }}
        </button>
      </form>

      <p class="mt-5 text-center text-sm text-slate-600">
        Belum punya akun?
        <RouterLink to="/register" class="font-bold text-brand-700">Register</RouterLink>
      </p>
    </div>
  </section>
</template>

<script setup>
import { ref } from "vue"
import { useRouter } from "vue-router"
import { loginUser, setAuth } from "../utils"

const router = useRouter()
const email = ref("")
const password = ref("")
const loading = ref(false)
const errorMessage = ref("")

async function login() {
  loading.value = true
  errorMessage.value = ""

  try {
    const data = await loginUser({
      email: email.value,
      password: password.value
    })
    setAuth(data)
    router.push("/dashboard")
  } catch (error) {
    errorMessage.value = error.message
  } finally {
    loading.value = false
  }
}
</script>
