<template>
  <div class="settings-page min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
    <!-- App Header -->
    <header class="fixed top-0 left-0 right-0 z-40 bg-white/90 backdrop-blur-md border-b border-gray-200/80">
      <div class="container mx-auto px-4 h-16 flex items-center justify-between relative">
        <button
          @click="$router.go(-1)"
          class="text-gray-600 hover:text-blue-600 transition-colors"
        >
          <i data-lucide="chevron-left" class="w-6 h-6"></i>
        </button>
        <h1 class="text-lg font-semibold text-gray-900 absolute left-1/2 -translate-x-1/2">个人资料</h1>
        <router-link to="/" class="text-gray-600 hover:text-blue-600 transition-colors">
          <i data-lucide="home" class="w-6 h-6"></i>
        </router-link>
      </div>
    </header>

    <main class="pt-20 pb-8 min-h-screen">
      <div class="container mx-auto px-4 max-w-4xl">
        <!-- 加载状态 -->
        <div v-if="loading" class="text-center py-12">
          <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
          <p class="mt-2 text-gray-600">加载中...</p>
        </div>

        <!-- 个人资料表单 -->
        <div v-else class="space-y-8">
          <!-- 基本信息 -->
          <div class="bg-white rounded-2xl shadow-lg p-8">
            <div class="flex items-center mb-8">
              <i data-lucide="user" class="w-6 h-6 text-blue-600 mr-3"></i>
              <h2 class="text-2xl font-bold text-gray-900">基本信息</h2>
            </div>

            <form @submit.prevent="saveProfile" class="space-y-6">
              <!-- 头像区域 -->
              <div class="flex items-center space-x-6 pb-6 border-b border-gray-200">
                <div class="relative">
                  <img
                    :src="currentAvatar"
                    alt="用户头像"
                    class="w-24 h-24 rounded-full object-cover border-4 border-gray-200 shadow-lg"
                  >
                  <button
                    type="button"
                    @click="triggerAvatarUpload"
                    class="absolute bottom-0 right-0 bg-blue-600 text-white p-2 rounded-full hover:bg-blue-700 transition-colors shadow-lg"
                  >
                    <i data-lucide="camera" class="w-4 h-4"></i>
                  </button>
                  <input
                    ref="avatarInput"
                    type="file"
                    accept="image/*"
                    @change="handleAvatarUpload"
                    class="hidden"
                  >
                </div>
                <div>
                  <h3 class="text-lg font-semibold text-gray-900">{{ displayNickname }}</h3>
                  <p class="text-gray-600">{{ displayEmail }}</p>
                  <p class="text-sm text-gray-500 mt-1">会员等级：{{ profile.memberLevel || 'free' }}</p>
                </div>
              </div>

              <!-- 表单字段 -->
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- 昵称 -->
                <div>
                  <label for="nickname" class="block text-sm font-medium text-gray-700 mb-2">昵称</label>
                  <input
                    id="nickname"
                    v-model="profile.nickname"
                    type="text"
                    placeholder="请输入昵称"
                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
                  >
                </div>

                <!-- 用户名 -->
                <div>
                  <label for="username" class="block text-sm font-medium text-gray-700 mb-2">用户名</label>
                  <input
                    id="username"
                    v-model="profile.username"
                    type="text"
                    disabled
                    class="w-full px-4 py-3 border border-gray-300 rounded-lg bg-gray-100 text-gray-500 cursor-not-allowed"
                  >
                </div>

                <!-- 邮箱 -->
                <div>
                  <label for="email" class="block text-sm font-medium text-gray-700 mb-2">邮箱</label>
                  <div class="relative">
                    <input
                      id="email"
                      v-model="profile.email"
                      type="email"
                      placeholder="请输入邮箱"
                      class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
                    >
                    <button
                      v-if="profile.email && !profile.isVerified"
                      type="button"
                      @click="sendEmailVerification"
                      class="absolute right-2 top-1/2 -translate-y-1/2 text-xs bg-orange-100 text-orange-600 px-2 py-1 rounded"
                    >
                      验证
                    </button>
                    <span
                      v-else-if="profile.isVerified"
                      class="absolute right-2 top-1/2 -translate-y-1/2 text-xs bg-green-100 text-green-600 px-2 py-1 rounded"
                    >
                      已验证
                    </span>
                  </div>
                </div>

                <!-- 手机号 -->
                <div>
                  <label for="phone" class="block text-sm font-medium text-gray-700 mb-2">手机号</label>
                  <input
                    id="phone"
                    v-model="profile.phone"
                    type="tel"
                    placeholder="请输入手机号"
                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
                  >
                </div>

                <!-- 生日 -->
                <div>
                  <label for="birthDate" class="block text-sm font-medium text-gray-700 mb-2">生日</label>
                  <input
                    id="birthDate"
                    v-model="profile.birthDate"
                    type="date"
                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
                  >
                </div>

                <!-- 所在地 -->
                <div>
                  <label for="location" class="block text-sm font-medium text-gray-700 mb-2">所在地</label>
                  <input
                    id="location"
                    v-model="profile.location"
                    type="text"
                    placeholder="请输入所在地"
                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
                  >
                </div>
              </div>

              <!-- 个人简介 -->
              <div>
                <label for="bio" class="block text-sm font-medium text-gray-700 mb-2">个人简介</label>
                <textarea
                  id="bio"
                  v-model="profile.bio"
                  rows="4"
                  placeholder="介绍一下自己吧..."
                  class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors resize-none"
                ></textarea>
              </div>

              <!-- 保存按钮 -->
              <div class="flex justify-end pt-6 border-t border-gray-200">
                <button
                  type="submit"
                  :disabled="saving"
                  class="bg-blue-600 text-white px-8 py-3 rounded-lg font-semibold hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {{ saving ? '保存中...' : '保存更改' }}
                </button>
              </div>
            </form>
          </div>

          <!-- 成长数据 -->
          <div class="bg-white rounded-2xl shadow-lg p-8">
            <div class="flex items-center mb-8">
              <i data-lucide="trending-up" class="w-6 h-6 text-green-600 mr-3"></i>
              <h2 class="text-2xl font-bold text-gray-900">成长数据</h2>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              <!-- 自我感知 -->
              <div class="bg-gradient-to-br from-blue-50 to-blue-100 p-6 rounded-xl">
                <div class="flex items-center justify-between mb-4">
                  <h3 class="font-semibold text-gray-900">自我感知</h3>
                  <i data-lucide="brain" class="w-5 h-5 text-blue-600"></i>
                </div>
                <div class="text-3xl font-bold text-blue-600 mb-2">
                  {{ profile.selfAwareness || 50 }}
                </div>
                <div class="w-full bg-blue-200 rounded-full h-2">
                  <div
                    class="bg-blue-600 h-2 rounded-full transition-all duration-500"
                    :style="{ width: `${(profile.selfAwareness || 50)}%` }"
                  ></div>
                </div>
              </div>

              <!-- 情绪韧性 -->
              <div class="bg-gradient-to-br from-green-50 to-green-100 p-6 rounded-xl">
                <div class="flex items-center justify-between mb-4">
                  <h3 class="font-semibold text-gray-900">情绪韧性</h3>
                  <i data-lucide="shield" class="w-5 h-5 text-green-600"></i>
                </div>
                <div class="text-3xl font-bold text-green-600 mb-2">
                  {{ profile.emotionalResilience || 50 }}
                </div>
                <div class="w-full bg-green-200 rounded-full h-2">
                  <div
                    class="bg-green-600 h-2 rounded-full transition-all duration-500"
                    :style="{ width: `${(profile.emotionalResilience || 50)}%` }"
                  ></div>
                </div>
              </div>

              <!-- 行动力 -->
              <div class="bg-gradient-to-br from-orange-50 to-orange-100 p-6 rounded-xl">
                <div class="flex items-center justify-between mb-4">
                  <h3 class="font-semibold text-gray-900">行动力</h3>
                  <i data-lucide="zap" class="w-5 h-5 text-orange-600"></i>
                </div>
                <div class="text-3xl font-bold text-orange-600 mb-2">
                  {{ profile.actionPower || 50 }}
                </div>
                <div class="w-full bg-orange-200 rounded-full h-2">
                  <div
                    class="bg-orange-600 h-2 rounded-full transition-all duration-500"
                    :style="{ width: `${(profile.actionPower || 50)}%` }"
                  ></div>
                </div>
              </div>

              <!-- 共情力 -->
              <div class="bg-gradient-to-br from-purple-50 to-purple-100 p-6 rounded-xl">
                <div class="flex items-center justify-between mb-4">
                  <h3 class="font-semibold text-gray-900">共情力</h3>
                  <i data-lucide="heart" class="w-5 h-5 text-purple-600"></i>
                </div>
                <div class="text-3xl font-bold text-purple-600 mb-2">
                  {{ profile.empathy || 50 }}
                </div>
                <div class="w-full bg-purple-200 rounded-full h-2">
                  <div
                    class="bg-purple-600 h-2 rounded-full transition-all duration-500"
                    :style="{ width: `${(profile.empathy || 50)}%` }"
                  ></div>
                </div>
              </div>

              <!-- 生活热度 -->
              <div class="bg-gradient-to-br from-red-50 to-red-100 p-6 rounded-xl">
                <div class="flex items-center justify-between mb-4">
                  <h3 class="font-semibold text-gray-900">生活热度</h3>
                  <i data-lucide="flame" class="w-5 h-5 text-red-600"></i>
                </div>
                <div class="text-3xl font-bold text-red-600 mb-2">
                  {{ profile.lifeEnthusiasm || 50 }}
                </div>
                <div class="w-full bg-red-200 rounded-full h-2">
                  <div
                    class="bg-red-600 h-2 rounded-full transition-all duration-500"
                    :style="{ width: `${(profile.lifeEnthusiasm || 50)}%` }"
                  ></div>
                </div>
              </div>

              <!-- 使用天数 -->
              <div class="bg-gradient-to-br from-indigo-50 to-indigo-100 p-6 rounded-xl">
                <div class="flex items-center justify-between mb-4">
                  <h3 class="font-semibold text-gray-900">使用天数</h3>
                  <i data-lucide="calendar" class="w-5 h-5 text-indigo-600"></i>
                </div>
                <div class="text-3xl font-bold text-indigo-600 mb-2">
                  {{ profile.totalDays || 0 }}
                </div>
                <p class="text-sm text-gray-600">天</p>
              </div>
            </div>
          </div>

        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import UserService, { type UserProfile, type UserProfileUpdateRequest } from '@/services/user'
