<template>
  <div class="profile">
    <div class="container">
      <div class="profile-container">
        <!-- 侧边栏 -->
        <div class="sidebar">
          <n-menu
            v-model:value="activeTab"
            :options="menuOptions"
            @update:value="handleMenuSelect"
          />
        </div>
        
        <!-- 主要内容 -->
        <div class="main-content">
          <!-- 个人信息 -->
          <div v-if="activeTab === 'info'" class="profile-section">
            <h2>个人信息</h2>
            <n-form
              ref="formRef"
              :model="profileForm"
              :rules="rules"
              label-placement="left"
              label-width="100px"
            >
              <n-form-item label="头像">
                <div class="avatar-section">
                  <SafeAvatar
                    :src="userStore.user?.avatar"
                    :name="userStore.user?.username"
                    :size="100"
                  />
                  <n-button size="small" @click="handleAvatarUpload">
                    更换头像
                  </n-button>
                </div>
              </n-form-item>
              
              <n-form-item path="username" label="用户名">
                <n-input v-model:value="profileForm.username" />
              </n-form-item>
              
              <n-form-item path="email" label="邮箱">
                <n-input v-model:value="profileForm.email" disabled />
              </n-form-item>
              
              <n-form-item>
                <n-button
                  type="primary"
                  :loading="userStore.isLoading"
                  @click="handleUpdateProfile"
                >
                  保存修改
                </n-button>
              </n-form-item>
            </n-form>
          </div>
          
          <!-- 我的课程 -->
          <div v-else-if="activeTab === 'courses'" class="profile-section">
            <h2>我的课程</h2>
            <div v-if="enrolledCourses.length > 0">
              <n-grid :cols="2" :x-gap="24" :y-gap="24" responsive="screen">
                <n-grid-item v-for="course in enrolledCourses" :key="course.id">
                  <CourseCard :course="course" />
                </n-grid-item>
              </n-grid>
            </div>
            <div v-else class="empty-state">
              <n-empty description="您还没有报名任何课程">
                <template #extra>
                  <n-button @click="$router.push('/courses')">
                    去选课
                  </n-button>
                </template>
              </n-empty>
            </div>
          </div>
          
          <!-- 学习统计 -->
          <div v-else-if="activeTab === 'stats'" class="profile-section">
            <h2>学习统计</h2>
            <n-grid :cols="3" :x-gap="24" :y-gap="24" responsive="screen">
              <n-grid-item>
                <n-card>
                  <n-statistic label="已报名课程" :value="enrolledCourses.length" />
                </n-card>
              </n-grid-item>
              <n-grid-item>
                <n-card>
                  <n-statistic label="完成课程" :value="completedCourses" />
                </n-card>
              </n-grid-item>
              <n-grid-item>
                <n-card>
                  <n-statistic label="学习时长" value="120" suffix="小时" />
                </n-card>
              </n-grid-item>
            </n-grid>
            
            <div class="learning-progress">
              <h3>学习进度</h3>
              <div v-for="course in enrolledCourses" :key="course.id" class="progress-item">
                <div class="course-info">
                  <h4>{{ course.title }}</h4>
                  <span class="progress-text">{{ course.progress || 0 }}%</span>
                </div>
                <n-progress
                  type="line"
                  :percentage="course.progress || 0"
                  :show-indicator="false"
                />
              </div>
            </div>
          </div>
          
          <!-- 设置 -->
          <div v-else-if="activeTab === 'settings'" class="profile-section">
            <h2>账户设置</h2>
            <div class="settings-section">
              <h3>密码修改</h3>
              <n-form label-placement="left" label-width="120px">
                <n-form-item label="当前密码">
                  <n-input type="password" placeholder="请输入当前密码" />
                </n-form-item>
                <n-form-item label="新密码">
                  <n-input type="password" placeholder="请输入新密码" />
                </n-form-item>
                <n-form-item label="确认新密码">
                  <n-input type="password" placeholder="请再次输入新密码" />
                </n-form-item>
                <n-form-item>
                  <n-button type="primary">修改密码</n-button>
                </n-form-item>
              </n-form>
            </div>
            
            <div class="settings-section">
              <h3>通知设置</h3>
              <n-space vertical>
                <n-checkbox>接收课程更新通知</n-checkbox>
                <n-checkbox>接收学习提醒</n-checkbox>
                <n-checkbox>接收优惠活动通知</n-checkbox>
              </n-space>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, h } from 'vue'
