<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import request from '../utils/request'
import ParticleBackground from '../components/ParticleBackground.vue'
import { GITCC_LOGO_URL, PRODUCT_TITLE, PRODUCT_TAGLINE } from '../shellConstants'

const router = useRouter()
const username_or_email = ref('')
const password = ref('')
const isLogining = ref(false)
const formRef = ref(null)

const validateEmail = (rule, value, callback) => {
  const emailRegex = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/
  if (value.includes('@') && !emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱格式'))
  } else {
    callback()
  }
}

const formRules = {
  username_or_email: [
    { required: true, message: '请输入用户名或邮箱', trigger: ['blur', 'change'] },
    { validator: validateEmail, trigger: ['blur', 'change'] },
  ],
  password: [{ required: true, message: '请输入密码', trigger: ['blur', 'change'] }],
}

const handleLogin = async () => {
  if (!formRef.value) {
    ElMessage.error({
      message: '【登录错误】表单实例不存在',
      duration: 5000,
    })
    return
  }

  try {
    await formRef.value.validate()
    isLogining.value = true

    const formData = new FormData()
    formData.append('username_or_email', username_or_email.value)
    formData.append('password', password.value)

    const safeFormData = {
      username_or_email: username_or_email.value,
      has_password: password.value ? '已设置' : '未设置',
    }
    console.info('【登录表单数据】', safeFormData)

    const data = await request.post('/user/login', formData)
    console.info('【登录响应数据】', data)
    const operation = data.operation

    if (data && operation && operation.status === 'SUCCESS') {
      localStorage.setItem('access_token', data.access_token)
      localStorage.setItem('refresh_token', data.refresh_token)
      localStorage.setItem('login_user', JSON.stringify(data.login_user))
      console.info('【登录用户】', data.login_user)

      ElMessage.success({
        message: '【登录成功】',
        duration: 3000,
      })

      router.push('/home')
    }
  } catch (error) {
    console.error('【登录错误】', error)
    ElMessage.error({
      message: '【登录错误】' + (error?.message || '请重试'),
      duration: 5000,
    })
  } finally {
    isLogining.value = false
  }
}

onMounted(() => {
  const token = localStorage.getItem('access_token')
  if (token) {
    ElMessage.success({
      message: '【登录成功】您已登录，正在跳转到首页...',
      duration: 3000,
    })
    router.push('/home')
  }
})
</script>

<template>
  <div class="hud-auth">
    <aside class="hud-auth-brand" aria-labelledby="login-brand-title">
      <div class="hud-auth-brand-inner">
        <img :src="GITCC_LOGO_URL" :alt="PRODUCT_TITLE" class="brand-logo" width="56" height="56" />
        <h2 id="login-brand-title">
          欢迎进入 <span class="accent">{{ PRODUCT_TITLE }}</span>
        </h2>
        <p class="brand-lead">{{ PRODUCT_TAGLINE }}</p>
        <ul>
          <li>桥梁安全隐患检测与记录统一入口</li>
          <li>媒体与模型资源可管可控</li>
          <li>控制台级状态与导航结构</li>
        </ul>
      </div>
    </aside>

    <div class="hud-auth-panel">
      <div class="hud-auth-particles" aria-hidden="true">
        <ParticleBackground />
      </div>

      <div class="hud-auth-form-card">
        <div class="form-head">
          <h1 class="form-title">登录</h1>
          <p class="form-sub">使用已有账号进入工作台</p>
        </div>

        <el-form
          ref="formRef"
          :model="{ username_or_email, password }"
          :rules="formRules"
          class="login-form"
          status-icon
          @submit.prevent="handleLogin"
          @keyup.enter="handleLogin"
        >
          <el-form-item prop="username_or_email">
            <el-input v-model="username_or_email" placeholder="用户名或邮箱" :prefix-icon="User" />
          </el-form-item>

          <el-form-item prop="password">
            <el-input v-model="password" type="password" placeholder="密码" :prefix-icon="Lock" show-password />
          </el-form-item>

          <el-button type="primary" :loading="isLogining" class="submit-btn" @click="handleLogin">
            {{ isLogining ? '登录中...' : '登录' }}
          </el-button>

          <div class="form-footer">
            <el-button link type="primary" @click="router.push('/register')" class="text-btn">注册账号</el-button>
            <el-button link type="primary" @click="router.push('/forgot-password')" class="text-btn">
              忘记密码 / 联系管理员
            </el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.brand-logo {
  border-radius: 14px;
  margin-bottom: 18px;
  box-shadow: 0 0 0 1px rgba(79, 70, 229, 0.35);
}
.brand-lead {
  margin: 0 0 8px;
  font-size: 0.95rem;
  color: var(--muted);
  line-height: 1.55;
  max-width: 36ch;
}
.hud-auth-particles {
  position: absolute;
  inset: 0;
  z-index: 0;
  pointer-events: none;
  overflow: hidden;
}
.hud-auth-particles :deep(canvas) {
  pointer-events: none;
}
.form-head {
  margin-bottom: 18px;
}
.form-title {
  margin: 0;
  font-size: 1.35rem;
  font-weight: 800;
  letter-spacing: -0.02em;
  color: var(--foreground);
}
.form-sub {
  margin: 6px 0 0;
  font-size: 0.88rem;
  color: var(--muted);
}
.login-form {
  display: flex;
  flex-direction: column;
  gap: 4px;
  width: 100%;
}
:deep(.el-form-item) {
  margin-bottom: 16px;
}
:deep(.el-input__wrapper) {
  border-radius: 10px;
  box-shadow: 0 0 0 1px var(--border) inset;
  background: color-mix(in srgb, var(--card-solid) 92%, transparent);
}
:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px color-mix(in srgb, var(--primary) 45%, var(--border)) inset,
    0 0 0 3px color-mix(in srgb, var(--primary) 18%, transparent);
}
.submit-btn {
  width: 100%;
  margin-top: 8px;
  height: 42px;
  font-weight: 600;
  border-radius: 10px;
  background: linear-gradient(180deg, color-mix(in srgb, var(--primary) 100%, #000), var(--primary));
  border-color: color-mix(in srgb, var(--primary) 85%, #000);
  box-shadow: 0 8px 22px color-mix(in srgb, var(--primary) 28%, transparent);
}
.submit-btn:active {
  transform: translateY(1px) scale(0.98);
  filter: brightness(0.96);
}
.form-footer {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 14px;
}
.text-btn {
  font-size: 13px;
}
@media (prefers-reduced-motion: reduce) {
  .submit-btn:active {
    transform: none;
  }
}
</style>
