<script setup lang="ts">
import { ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useSessionStore } from "../stores/session";
import { useConfigStore } from "../stores/config";
import BaseInput from "../components/BaseInput.vue";
import BaseButton from "../components/BaseButton.vue";
import type { ApiError } from "../api/client";

const session = useSessionStore();
const config = useConfigStore();
const router = useRouter();
const route = useRoute();

const email = ref("");
const password = ref("");
const error = ref("");
const loading = ref(false);

async function submit() {
  error.value = "";
  loading.value = true;
  try {
    await session.login(email.value, password.value);
    const redirect = typeof route.query.redirect === "string" ? route.query.redirect : "/";
    await router.replace(redirect);
  } catch (e) {
    error.value = (e as ApiError).error ?? "Could not sign in.";
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <main class="flex min-h-full items-center justify-center px-4 py-12">
    <div class="w-full max-w-sm">
      <div class="mb-8 text-center">
        <div
          class="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-xl bg-brand text-lg font-black text-neutral-900"
        >
          TS
        </div>
        <h1 class="text-2xl font-bold tracking-tight">Welcome back</h1>
        <p class="mt-1 text-sm text-neutral-500 dark:text-neutral-400">Sign in to your thoughts.</p>
      </div>

      <form class="flex flex-col gap-4" novalidate @submit.prevent="submit">
        <BaseInput
          id="email"
          v-model="email"
          label="Email"
          type="email"
          autocomplete="email"
          placeholder="you@example.com"
          required
        />
        <BaseInput
          id="password"
          v-model="password"
          label="Password"
          type="password"
          autocomplete="current-password"
          placeholder="••••••••"
          required
        />
        <p
          v-if="error"
          role="alert"
          class="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700 dark:bg-red-950/50 dark:text-red-300"
        >
          {{ error }}
        </p>
        <BaseButton type="submit" :loading="loading">Sign in</BaseButton>
      </form>

      <p v-if="config.allowRegistration" class="mt-6 text-center text-sm text-neutral-500 dark:text-neutral-400">
        No account?
        <RouterLink to="/register" class="font-semibold text-brand-700 hover:underline dark:text-brand"
          >Create one</RouterLink
        >
      </p>
    </div>
  </main>
</template>