import { useAuthStore } from '@/stores/auth'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const avatarInput = ref<HTMLInputElement>()

// 默认头像
const defaultAvatar = 'https://r2.flowith.net/files/o/1752574572161-kaikai_character_energetic_animation_index_2@1024x1024.png'

// 计算属性：当前显示的头像
const currentAvatar = computed(() => {
  return profile.value.avatar || defaultAvatar
})

// 计算属性：用户昵称
const displayNickname = computed(() => {
  return profile.value.nickname || profile.value.username || '未设置昵称'
})

// 计算属性：用户邮箱
const displayEmail = computed(() => {
  return profile.value.email || '未设置邮箱'
})

// 用户资料
const profile = ref<UserProfile>({
  id: '',
  account: '',
  username: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: '',
  birthDate: '',
  location: '',
  bio: '',
  memberLevel: 'free',
  totalDays: 0,
  selfAwareness: 50,
  emotionalResilience: 50,
  actionPower: 50,
  empathy: 50,
  lifeEnthusiasm: 50,
  status: 1,
  isVerified: 0,
  createTime: '',
  updateTime: '',
  lastActiveTime: ''
})

// 加载用户资料
const loadUserProfile = async () => {
  try {
    loading.value = true
    console.log('🔧 开始加载用户资料...')
    
    const userProfile = await UserService.getCurrentUserProfile()
    console.log('🔧 API返回的用户资料:', userProfile)
    
    // 合并API返回的数据和默认值，确保所有字段都有值
    profile.value = {
      id: userProfile?.id || '',
      account: userProfile?.account || '',
      username: userProfile?.username || '',
      nickname: userProfile?.nickname || userProfile?.username || '未设置昵称',
      email: userProfile?.email || '',
      phone: userProfile?.phone || '',
      avatar: userProfile?.avatar || '',
      birthDate: userProfile?.birthDate || '',
      location: userProfile?.location || '',
      bio: userProfile?.bio || '',
      memberLevel: userProfile?.memberLevel || 'free',
      totalDays: userProfile?.totalDays || 0,
      selfAwareness: userProfile?.selfAwareness || 50,
      emotionalResilience: userProfile?.emotionalResilience || 50,
      actionPower: userProfile?.actionPower || 50,
      empathy: userProfile?.empathy || 50,
      lifeEnthusiasm: userProfile?.lifeEnthusiasm || 50,
      status: userProfile?.status || 1,
      isVerified: userProfile?.isVerified || 0,
      createTime: userProfile?.createTime || '',
      updateTime: userProfile?.updateTime || '',
      lastActiveTime: userProfile?.lastActiveTime || ''
    }
    
    console.log('🔧 处理后的用户资料:', profile.value)
  } catch (error) {
    console.error('🔧 加载用户资料失败:', error)
    ElMessage.error('加载用户资料失败，请稍后重试')
    
    // 如果加载失败，至少显示基本信息
    const authStore = useAuthStore()
    if (authStore.userInfo) {
      profile.value = {
        ...profile.value,
        id: authStore.userInfo.id || '',
        account: authStore.userInfo.account || '',
        username: authStore.userInfo.username || '',
        nickname: authStore.userInfo.nickname || authStore.userInfo.username || '未设置昵称',
        email: authStore.userInfo.email || '',
        phone: authStore.userInfo.phone || '',
        avatar: authStore.userInfo.avatar || '',
        status: authStore.userInfo.status || 1
      }
    }
  } finally {
    loading.value = false
  }
}

