<template>
  <div class="card card-dash h-80 w-100 shadow-xl bg-base-100">
    <div class="card-body">
      <h1 class="card-title place-self-center my-3 text-2xl">User Login</h1>
      <div class="flex flex-col w-full h-full">
        <label class="input w-full my-3">
          <img
            class="h-[1em] opacity-50"
            src="@/assets/user.svg"
            alt="User img"
          />
          <input
            type="text"
            class="grow"
            placeholder="用户名"
            v-model="username"
            @keyup.enter="handleLogin"
          />
        </label>
        <label class="input w-full my-3">
          <img
            class="h-[1em] opacity-50"
            src="@/assets/pwd.svg"
            alt="User img"
          />
          <input
            type="password"
            class="grow"
            placeholder="密码"
            v-model="password"
            @keyup.enter="handleLogin"
          />
        </label>
      </div>
      <div class="flex justify-end mx-3">
        <RouterLink to="/">忘记密码?</RouterLink>
      </div>
      <div class="card-actions flex items-end my-3">
        <button class="btn flex-1" @click="handleRegister">注册</button>
        <button
          class="btn btn-primary flex-3"
          @click="handleLogin"
          :disabled="isLoading"
        >
          {{ isLoading ? "登录中..." : "登录" }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { AuthManager } from "@/utils/AuthManager";
import { useAlertStore } from "@/components/Alert";

const router = useRouter();

// 获取Alert store
const alertStore = useAlertStore();

// 响应式数据
const username = ref("");
const password = ref("");
const isLoading = ref(false);

// 登录处理函数
const handleLogin = async () => {
  // 验证输入
  if (!username.value.trim()) {
    alertStore?.show("请输入用户名", "error");
    return;
  }

  if (!password.value.trim()) {
    alertStore?.show("请输入密码", "error");
    return;
  }

  isLoading.value = true;

  try {
    // 调用AuthManager的登录函数
    await AuthManager.login(username.value.trim(), password.value.trim());

    // 登录成功，显示成功消息并跳转
    alertStore?.show("登录成功", "success", 1000);

    // 短暂延迟后跳转到project页面
    setTimeout(async () => {
      await router.push("/project");
    }, 1000);
  } catch (error: any) {
    console.error("Login error:", error);

    // 处理不同类型的错误
    let errorMessage = "登录失败，请检查网络连接";

    if (error.status === 400) {
      errorMessage = "用户名或密码错误";
    } else if (error.status === 401) {
      errorMessage = "用户名或密码错误";
    } else if (error.status === 500) {
      errorMessage = "服务器错误，请稍后重试";
    } else if (error.message) {
      errorMessage = error.message;
    }

    alertStore?.show(errorMessage, "error");
  } finally {
    isLoading.value = false;
  }
};

// 注册处理函数（可以根据需要实现）
const handleRegister = () => {
  // 这里可以导航到注册页面或者打开注册模态框
  console.log("Navigate to register page");
  // router.push('/register')
};

// 页面初始化时检查是否已有有效token
const checkExistingToken = async () => {
  try {
    const isValid = await AuthManager.verifyToken();
    if (isValid) {
      // 如果token仍然有效，直接跳转到project页面
      await router.push("/project");
    }
  } catch (error) {
    // token无效或验证失败，继续显示登录页面
    console.log("Token verification failed, showing login page");
  }
};

// 组件挂载时检查已存在的token
onMounted(() => {
  checkExistingToken();
});
</script>

<style scoped>
@import "@/assets/main.css";
</style>
