<template>
  <div class="w-full animate-reveal max-w-3xl">
    <h1 class="text-2xl font-serif italic text-white mb-6">个人中心</h1>

    <div class="admin-card p-6 md:p-8 space-y-6">
      <form @submit.prevent="handleSaveProfile" class="space-y-5">
        <div class="flex items-center gap-4 pb-4 border-b border-white/5">
          <ImagePicker
            v-model="form.avatar"
            label="头像"
            variant="avatar"
            size="lg"
            placeholder="暂无头像"
            hint="支持本地上传或从素材库选择"
          />
          <div>
            <p class="text-white font-medium">{{ form.username }}</p>
            <p class="text-xs text-art-muted mt-1">用户名不可修改</p>
          </div>
        </div>

        <div class="form-group">
          <label>邮箱</label>
          <EmailAutocomplete
            name="email"
            label="邮箱"
            v-model="form.email"
            variant="admin"
            :user-lookup="true"
            required
          />
        </div>

        <div class="form-group">
          <label>个人介绍</label>
          <textarea v-model="form.bio" rows="4" class="admin-input resize-none" placeholder="介绍一下自己..." />
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div class="form-group">
            <label>手机号</label>
            <input v-model="form.phone" type="tel" class="admin-input" placeholder="选填" />
          </div>
          <div class="form-group">
            <label>微信号</label>
            <input v-model="form.wechat" type="text" class="admin-input" placeholder="选填" />
          </div>
        </div>

        <div class="form-group">
          <ImagePicker
            v-model="form.wechatQrcode"
            label="微信二维码"
            hint="上传二维码图片，悬浮展示给访客"
          />
        </div>

        <div class="flex flex-wrap gap-3 pt-2">
          <button type="submit" class="admin-btn-primary" :disabled="saving">
            {{ saving ? '保存中...' : '保存资料' }}
          </button>
          <button type="button" class="admin-btn-secondary" @click="openPreview">
            预览我的主页
          </button>
        </div>
      </form>
    </div>

    <!-- Password -->
    <div class="admin-card p-6 md:p-8 mt-6 space-y-4">
      <h2 class="text-lg font-medium text-white">修改密码</h2>
      <form @submit.prevent="handleChangePassword" class="space-y-4 max-w-md">
        <div class="form-group">
          <label>原密码</label>
          <input v-model="passwordForm.oldPassword" type="password" class="admin-input" required />
        </div>
        <div class="form-group">
          <label>新密码</label>
          <input v-model="passwordForm.newPassword" type="password" class="admin-input" required minlength="6" />
        </div>
        <button type="submit" class="admin-btn-secondary" :disabled="changingPassword">
          {{ changingPassword ? '提交中...' : '更新密码' }}
        </button>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useToast } from '../../composables/useToast'
import { useAuth } from '../../composables/useAuth'
import { useUserProfileModal } from '../../composables/useUserProfileModal'
import { getCurrentUser, updateCurrentUser, updateCurrentUserPassword } from '../../services/api'
import ImagePicker from '../../components/admin/ImagePicker.vue'
import EmailAutocomplete from '../../components/ui/EmailAutocomplete.vue'

const toast = useToast()
const { setUser, getUser } = useAuth()
const { openUserProfile } = useUserProfileModal()

const saving = ref(false)
const changingPassword = ref(false)
const userId = ref<number | null>(null)

const form = reactive({
  username: '',
  email: '',
  avatar: '',
  bio: '',
  phone: '',
  wechat: '',
  wechatQrcode: '',
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
})

const loadProfile = async () => {
  try {
    const user = await getCurrentUser()
    userId.value = user.id
    form.username = user.username
    form.email = user.email
    form.avatar = user.avatar || ''
    form.bio = user.bio || ''
    form.phone = user.phone || ''
    form.wechat = user.wechat || ''
    form.wechatQrcode = user.wechatQrcode || ''
    setUser(user)
  } catch (e) {
    console.error(e)
    toast.error('加载个人资料失败')
  }
}

const handleSaveProfile = async () => {
  saving.value = true
  try {
    const updated = await updateCurrentUser({
      email: form.email,
      avatar: form.avatar,
      bio: form.bio,
      phone: form.phone,
      wechat: form.wechat,
      wechatQrcode: form.wechatQrcode,
    })
    setUser(updated)
    toast.success('资料已保存')
  } catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '保存失败')
  } finally {
    saving.value = false
  }
}

const handleChangePassword = async () => {
  changingPassword.value = true
  try {
    await updateCurrentUserPassword(passwordForm.oldPassword, passwordForm.newPassword)
    passwordForm.oldPassword = ''
    passwordForm.newPassword = ''
    toast.success('密码已更新')
  } catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '密码更新失败')
  } finally {
    changingPassword.value = false
  }
}

const openPreview = () => {
  const id = userId.value || getUser()?.id
  if (id) openUserProfile(id)
}

onMounted(loadProfile)
</script>

<style scoped>
.form-group label {
  display: block;
  font-size: 0.75rem;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.5);
  margin-bottom: 0.5rem;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}
</style>