// 触发头像上传
const triggerAvatarUpload = () => {
  avatarInput.value?.click()
}

// 处理头像上传
const handleAvatarUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]

  if (!file) return

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }

  // 验证文件大小 (5MB)
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB')
    return
  }

  try {
    const avatarUrl = await UserService.uploadAvatar(file)
    profile.value.avatar = avatarUrl
    ElMessage.success('头像上传成功')
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  }
}

// 保存个人资料
const saveProfile = async () => {
  try {
    saving.value = true

    const updateData: UserProfileUpdateRequest = {
      nickname: profile.value.nickname,
      email: profile.value.email,
      phone: profile.value.phone,
      avatar: profile.value.avatar,
      birthDate: profile.value.birthDate,
      location: profile.value.location,
      bio: profile.value.bio
    }

    const updatedProfile = await UserService.updateCurrentUserProfile(updateData)
    profile.value = updatedProfile
    ElMessage.success('个人资料保存成功')
  } catch (error) {
    console.error('保存个人资料失败:', error)
    ElMessage.error('保存个人资料失败')
  } finally {
    saving.value = false
  }
}

// 发送邮箱验证
const sendEmailVerification = async () => {
  try {
    await UserService.sendEmailVerificationCode()
    ElMessage.success('验证码已发送到您的邮箱')
  } catch (error) {
    console.error('发送邮箱验证失败:', error)
    ElMessage.error('发送邮箱验证失败')
  }
}

