<template>
  <div class="auth-page">
    <el-card class="auth-card">
      <h2>登录</h2>

      <!-- 角色选择 -->
      <div class="role-tabs">
        <button
          :class="['role-tab', { active: role === 'seeker' }]"
          @click="role = 'seeker'"
        >
          求职者
        </button>
        <button
          :class="['role-tab', { active: role === 'admin' }]"
          @click="role = 'admin'"
        >
          管理员
        </button>
      </div>

      <!-- 求职者登入 -->
      <div v-if="role === 'seeker'" class="login-container">
        <!-- 登入方式选择 -->
        <div class="method-tabs">
          <button
            :class="['method-tab', { active: seekerMethod === 'password' }]"
            @click="seekerMethod = 'password'"
          >
            邮箱/用户名登入
          </button>
          <button
            :class="['method-tab', { active: seekerMethod === 'code' }]"
            @click="seekerMethod = 'code'"
          >
            验证码登入
          </button>
        </div>

        <!-- 密码登入 -->
        <el-form v-if="seekerMethod === 'password'" :model="passwordForm" @submit.prevent="handlePasswordLogin">
          <el-form-item>
            <el-input
              v-model="passwordForm.username"
              placeholder="邮箱或用户名"
            />
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="passwordForm.password"
              type="password"
              placeholder="密码"
              show-password
            />
          </el-form-item>
          <el-button
            type="primary"
            native-type="submit"
            :loading="passwordLoading"
            style="width: 100%"
          >
            登录
          </el-button>
          <div style="text-align: right; margin-top: 8px;">
            <router-link to="/forgot-password" style="color: var(--text-muted); font-size: 12px; text-decoration: none;">
              忘记密码？
            </router-link>
          </div>
        </el-form>

        <!-- 验证码登入 -->
        <el-form v-if="seekerMethod === 'code'" @submit.prevent="handleCodeLogin">
          <!-- 邮箱输入 -->
          <el-form-item>
            <el-input
              v-model="codeForm.email"
              type="email"
              placeholder="请输入邮箱"
              :disabled="codeSent"
            />
          </el-form-item>

          <!-- 获取验证码按钮 -->
          <el-form-item v-if="!codeSent">
            <el-button
              type="info"
              @click="handleSendCode"
              :loading="sendingCode"
              style="width: 100%"
            >
              获取验证码
            </el-button>
          </el-form-item>

          <!-- 验证码输入 -->
          <el-form-item v-if="codeSent">
            <div style="display: flex; gap: 8px;">
              <el-input
                v-model="codeForm.code"
                placeholder="请输入验证码（6位）"
                maxlength="6"
                style="flex: 1"
              />
              <el-button
                type="info"
                @click="handleResendCode"
                :disabled="codeCountdown > 0"
              >
                {{ codeCountdown > 0 ? `${codeCountdown}s` : '重新获取' }}
              </el-button>
            </div>
          </el-form-item>

          <!-- 登录按钮 -->
          <el-button
            v-if="codeSent"
            type="primary"
            native-type="submit"
            :loading="codeLoading"
            style="width: 100%"
          >
            登录
          </el-button>
        </el-form>
      </div>

      <!-- 管理员登入 -->
      <el-form v-if="role === 'admin'" :model="adminForm" @submit.prevent="handleAdminLogin">
        <el-form-item>
          <el-input
            v-model="adminForm.username"
            placeholder="用户名"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="adminForm.password"
            type="password"
            placeholder="密码"
            show-password
          />
        </el-form-item>
        <el-button
          type="primary"
          native-type="submit"
          :loading="adminLoading"
          style="width: 100%"
        >
          登录
        </el-button>
      </el-form>

      <div style="margin-top: 12px; text-align: center; font-size: 12px;">
        <span v-if="role === 'seeker'">
          没有账号？<router-link to="/register" style="color: var(--brand-red); text-decoration: none;">立即注册</router-link>
        </span>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'
import { sendCode, loginApi } from '@/api/auth'

const role = ref('seeker')
const seekerMethod = ref('password')

// 密码登入
const passwordForm = reactive({ username: '', password: '' })
const passwordLoading = ref(false)

// 验证码登入
const codeForm = reactive({ email: '', code: '' })
const codeSent = ref(false)
const sendingCode = ref(false)
const codeLoading = ref(false)
const codeCountdown = ref(0)