import { useMessage, type FormInst, type FormRules } from 'naive-ui'
import { useUserStore } from '@/stores/user'
import { useCourseStore } from '@/stores/course'
import CourseCard from '@/components/course/CourseCard.vue'
import SafeAvatar from '@/components/common/SafeAvatar.vue'
import {
  PersonOutline,
  BookOutline,
  StatsChartOutline,
  SettingsOutline
} from '@vicons/ionicons5'

const message = useMessage()
const userStore = useUserStore()
const courseStore = useCourseStore()

const activeTab = ref('info')
const formRef = ref<FormInst | null>(null)

// 个人信息表单
const profileForm = reactive({
  username: '',
  email: ''
})

// 表单验证规则
const rules: FormRules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: ['input', 'blur']
    }
  ]
}

// 菜单选项
const menuOptions = [
  {
    label: '个人信息',
    key: 'info',
    icon: () => h(PersonOutline)
  },
  {
    label: '我的课程',
    key: 'courses',
    icon: () => h(BookOutline)
  },
  {
    label: '学习统计',
    key: 'stats',
    icon: () => h(StatsChartOutline)
  },
  {
    label: '账户设置',
    key: 'settings',
    icon: () => h(SettingsOutline)
  }
]

// 已报名课程
const enrolledCourses = computed(() => courseStore.enrolledCourses)

// 完成课程数量
const completedCourses = computed(() => {
  return enrolledCourses.value.filter(course => course.progress === 100).length
})

// 处理菜单选择
const handleMenuSelect = (key: string) => {
  activeTab.value = key
}

// 处理头像上传
const handleAvatarUpload = () => {
  message.info('头像上传功能待实现')
}

// 处理更新个人信息
const handleUpdateProfile = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    const result = await userStore.updateProfile({
      username: profileForm.username
    })

    if (result.success) {
      message.success(result.message)
    } else {
      message.error(result.message)
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

onMounted(() => {
  // 初始化表单数据
  if (userStore.user) {
    profileForm.username = userStore.user.username
    profileForm.email = userStore.user.email
  }
})
</script>

<style scoped>
.profile {
  min-height: 100vh;
  padding: 40px 0;
}

.profile-container {
  display: grid;
  grid-template-columns: 250px 1fr;
  gap: 40px;
  max-width: 1200px;
  margin: 0 auto;
}

.sidebar {
  background: white;
  border-radius: 12px;
  padding: 24px 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.main-content {
  background: white;
  border-radius: 12px;
  padding: 32px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.profile-section h2 {
  margin: 0 0 32px;
  color: #333;
  font-size: 24px;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.learning-progress {
  margin-top: 32px;
}

.learning-progress h3 {
  margin-bottom: 24px;
  color: #333;
}

.progress-item {
  margin-bottom: 24px;
}

.progress-item .course-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.progress-item h4 {
  margin: 0;
  color: #333;
  font-size: 16px;
}

.progress-text {
  color: #666;
  font-size: 14px;
}

.settings-section {
  margin-bottom: 40px;
}

.settings-section h3 {
  margin-bottom: 24px;
  color: #333;
  font-size: 18px;
}

@media (max-width: 768px) {
  .profile-container {
    grid-template-columns: 1fr;
    gap: 24px;
  }
  
  .sidebar {
    order: 2;
  }
  
  .main-content {
    order: 1;
    padding: 24px;
  }
}
</style>
