<template>
  <div class="auth-page">
    <el-card class="auth-card">
      <h2>重置密码</h2>

      <el-form @submit.prevent="handleResetPassword">
        <!-- 第一步：邮箱验证 -->
        <div v-if="step === 1">
          <el-form-item>
            <el-input
              v-model="form.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="form.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"
            @click="goToStep2"
            style="width: 100%"
          >
            下一步
          </el-button>
        </div>

        <!-- 第二步：重置密码 -->
        <div v-if="step === 2">
          <div style="margin-bottom: 16px; padding: 8px 12px; background: #f0f9ff; border-radius: 4px; color: #606266; font-size: 12px;">
            邮箱：<span style="font-weight: 600;">{{ form.email }}</span>
          </div>

          <el-form-item>
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入新密码（至少6位）"
              show-password
            />
          </el-form-item>

          <el-form-item>
            <el-input
              v-model="form.passwordConfirm"
              type="password"
              placeholder="请确认新密码"
              show-password
            />
          </el-form-item>

          <el-button
            type="primary"
            native-type="submit"
            :loading="resetLoading"
            style="width: 100%"
          >
            重置密码
          </el-button>

          <el-button
            @click="goBackToStep1"
            style="width: 100%; margin-top: 8px;"
          >
            上一步
          </el-button>
        </div>
      </el-form>

      <div style="margin-top: 12px; text-align: center; font-size: 12px;">
        <router-link to="/login" style="color: var(--brand-red); text-decoration: none;">返回登录</router-link>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const step = ref(1)
const form = reactive({
  email: '',
  code: '',
  password: '',
  passwordConfirm: '',
})

const codeSent = ref(false)
const sendingCode = ref(false)
const resetLoading = ref(false)
const codeCountdown = ref(0)

const router = useRouter()

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

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

  sendingCode.value = true
  try {
    const response = await fetch('/api/auth/reset-password/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: form.email }),
    })

    if (!response.ok) {
      const data = await response.json()
      ElMessage.error(data.email?.[0] || '发送失败')
      return
    }

    ElMessage.success('验证码已发送到您的邮箱')
    codeSent.value = true
    startCountdown()
  } catch (err) {
    ElMessage.error('发送失败，请稍后重试')
  } finally {
    sendingCode.value = false
  }
}

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

// 下一步
function goToStep2() {
  if (!form.code || form.code.length !== 6) {
    ElMessage.warning('请输入正确的6位验证码')
    return
  }
  step.value = 2
}

// 上一步
function goBackToStep1() {
  step.value = 1
}

// 重置密码
async function handleResetPassword() {
  if (!form.password || form.password.length < 6) {
    ElMessage.warning('请输入至少6位密码')
    return
  }
  if (form.password !== form.passwordConfirm) {
    ElMessage.warning('两次输入的密码不一致')
    return
  }

  resetLoading.value = true
  try {
    const response = await fetch('/api/auth/confirm-reset-password/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email: form.email,
        code: form.code,
        new_password: form.password,
      }),
    })

    if (!response.ok) {
      const data = await response.json()
      const errorMsg = data.code?.[0] || data.new_password?.[0] || '重置失败'
      ElMessage.error(errorMsg)
      return
    }

    ElMessage.success('密码重置成功，请使用新密码登入')
    router.push('/login')
  } catch (err) {
    ElMessage.error('密码重置失败，请稍后重试')
  } finally {
    resetLoading.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: 24px;
  color: #333;
  font-weight: 600;
}
</style>
