<template>
  <div class="profile-container">
    <div class="page-header">
      <h1 class="page-title">个人信息</h1>
    </div>

    <div class="profile-content">
      <!-- 基本信息 -->
      <div class="info-section card">
        <div class="section-header">
          <h2 class="section-title">基本信息</h2>
          <el-button v-if="!isEditing" link type="primary" @click="handleEdit">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
        </div>

        <div class="info-content">
          <div class="avatar-section">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :disabled="!isEditing"
              @change="handleAvatarChange"
            >
              <el-avatar :size="120" :src="userInfo.avatar">
                <el-icon :size="60"><UserFilled /></el-icon>
              </el-avatar>
              <div v-if="isEditing" class="avatar-overlay">
                <el-icon :size="24"><Camera /></el-icon>
              </div>
            </el-upload>
            <div class="user-name">{{ userInfo.name }}</div>
            <div class="user-role">{{ userInfo.role }}</div>
          </div>

          <el-form
            ref="formRef"
            :model="userInfo"
            :rules="rules"
            label-width="100px"
            :disabled="!isEditing"
            class="info-form"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userInfo.username" />
            </el-form-item>
            <el-form-item label="真实姓名" prop="name">
              <el-input v-model="userInfo.name" />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="userInfo.gender">
                <el-radio label="male">男</el-radio>
                <el-radio label="female">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userInfo.phone" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userInfo.email" />
            </el-form-item>
            <el-form-item label="学校" prop="school">
              <el-input v-model="userInfo.school" />
            </el-form-item>
            <el-form-item label="专业" prop="major">
              <el-input v-model="userInfo.major" />
            </el-form-item>
            <el-form-item label="个人简介" prop="bio">
              <el-input
                v-model="userInfo.bio"
                type="textarea"
                :rows="3"
                placeholder="介绍一下自己吧"
              />
            </el-form-item>
          </el-form>

          <div v-if="isEditing" class="form-actions">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSave">保存修改</el-button>
          </div>
        </div>
      </div>

      <!-- 账号安全 -->
      <div class="security-section card">
        <h2 class="section-title">账号安全</h2>
        <div class="security-item">
          <div class="security-info">
            <div class="security-label">登录密码</div>
            <div class="security-desc">定期修改密码可以提高账号安全性</div>
          </div>
          <el-button type="primary" @click="handleChangePassword">
            修改密码
          </el-button>
        </div>
      </div>

      <!-- 学习统计 -->
      <div class="stats-section card">
        <h2 class="section-title">学习统计</h2>
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: rgba(102, 126, 234, 0.1)">
              <el-icon :size="24" color="#667eea"><Calendar /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.learningDays }}</div>
              <div class="stat-label">学习天数</div>
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-icon" style="background-color: rgba(103, 194, 58, 0.1)">
              <el-icon :size="24" color="#67c23a"><Clock /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.totalHours }}</div>
              <div class="stat-label">学习时长(小时)</div>
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-icon" style="background-color: rgba(230, 162, 60, 0.1)">
              <el-icon :size="24" color="#e6a23c"><Document /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.practiceQuestions }}</div>
              <div class="stat-label">练习题数</div>
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-icon" style="background-color: rgba(245, 108, 108, 0.1)">
              <el-icon :size="24" color="#f56c6c"><Trophy /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.averageScore }}</div>
              <div class="stat-label">平均成绩</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 成就徽章 -->
      <div class="achievement-section card">
        <h2 class="section-title">成就徽章</h2>
        <div class="achievement-grid">
          <div class="achievement-item" v-for="badge in achievements" :key="badge.id">
            <div class="badge-icon" :class="{ locked: !badge.unlocked }">
              <el-icon :size="32">
                <component :is="badge.icon" />
              </el-icon>
            </div>
            <div class="badge-name">{{ badge.name }}</div>
            <div class="badge-desc">{{ badge.description }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getCurrentUserProfile, updateCurrentUserProfile, getCurrentUserStatistics } from '@/api/user'
import type { ApiResponse } from '@/api/config'

const formRef = ref<FormInstance>()
const isEditing = ref(false)
const router = useRouter()

