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

import { logout, updateAdminPassword, updateAdminUsername } from '../api/admin'

const username = ref('')
const currentPassword = ref('')
const password = ref('')
const confirmPassword = ref('')
const submitting = ref(false)

function validateStrongPassword(value) {
  const text = String(value || '')
  if (text.length < 8) return { ok: false, message: '密码长度至少8位' }
  if (text.length > 128) return { ok: false, message: '密码长度不能超过128个字符' }
  if (!/[a-zA-Z]/.test(text) || !/\d/.test(text)) return { ok: false, message: '密码必须包含字母和数字' }
  return { ok: true, message: '' }
}

async function relogin() {
  try {
    await logout()
  } catch {
    // ignore
  } finally {
    window.location.href = '/yuyx'
  }
}

async function saveUsername() {
  const value = username.value.trim()
  if (!value) {
    ElMessage.error('请输入新用户名')
    return
  }

  try {
    await ElMessageBox.confirm(`确定将管理员用户名修改为「${value}」吗？修改后需要重新登录。`, '修改用户名', {
      confirmButtonText: '确认修改',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }

  submitting.value = true
  try {
    await updateAdminUsername(value)
    ElMessage.success('用户名修改成功，请重新登录')
    username.value = ''
    setTimeout(relogin, 1200)
  } catch {
    // handled by interceptor
  } finally {
    submitting.value = false
  }
}

async function savePassword() {
  const currentValue = currentPassword.value
  const value = password.value
  const confirmValue = confirmPassword.value

  if (!currentValue) {
    ElMessage.error('请输入当前密码')
    return
  }

  if (!value) {
    ElMessage.error('请输入新密码')
    return
  }

  const check = validateStrongPassword(value)
  if (!check.ok) {
    ElMessage.error(check.message)
    return
  }

  if (value !== confirmValue) {
    ElMessage.error('两次输入的新密码不一致')
    return
  }

  try {
    await ElMessageBox.confirm('确定修改管理员密码吗？修改后需要重新登录。', '修改密码', {
      confirmButtonText: '确认修改',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }

  submitting.value = true
  try {
    await updateAdminPassword({ currentPassword: currentValue, newPassword: value })
    ElMessage.success('密码修改成功，请重新登录')
    currentPassword.value = ''
    password.value = ''
    confirmPassword.value = ''
    setTimeout(relogin, 1200)
  } catch {
    // handled by interceptor
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <div class="page-stack">
    <div class="app-page-title">
      <h2>设置</h2>
      <span class="app-muted">管理员账号设置</span>
    </div>

    <el-card shadow="never" :body-style="{ padding: '16px' }" class="card">
      <h3 class="section-title">修改管理员用户名</h3>
      <el-form label-width="120px">
        <el-form-item label="新用户名">
          <el-input v-model="username" placeholder="输入新用户名" :disabled="submitting" />
        </el-form-item>
      </el-form>
      <el-button type="primary" :loading="submitting" @click="saveUsername">保存用户名</el-button>
    </el-card>

    <el-card shadow="never" :body-style="{ padding: '16px' }" class="card">
      <h3 class="section-title">修改管理员密码</h3>
      <el-form label-width="120px">
        <el-form-item label="当前密码">
          <el-input
            v-model="currentPassword"
            type="password"
            show-password
            placeholder="输入当前密码"
            :disabled="submitting"
          />
        </el-form-item>

        <el-form-item label="新密码">
          <el-input
            v-model="password"
            type="password"
            show-password
            placeholder="输入新密码"
            :disabled="submitting"
          />
        </el-form-item>

        <el-form-item label="确认新密码">
          <el-input
            v-model="confirmPassword"
            type="password"
            show-password
            placeholder="再次输入新密码"
            :disabled="submitting"
          />
        </el-form-item>
      </el-form>
      <el-button type="primary" :loading="submitting" @click="savePassword">保存密码</el-button>
      <div class="help">建议使用更强密码（至少8位且包含字母与数字）。</div>
    </el-card>
  </div>
</template>

<style scoped>
.page-stack {
  display: flex;
  flex-direction: column;
  gap: 14px;
  min-width: 0;
}

.card {
  border-radius: var(--app-radius);
  border: 1px solid var(--app-border);
  background: var(--app-card-bg);
  box-shadow: var(--app-shadow-soft);
}

.section-title {
  margin: 0 0 12px;
  font-size: 15px;
  font-weight: 800;
  letter-spacing: 0.2px;
}

.help {
  margin-top: 10px;
  font-size: 12px;
  color: var(--app-muted);
}
</style>