// 生命周期
onMounted(async () => {
  // 添加认证状态调试信息
  const authStore = useAuthStore()
  console.log('🔧 Settings页面加载，认证状态:', {
    isLoggedIn: authStore.isLoggedIn,
    hasToken: !!authStore.accessToken,
    hasUserInfo: !!authStore.userInfo,
    userId: authStore.userId,
    username: authStore.username
  })

  // 加载用户资料
  await loadUserProfile()

  // 初始化Lucide图标
  if (window.lucide) {
    window.lucide.createIcons()
  }

  // 延迟初始化图标
  setTimeout(() => {
    if (window.lucide) {
      window.lucide.createIcons()
    }
  }, 100)
})
</script>

<style scoped>
.settings-page {
  font-family: 'Inter', 'Noto Sans SC', sans-serif;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 输入框焦点效果 */
input:focus,
textarea:focus {
  outline: none;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* 按钮悬停效果 */
button:hover {
  transform: translateY(-1px);
}

button:active {
  transform: translateY(0);
}

/* 头像悬停效果 */
.relative:hover .absolute {
  opacity: 1;
}

/* 成长数据卡片动画 */
.bg-gradient-to-br {
  transition: all 0.3s ease;
}

.bg-gradient-to-br:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

/* 进度条动画 */
.h-2 {
  transition: width 0.8s ease-in-out;
}

/* 表单验证样式 */
.border-red-300 {
  border-color: #fca5a5;
}

.text-red-600 {
  color: #dc2626;
}

/* 加载动画 */
@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .container {
    padding-left: 1rem;
    padding-right: 1rem;
  }
}
</style>