// 管理员登入
const adminForm = reactive({ username: '', password: '' })
const adminLoading = ref(false)

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

// 倒计时逻辑
const startCountdown = () => {
  codeCountdown.value = 60
  const interval = setInterval(() => {
    codeCountdown.value--
    if (codeCountdown.value <= 0) clearInterval(interval)
  }, 1000)
}

// 发送验证码
async function handleSendCode() {
  if (!codeForm.email) {
    ElMessage.warning('请输入邮箱')
    return
  }

  sendingCode.value = true
  try {
    await sendCode(codeForm.email)
    ElMessage.success('验证码已发送到您的邮箱')
    codeSent.value = true
    startCountdown()
  } catch (err) {
    ElMessage.error(err.response?.data?.email?.[0] || err.response?.data?.error || '发送失败')
  } finally {
    sendingCode.value = false
  }
}

// 重新发送验证码
async function handleResendCode() {
  codeForm.code = ''
  await handleSendCode()
}

// 密码登入
async function handlePasswordLogin() {
  if (!passwordForm.username || !passwordForm.password) {
    ElMessage.warning('请输入邮箱/用户名和密码')
    return
  }

  passwordLoading.value = true
  try {
    const { data } = await loginApi({
      username: passwordForm.username,
      password: passwordForm.password,
    })
    localStorage.setItem('access_token', data.access)
    localStorage.setItem('refresh_token', data.refresh)
    await auth.fetchMe()

    ElMessage.success('登录成功')
    const redirect = route.query.redirect
    if (redirect) return router.push(redirect)
    router.push('/seeker/resume')
  } catch (err) {
    ElMessage.error(err.response?.data?.detail || err.response?.data?.username?.[0] || '登录失败')
  } finally {
    passwordLoading.value = false
  }
}

// 验证码登入
async function handleCodeLogin() {
  if (!codeForm.code || codeForm.code.length !== 6) {
    ElMessage.warning('请输入正确的6位验证码')
    return
  }

  codeLoading.value = true
  try {
    const { data } = await loginApi({
      email: codeForm.email,
      code: codeForm.code,
    })
    localStorage.setItem('access_token', data.access)
    localStorage.setItem('refresh_token', data.refresh)
    await auth.fetchMe()

    ElMessage.success('登录成功')
    const redirect = route.query.redirect
    if (redirect) return router.push(redirect)
    router.push('/seeker/resume')
  } catch (err) {
    ElMessage.error(err.response?.data?.code?.[0] || '登录失败')
  } finally {
    codeLoading.value = false
  }
}

// 管理员登入
async function handleAdminLogin() {
  if (!adminForm.username || !adminForm.password) {
    ElMessage.warning('请输入用户名和密码')
    return
  }

  adminLoading.value = true
  try {
    const { data } = await loginApi({
      username: adminForm.username,
      password: adminForm.password,
    })
    localStorage.setItem('access_token', data.access)
    localStorage.setItem('refresh_token', data.refresh)
    await auth.fetchMe()

    ElMessage.success('登录成功')
    const redirect = route.query.redirect
    if (redirect) return router.push(redirect)
    router.push('/admin/dashboard')
  } catch (err) {
    ElMessage.error(err.response?.data?.detail || '用户名或密码错误')
  } finally {
    adminLoading.value = false
  }
}
</script>

<style scoped>
.auth-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
}

.auth-card {
  width: 380px;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
  font-weight: 600;
}

.role-tabs {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
  background: #f5f7fa;
  padding: 4px;
  border-radius: 4px;
}

.role-tab {
  flex: 1;
  padding: 8px 16px;
  border: none;
  background: transparent;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
  border-radius: 3px;
  transition: all 0.2s;
}

.role-tab:hover {
  background: rgba(255, 255, 255, 0.5);
}

.role-tab.active {
  background: #fff;
  color: var(--brand-red);
  font-weight: 600;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

.method-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
  background: #f5f7fa;
  padding: 4px;
  border-radius: 4px;
}

.method-tab {
  flex: 1;
  padding: 6px 12px;
  border: none;
  background: transparent;
  cursor: pointer;
  font-size: 12px;
  color: #606266;
  border-radius: 3px;
  transition: all 0.2s;
}

.method-tab:hover {
  background: rgba(255, 255, 255, 0.5);
}

.method-tab.active {
  background: #fff;
  color: var(--brand-red);
  font-weight: 600;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}

.login-container {
  width: 100%;
}
</style>
