<template>
  <AppShell>
    <div class="max-w-md space-y-4">
      <h2 class="text-lg font-semibold">
        修改密码
      </h2>
      <NForm>
        <NFormItem label="当前密码">
          <NInput
            v-model:value="oldPassword"
            type="password"
            show-password-on="click"
          />
        </NFormItem>
        <NFormItem label="新密码（至少 8 位）">
          <NInput
            v-model:value="newPassword"
            type="password"
            show-password-on="click"
          />
        </NFormItem>
        <NFormItem label="确认新密码">
          <NInput
            v-model:value="confirm"
            type="password"
            show-password-on="click"
          />
        </NFormItem>
      </NForm>
      <NButton
        type="primary"
        :loading="saving"
        :disabled="!canSubmit"
        @click="submit"
      >
        修改密码
      </NButton>
    </div>
  </AppShell>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { NButton, NForm, NFormItem, NInput, useMessage } from 'naive-ui'
import { useRouter } from 'vue-router'

import AppShell from '@/layouts/AppShell.vue'
import { authApi } from '@/api/auth'
import { useAuthStore } from '@/stores/auth'

const msg = useMessage()
const router = useRouter()
const auth = useAuthStore()

const oldPassword = ref('')
const newPassword = ref('')
const confirm = ref('')
const saving = ref(false)

const canSubmit = computed(
  () =>
    !!oldPassword.value &&
    newPassword.value.length >= 8 &&
    newPassword.value === confirm.value,
)

async function submit() {
  if (!canSubmit.value) return
  saving.value = true
  try {
    await authApi.changePassword(oldPassword.value, newPassword.value)
    msg.success('密码已修改，请重新登录')
    // 后端已撤销全部会话，本地清理并跳登录页。
    auth.clearSession()
    router.replace({ name: 'login' }).catch(() => {})
  } catch (e: unknown) {
    msg.error((e as Error).message || '修改失败')
  } finally {
    saving.value = false
  }
}
</script>
