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

const userStore = useUserStore()

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

const formState = reactive({
  email: '',
})

const rules = {
  email: [
    { type: 'string' as const, required: true, message: '请输入邮箱', trigger: 'blur' as const },
    { type: 'email' as const, message: '请输入有效的邮箱地址', trigger: 'blur' as const },
  ],
}

onMounted(async () => {
  if (userStore.user) {
    formState.email = userStore.user.email || ''
  }
  try {
    await userStore.fetchCurrentUser()
    if (userStore.user) {
      formState.email = userStore.user.email || ''
    }
  } catch (error: unknown) {
    if (error instanceof ApiError) {
      message.error(error.message)
    }
  }
})

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true
    await userStore.updateProfile({ email: formState.email })
    message.success('个人信息更新成功')
  } 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="个人信息">
    <a-descriptions :column="1" bordered class="mb-6">
      <a-descriptions-item label="用户 ID">
        {{ userStore.user?.id }}
      </a-descriptions-item>
      <a-descriptions-item label="用户名">
        {{ userStore.user?.username }}
      </a-descriptions-item>
      <a-descriptions-item label="角色">
        {{ userStore.user?.role }}
      </a-descriptions-item>
    </a-descriptions>

    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      layout="vertical"
      @finish="handleSubmit"
    >
      <a-form-item label="邮箱" name="email">
        <a-input
          v-model:value="formState.email"
          placeholder="请输入邮箱地址"
        />
      </a-form-item>

      <a-form-item>
        <a-button
          type="primary"
          html-type="submit"
          :loading="loading"
        >
          保存修改
        </a-button>
      </a-form-item>
    </a-form>
  </a-card>

  <a-card title="API Key 管理" class="mt-4">
    <ApiKeyPanel />
  </a-card>
</template>
