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

import { showError, showSuccess } from '@/lib/feedback'
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()) {
    showError('请输入账号和密码')
    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)
    showSuccess('登录成功')
    await router.replace('/admin/dashboard')
  } catch (error) {
    showError(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>
        <el-input v-model="username" placeholder="输入账号" @keyup.enter="submitLogin" />
      </label>

      <label class="field">
        <span>密码</span>
        <el-input
          v-model="password"
          type="password"
          placeholder="输入密码"
          show-password
          @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: var(--space-4);
  background:
    radial-gradient(circle at top left, rgba(59, 130, 246, 0.12), transparent 28%),
    radial-gradient(circle at bottom right, rgba(59, 130, 246, 0.08), transparent 26%),
    linear-gradient(160deg, var(--color-primary-light) 0%, #f7fbff 42%, #edf6f3 100%);
}

.login-card {
  width: min(460px, 100%);
  padding: 28px;
  border-radius: var(--radius-xl);
  border: 1px solid var(--border-default);
  background: var(--bg-surface);
  box-shadow: var(--shadow-lg);
}

.login-header h1 {
  margin: var(--space-2) 0 0;
  color: var(--text-primary);
}

.login-header p {
  margin: 10px 0 0;
  color: var(--text-secondary);
}

.eyebrow {
  margin: 0;
  color: var(--color-primary);
  text-transform: uppercase;
  letter-spacing: 0.12em;
  font-size: var(--text-xs);
  font-weight: 700;
}

.field {
  margin-top: var(--space-6);
  display: grid;
  gap: 10px;
  color: var(--text-primary);
}

.submit-btn {
  width: 100%;
  margin-top: var(--space-5);
}
</style>
