<template>
  <v-container fluid class="fill-height pa-0" style="background: rgb(var(--v-theme-background))">
    <v-row align="center" justify="center" no-gutters style="min-height: 100vh">
      <v-col cols="12" sm="8" md="5" lg="4">
        <v-card elevation="0" rounded="lg" class="pa-8" color="surface" border>
          <!-- Logo -->
          <div class="text-center mb-8">
            <v-avatar color="primary" size="56" rounded="lg" class="mb-4">
              <v-icon icon="mdi-server-network" size="32" color="white" />
            </v-avatar>
            <div class="text-h5 font-weight-bold">Nexus</div>
            <div class="text-body-2 text-medium-emphasis mt-1">服务器运维管理平台</div>
          </div>

          <!-- Error Alert -->
          <v-alert v-if="error" type="error" density="compact" class="mb-4" closable @click:close="error = ''" rounded="lg">
            {{ error }}
          </v-alert>

          <!-- Lockout Warning -->
          <v-alert v-if="lockoutUntil" type="warning" density="compact" class="mb-4" rounded="lg">
            账户已锁定，请 {{ remainingMinutes }} 分钟后重试
          </v-alert>

          <!-- Form -->
          <v-form @submit.prevent="doLogin">
            <v-text-field
              v-model="username"
              label="用户名"
              variant="outlined"
              density="comfortable"
              prepend-inner-icon="mdi-account-outline"
              :disabled="loading"
              class="mb-3"
              autocomplete="username"
              rounded="lg"
            />

            <v-text-field
              v-model="password"
              label="密码"
              variant="outlined"
              density="comfortable"
              prepend-inner-icon="mdi-lock-outline"
              :append-inner-icon="showPassword ? 'mdi-eye' : 'mdi-eye-off'"
              :type="showPassword ? 'text' : 'password'"
              @click:append-inner="showPassword = !showPassword"
              :disabled="loading"
              class="mb-3"
              autocomplete="current-password"
              rounded="lg"
            />

            <v-text-field
              v-if="needTotp"
              v-model="totpCode"
              label="TOTP 验证码"
              variant="outlined"
              density="comfortable"
              prepend-inner-icon="mdi-shield-key-outline"
              :disabled="loading"
              class="mb-3"
              autocomplete="one-time-code"
              rounded="lg"
            />

            <v-btn
              type="submit"
              color="primary"
              variant="flat"
              block
              size="large"
              :loading="loading"
              :disabled="!!lockoutUntil"
              rounded="lg"
              class="mt-2"
            >
              登录
            </v-btn>
          </v-form>

          <!-- Failed attempts -->
          <div v-if="failedAttempts > 0 && !lockoutUntil" class="text-caption text-warning text-center mt-4">
            已失败 {{ failedAttempts }} 次（5 次后锁定 15 分钟）
          </div>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ApiError } from '@/api'

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

// ── State ──
const username = ref('')
const password = ref('')
const totpCode = ref('')
const showPassword = ref(false)
const loading = ref(false)
const error = ref('')
const needTotp = ref(false)
const failedAttempts = ref(0)
const lockoutUntil = ref<string | null>(null)

const remainingMinutes = computed(() => {
  if (!lockoutUntil.value) return 0
  const diff = new Date(lockoutUntil.value).getTime() - Date.now()
  return Math.max(1, Math.ceil(diff / 60000))
})

// ── Login ──
async function doLogin() {
  if (!username.value || !password.value) {
    error.value = '请输入用户名和密码'
    return
  }

  loading.value = true
  error.value = ''

  try {
    await auth.login(username.value, password.value, needTotp.value ? totpCode.value : undefined)
    const redirect = (route.query.redirect as string) || '/'
    router.push(redirect)
  } catch (e: any) {
    if (e instanceof ApiError) {
      if (e.status === 429) {
        const retryAfter = new Date(Date.now() + 15 * 60 * 1000).toISOString()
        lockoutUntil.value = retryAfter
        error.value = '登录尝试过多，账户已锁定 15 分钟'
      } else if (e.message.includes('TOTP') || e.message.includes('totp') || e.message.includes('验证码')) {
        needTotp.value = true
        error.value = e.message
      } else {
        failedAttempts.value++
        error.value = e.message
      }
    } else {
      error.value = '网络错误，请重试'
    }
  } finally {
    loading.value = false
  }
}
</script>
