<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { useAuthStore } from "../stores/auth";
import AuthLayout from "../components/AuthLayout.vue";

const router = useRouter();
const auth = useAuthStore();

const username = ref("");
const password = ref("");
const loading = ref(false);
const feedback = ref({ severity: "", message: "" });

async function onSubmit() {
  feedback.value = { severity: "", message: "" };
  loading.value = true;

  const result = auth.login({
    username: username.value,
    password: password.value,
  });

  loading.value = false;

  if (result.ok) {
    router.push({ name: "home" });
    return;
  }

  feedback.value = { severity: "error", message: result.message };
}
</script>

<template>
  <AuthLayout title="登录" subtitle="连接你的 AI 工作空间">
    <form class="flex flex-col gap-5" @submit.prevent="onSubmit">
      <Message
        v-if="feedback.message"
        :severity="feedback.severity"
        :closable="false"
        class="w-full"
      >
        {{ feedback.message }}
      </Message>

      <div class="flex flex-col gap-2">
        <label for="login-username" class="font-mono text-xs text-text-muted uppercase">
          用户名
        </label>
        <InputText
          id="login-username"
          v-model="username"
          placeholder="请输入用户名"
          autocomplete="username"
          class="w-full"
        />
      </div>

      <div class="flex flex-col gap-2">
        <label for="login-password" class="font-mono text-xs text-text-muted uppercase">
          密码
        </label>
        <Password
          id="login-password"
          v-model="password"
          placeholder="请输入密码"
          :feedback="false"
          toggle-mask
          fluid
          input-class="w-full"
          autocomplete="current-password"
        />
      </div>

      <Button
        type="submit"
        label="登录"
        :loading="loading"
        class="w-full"
      />

      <p class="text-center text-sm text-text-muted">
        还没有账号？
        <RouterLink to="/register" class="auth-link">立即注册</RouterLink>
      </p>
    </form>
  </AuthLayout>
</template>
