<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

import { loginAdmin } from '@/services/admin'
import { setAdminSession } from '@/utils/admin-auth'

const router = useRouter()
const loading = ref(false)
const username = ref('')
const password = ref('')

async function submitLogin() {
  if (!username.value.trim() || !password.value.trim()) {
    ElMessage.error('请输入账号和密码')
    return
  }

  loading.value = true

  try {
    const response = await loginAdmin({
      username: username.value.trim(),
      password: password.value.trim(),
    })

    setAdminSession(response.data.token, response.data.expiresAt, response.data.user)
    ElMessage.success('登录成功')
    await router.replace('/admin/dashboard')
  } catch (error) {
    ElMessage.error(error instanceof Error ? error.message : '后台登录失败')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <main class="login-page">
    <section class="login-card">
      <header class="login-header">
        <p class="eyebrow">Order Site Admin</p>
        <h1>运营后台登录</h1>
        <p>使用账号密码进入后台，并按角色开放不同操作权限。</p>
      </header>

      <label class="field">
        <span>账号</span>
        <input
          v-model="username"
          type="text"
          class="text-input"
          placeholder="输入账号"
          @keyup.enter="submitLogin"
        />
      </label>

      <label class="field">
        <span>密码</span>
        <input
          v-model="password"
          type="password"
          class="text-input"
          placeholder="输入密码"
          @keyup.enter="submitLogin"
        />
      </label>

      <el-button :loading="loading" round type="primary" class="submit-btn" @click="submitLogin">
        登录后台
      </el-button>
    </section>
  </main>
</template>

<style scoped>
.login-page {
  min-height: 100vh;
  display: grid;
  place-items: center;
  padding: 24px;
  background:
    radial-gradient(circle at top left, rgba(18, 102, 214, 0.18), transparent 28%),
    radial-gradient(circle at bottom right, rgba(12, 74, 110, 0.16), transparent 26%),
    linear-gradient(160deg, #eef5ff 0%, #f7fbff 42%, #edf6f3 100%);
}

.login-card {
  width: min(460px, 100%);
  padding: 28px;
  border-radius: 28px;
  border: 1px solid rgba(38, 88, 155, 0.14);
  background: rgba(255, 255, 255, 0.92);
  box-shadow: 0 24px 80px rgba(15, 23, 42, 0.08);
}

.login-header h1 {
  margin: 8px 0 0;
  color: #17324f;
}

.login-header p {
  margin: 10px 0 0;
  color: #5f7289;
}

.eyebrow {
  margin: 0;
  color: #1266d6;
  text-transform: uppercase;
  letter-spacing: 0.12em;
  font-size: 12px;
  font-weight: 700;
}

.field {
  margin-top: 24px;
  display: grid;
  gap: 10px;
  color: #334155;
}

.text-input {
  min-height: 48px;
  padding: 0 16px;
  border-radius: 16px;
  border: 1px solid rgba(86, 108, 138, 0.2);
  background: rgba(255, 255, 255, 0.96);
}

.submit-btn {
  width: 100%;
  margin-top: 20px;
}
</style>
