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

import { confirmPasswordReset } from '../api/auth'
import { validateStrongPassword } from '../utils/password'

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

const token = ref(String(route.params.token || ''))
const valid = ref(true)
const invalidMessage = ref('')

const form = reactive({
  newPassword: '',
  confirmPassword: '',
})

const loading = ref(false)
const successText = ref('')

const redirectSeconds = ref(0)
let redirectTimer = null

function loadInitialState() {
  if (typeof window === 'undefined') return null
  const state = window.__APP_INITIAL_STATE__
  if (!state || typeof state !== 'object') return null
  window.__APP_INITIAL_STATE__ = null
  return state
}

const canSubmit = computed(() => Boolean(valid.value && token.value && !successText.value))

function goLogin() {
  router.push('/login')
}

function startRedirect() {
  redirectSeconds.value = 3
  redirectTimer = window.setInterval(() => {
    redirectSeconds.value -= 1
    if (redirectSeconds.value <= 0) {
      window.clearInterval(redirectTimer)
      redirectTimer = null
      window.location.href = '/login'
    }
  }, 1000)
}

async function onSubmit() {
  if (!canSubmit.value) return

  const newPassword = form.newPassword
  const confirmPassword = form.confirmPassword

  const check = validateStrongPassword(newPassword)
  if (!check.ok) {
    ElMessage.error(check.message)
    return
  }
  if (newPassword !== confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }

  loading.value = true
  try {
    await confirmPasswordReset({ token: token.value, new_password: newPassword })
    successText.value = '密码重置成功！3秒后跳转到登录页面...'
    ElMessage.success('密码重置成功')
    startRedirect()
  } catch (e) {
    const data = e?.response?.data
    ElMessage.error(data?.error || '重置失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  const init = loadInitialState()
  if (init?.page === 'reset_password') {
    token.value = String(init?.token || token.value || '')
    valid.value = Boolean(init?.valid)
    invalidMessage.value =
      init?.error_message || (valid.value ? '' : '重置链接无效或已过期，请重新申请密码重置')
  } else if (!token.value) {
    valid.value = false
    invalidMessage.value = '重置链接无效或已过期，请重新申请密码重置'
  }
})

onBeforeUnmount(() => {
  if (redirectTimer) window.clearInterval(redirectTimer)
})
</script>

<template>
  <div class="auth-wrap">
    <el-card shadow="never" class="auth-card" :body-style="{ padding: '22px' }">
      <div class="brand">
        <div class="brand-title">知识管理平台</div>
        <div class="brand-sub app-muted">重置密码</div>
      </div>

      <template v-if="!valid">
        <el-alert type="error" :closable="false" title="链接已失效" :description="invalidMessage" show-icon />
        <div class="actions">
          <el-button type="primary" @click="goLogin">返回登录</el-button>
        </div>
      </template>

      <template v-else>
        <el-alert
          v-if="successText"
          type="success"
          :closable="false"
          title="重置成功"
          :description="successText"
          show-icon
          class="alert"
        />

        <el-form label-position="top">
          <el-form-item label="新密码（至少8位且包含字母和数字）">
            <el-input
              v-model="form.newPassword"
              type="password"
              show-password
              placeholder="请输入新密码"
              autocomplete="new-password"
            />
          </el-form-item>
          <el-form-item label="确认密码">
            <el-input
              v-model="form.confirmPassword"
              type="password"
              show-password
              placeholder="请再次输入新密码"
              autocomplete="new-password"
              @keyup.enter="onSubmit"
            />
          </el-form-item>
        </el-form>

        <el-button type="primary" class="submit-btn" :loading="loading" :disabled="!canSubmit" @click="onSubmit">
          确认重置
        </el-button>

        <div class="actions">
          <el-button link type="primary" @click="goLogin">返回登录</el-button>
          <span v-if="redirectSeconds > 0" class="app-muted">{{ redirectSeconds }} 秒后自动跳转…</span>
        </div>
      </template>
    </el-card>
  </div>
</template>

<style scoped>
.auth-wrap {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.auth-card {
  width: 100%;
  max-width: 420px;
  border-radius: var(--app-radius);
  border: 1px solid var(--app-border);
  box-shadow: var(--app-shadow);
}

.brand {
  margin-bottom: 14px;
}

.brand-title {
  font-size: 18px;
  font-weight: 900;
}

.brand-sub {
  margin-top: 4px;
  font-size: 12px;
}

.alert {
  margin-bottom: 12px;
}

.submit-btn {
  width: 100%;
  margin-top: 4px;
}

.actions {
  margin-top: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  flex-wrap: wrap;
}
</style>
