<template>
  <section class="mx-auto flex min-h-[70vh] max-w-lg flex-col justify-center gap-6">
    <div class="text-center">
      <h1 class="mos-title text-2xl font-semibold">管理员登录</h1>
      <p class="mos-muted mt-2 text-sm">{{ isDemoMode ? '使用演示账号快速预览功能' : '请输入管理员账号密码登录' }}</p>
    </div>

    <div class="mos-card p-6 space-y-4">
      <!-- 真实登录表单 -->
      <div v-if="mode === 'real'">
        <div>
          <label class="text-xs font-semibold text-mosquito-ink/70">用户名</label>
          <input
            v-model="username"
            class="mos-input mt-2 w-full"
            placeholder="管理员账号"
          />
        </div>
        <div>
          <label class="text-xs font-semibold text-mosquito-ink/70">密码</label>
          <input
            v-model="password"
            class="mos-input mt-2 w-full"
            type="password"
            placeholder="••••••••"
            @keyup.enter="login"
          />
        </div>
        <div v-if="errorMessage" class="text-red-500 text-sm mt-2">
          {{ errorMessage }}
        </div>
        <button
          class="mos-btn mos-btn-accent w-full mt-4"
          :disabled="loading"
          @click="login"
        >
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </div>

      <!-- 演示登录入口（始终显示） -->
      <div class="border-t border-mosquito-line pt-4">
        <button class="mos-btn mos-btn-secondary w-full" @click="loginDemo">
          一键登录（演示管理员）
        </button>
        <p class="mos-muted mt-2 text-xs text-center">在任何模式下均可使用演示账号快速体验</p>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { authApi } from '../services/api/AuthApi'

const auth = useAuthStore()
const router = useRouter()
const route = useRoute()

const username = ref('')
const password = ref('')
const loading = ref(false)
const errorMessage = ref('')

const mode = computed(() => auth.mode)
const isDemoMode = computed(() => auth.isDemoMode)

// auto模式下自动登录demo
onMounted(() => {
  const envMode = import.meta.env.VITE_MOSQUITO_AUTH_MODE
  if (envMode === 'auto' && !auth.isAuthenticated) {
    loginDemo()
  }
})

const login = async () => {
  if (!username.value || !password.value) {
    errorMessage.value = '请输入用户名和密码'
    return
  }

  loading.value = true
  errorMessage.value = ''

  try {
    const response = await authApi.login(username.value, password.value)

    if (response) {
      // 真实登录成功
      const role = (response.roles && response.roles[0]) as any || 'viewer'
      await auth.login({
        id: response.userId,
        name: response.displayName,
        email: response.username,
        role: role
      }, response.token)

      // 跳转到原始页面或首页
      const redirect = route.query.redirect as string
      await router.push(redirect || '/')
    } else {
      errorMessage.value = '用户名或密码错误'
    }
  } catch (error) {
    errorMessage.value = '登录失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

const loginDemo = async () => {
  await auth.loginDemo('super_admin')
  await router.push('/')
}
</script>
