<script setup lang="ts">
import { useUserStore } from '@/stores/user'
import { ApiError } from '@/types/api'

const userStore = useUserStore()
const router = useRouter()

const formRef = ref()
const loading = ref(false)

const formState = reactive({
  old_password: '',
  new_password: '',
  new_password_confirmation: '',
})

const rules = {
  old_password: [
    {
      type: 'string' as const,
      required: true,
      message: '请输入当前密码',
      trigger: 'blur' as const,
    },
  ],
  new_password: [
    {
      type: 'string' as const,
      required: true,
      message: '请输入新密码',
      trigger: 'blur' as const,
    },
    {
      type: 'string' as const,
      min: 6,
      message: '密码长度至少为 6 个字符',
      trigger: 'blur' as const,
    },
  ],
  new_password_confirmation: [
    {
      type: 'string' as const,
      required: true,
      message: '请确认新密码',
      trigger: 'blur' as const,
    },
    {
      validator: (_rule: unknown, value: string) => {
        if (value !== formState.new_password) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
      trigger: 'blur' as const,
    },
  ],
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true
    await userStore.changePassword({
      old_password: formState.old_password,
      new_password: formState.new_password,
      new_password_confirmation: formState.new_password_confirmation,
    })
    message.success('密码修改成功，请重新登录')
    setTimeout(() => {
      router.push('/login')
    }, 1500)
  } catch (error: unknown) {
    if (error && typeof error === 'object' && 'errorFields' in error) {
      return
    }
    if (error instanceof ApiError) {
      message.error(error.message)
      return
    }
    console.error('密码修改错误：', error)
    message.error('密码修改失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <a-card title="修改密码">
    <div class="max-w-md">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        layout="vertical"
        @finish="handleSubmit"
      >
        <a-form-item label="当前密码" name="old_password">
          <a-input-password
            v-model:value="formState.old_password"
            placeholder="请输入当前密码"
          />
        </a-form-item>

        <a-form-item label="新密码" name="new_password">
          <a-input-password
            v-model:value="formState.new_password"
            placeholder="请输入新密码（至少6位）"
          />
        </a-form-item>

        <a-form-item label="确认新密码" name="new_password_confirmation">
          <a-input-password
            v-model:value="formState.new_password_confirmation"
            placeholder="请再次输入新密码"
          />
        </a-form-item>

        <a-form-item>
          <a-button
            type="primary"
            html-type="submit"
            :loading="loading"
          >
            修改密码
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </a-card>
</template>