// 用户信息（与后端字段对齐）
const userInfo = reactive({
  id: 0,
  username: '',
  name: '',
  gender: 'male',
  phone: '',
  email: '',
  school: '',
  major: '',
  bio: '',
  avatar: '',
  role: ''
})

/**
 * 加载当前用户信息
 * 从后端 GET /api/v1/users/me 拉取真实数据并填充表单
 */
async function loadUserProfile(): Promise<void> {
  try {
    const res = await getCurrentUserProfile()
    // 后端统一响应结构 { code, message, data }
    const data = (res as ApiResponse<any>).data
    if (!data) {
      ElMessage.error('获取个人信息失败：数据为空')
      return
    }
    // 兼容后端字段（full_name -> name, avatar_url -> avatar）
    userInfo.id = data.id ?? 0
    userInfo.username = data.username ?? ''
    userInfo.name = data.full_name ?? data.name ?? ''
    userInfo.phone = data.phone ?? ''
    userInfo.email = data.email ?? ''
    userInfo.bio = data.bio ?? ''
    userInfo.avatar = data.avatar_url ?? data.avatar ?? ''
    userInfo.role = data.role ?? ''
    userInfo.gender = data.gender ?? 'male'  // 加载性别字段，默认 male
    // 加载学校和专业字段
    userInfo.school = data.school ?? ''
    userInfo.major = data.major ?? ''
  } catch (err: any) {
    ElMessage.error(err?.message || '获取个人信息失败')
  }
}

// 表单验证规则
const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
})

// 成就徽章
const achievements = ref([
  {
    id: 1,
    name: '初学者',
    description: '完成第一次考试',
    icon: 'Star',
    unlocked: true
  },
  {
    id: 2,
    name: '勤奋学习',
    description: '连续学习7天',
    icon: 'Calendar',
    unlocked: true
  },
  {
    id: 3,
    name: '题海战术',
    description: '累计练习1000题',
    icon: 'Files',
    unlocked: true
  },
  {
    id: 4,
    name: '学霸',
    description: '连续10次考试90分以上',
    icon: 'Trophy',
    unlocked: false
  },
  {
    id: 5,
    name: '完美主义',
    description: '单次考试满分',
    icon: 'CircleCheck',
    unlocked: true
  },
  {
    id: 6,
    name: '持之以恒',
    description: '连续学习30天',
    icon: 'Flag',
    unlocked: false
  }
])

// 学习统计（真实数据）
const stats = reactive({
  learningDays: 0,
  totalHours: 0,
  practiceQuestions: 0,
  averageScore: 0
})

/**
 * 加载当前用户学习统计
 */
async function loadUserStatistics(): Promise<void> {
  try {
    const res = await getCurrentUserStatistics()
    const data = (res as ApiResponse<any>).data
    if (data) {
      stats.learningDays = data.learningDays ?? 0
      stats.totalHours = data.totalHours ?? 0
      stats.practiceQuestions = data.practiceQuestions ?? 0
      stats.averageScore = data.averageScore ?? 0
    }
  } catch (err: any) {
    // 静默失败，保留占位
  }
}

/**
 * 编辑信息
 * 进入编辑态
 */
function handleEdit(): void {
  isEditing.value = true
}

/**
 * 取消编辑
 * 退出编辑态并重置表单至服务器状态
 */
async function handleCancel(): Promise<void> {
  isEditing.value = false
  formRef.value?.resetFields()
  await loadUserProfile()
}

/**
 * 保存修改
 * 提交 PUT /api/v1/users/me，只传后端可接受字段
 */
async function handleSave(): Promise<void> {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      const payload = {
        // 与 app/schemas/user.py::UserUpdate 对齐
        email: userInfo.email || undefined,
        phone: userInfo.phone || undefined,
        full_name: userInfo.name || undefined,
        avatar_url: userInfo.avatar || undefined,
        bio: userInfo.bio || undefined,
        gender: userInfo.gender || undefined,
        school: userInfo.school || undefined,
        major: userInfo.major || undefined
      }
      await updateCurrentUserProfile(payload)
      ElMessage.success('个人信息修改成功')
      isEditing.value = false
      await loadUserProfile()
    } catch (err: any) {
      ElMessage.error(err?.message || '保存失败')
    }
  })
}

/**
 * 头像更改
 * 目前仅前端提示，后续可改为实际上传后设置 avatar_url
 */
function handleAvatarChange(_file: any): void {
  ElMessage.success('头像更新成功（示例）')
}

/**
 * 跳转到修改密码页面
 */
function handleChangePassword(): void {
  router.push('/user/change-password')
}

onMounted(() => {
  loadUserProfile()
  loadUserStatistics()
})
</script>

<style lang="scss" scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;

  .page-header {
    margin-bottom: 24px;

    .page-title {
      font-size: 24px;
      font-weight: 600;
      color: #333;
    }
  }

  .profile-content {
    display: grid;
    gap: 24px;

    .info-section {
      padding: 24px;

      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
      }

      .section-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
      }

      .info-content {
        display: flex;
        gap: 48px;

        .avatar-section {
          text-align: center;

          .avatar-uploader {
            position: relative;
            display: inline-block;
            cursor: pointer;

            .el-avatar {
              border: 4px solid #f0f2f5;
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            }

            .avatar-overlay {
              position: absolute;
              top: 0;
              left: 0;
              width: 100%;
              height: 100%;
              background: rgba(0, 0, 0, 0.5);
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              opacity: 0;
              transition: opacity 0.3s;
              color: white;

              &:hover {
                opacity: 1;
              }
            }
          }

          .user-name {
            font-size: 20px;
            font-weight: 600;
            color: #333;
            margin-top: 16px;
          }

          .user-role {
            font-size: 14px;
            color: #666;
            margin-top: 8px;
          }
        }

        .info-form {
          flex: 1;
          max-width: 500px;
        }

        .form-actions {
          display: flex;
          justify-content: flex-end;
          gap: 12px;
          margin-top: 24px;

          .el-button--primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
          }
        }
      }
    }

    .stats-section {
      padding: 24px;

      .section-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        margin-bottom: 24px;
      }

      .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 24px;

        .stat-item {
          display: flex;
          align-items: center;
          gap: 16px;

          .stat-icon {
            width: 56px;
            height: 56px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
          }

          .stat-content {
            .stat-value {
              font-size: 24px;
              font-weight: 600;
              color: #333;
            }

            .stat-label {
              font-size: 14px;
              color: #666;
              margin-top: 4px;
            }
          }
        }
      }
    }

    .security-section {
      padding: 24px;

      .section-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        margin-bottom: 24px;
      }

      .security-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 0;

        .security-info {
          flex: 1;

          .security-label {
            font-size: 14px;
            color: #333;
            margin-bottom: 4px;
            font-weight: 500;
          }

          .security-desc {
            font-size: 12px;
            color: #909399;
          }
        }

        .el-button--primary {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border: none;
        }
      }
    }

    .achievement-section {
      padding: 24px;

      .section-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        margin-bottom: 24px;
      }

      .achievement-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 24px;

        .achievement-item {
          text-align: center;
          padding: 20px;
          border-radius: 12px;
          background: #f5f7fa;
          transition: all 0.3s ease;

          &:hover {
            transform: translateY(-4px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          }

          .badge-icon {
            width: 64px;
            height: 64px;
            margin: 0 auto 12px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;

            &.locked {
              background: #c0c4cc;
              filter: grayscale(1);
            }
          }

          .badge-name {
            font-size: 14px;
            font-weight: 600;
            color: #333;
            margin-bottom: 4px;
          }

          .badge-desc {
            font-size: 12px;
            color: #666;
          }
        }
      }
    }
  }
}

// 响应式
@media (max-width: 768px) {
  .profile-container {
    .info-content {
      flex-direction: column !important;
      gap: 24px !important;

      .avatar-section {
        margin-bottom: 24px;
      }
    }

    .stats-grid {
      grid-template-columns: repeat(2, 1fr) !important;
    }

    .achievement-grid {
      grid-template-columns: repeat(2, 1fr) !important;
    }
  }
}
</style>