<template>
  <el-row :gutter="20">
    <!-- Left Column: Profile Card -->
    <el-col :span="8" :xs="24">
      <el-card class="profile-card" :body-style="{ padding: '0px' }">
        <div class="profile-header">
          <img src="@/assets/img/profile_bg.jpg" alt="Cover" class="cover-image" />
          <div class="avatar-wrapper">
            <el-upload
              class="avatar-uploader-card"
              :show-file-list="false"
              :http-request="handleAvatarUpload"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.avatarPath" :src="apiBase + form.avatarPath" class="profile-avatar" />
              <div v-else class="profile-avatar-placeholder">
                <el-icon><Plus /></el-icon>
              </div>
              <div class="avatar-mask">
                <el-icon><Plus /></el-icon>
              </div>
            </el-upload>
          </div>
        </div>
        <div class="profile-info">
          <h2 class="profile-name">{{ form.nickname || form.username || 'User' }}</h2>
          
          <div class="profile-details">
            <div class="detail-item">
              <el-icon><Message /></el-icon>
              <span>{{ form.email || '未设置邮箱' }}</span>
            </div>
            <div class="detail-item">
              <el-icon><Iphone /></el-icon>
              <span>{{ form.phone || '未设置手机' }}</span>
            </div>
            <div class="detail-item">
              <el-icon><User /></el-icon>
              <span>{{ form.gender === 1 ? '男' : (form.gender === 2 ? '女' : '未知') }}</span>
            </div>
          </div>
          
          <!-- <el-divider content-position="center">标签</el-divider>
          <div class="profile-tags">
            <el-tag effect="plain">交互专家</el-tag>
            <el-tag effect="plain" type="success">设计爱好者</el-tag>
            <el-tag effect="plain" type="warning">Vue.js</el-tag>
            <el-tag effect="plain" type="info">Spring Boot</el-tag>
          </div> -->
        </div>
      </el-card>
    </el-col>

    <!-- Right Column: Settings Tabs -->
    <el-col :span="16" :xs="24">
      <el-card>
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本设置" name="info">
            <div class="tab-content">
              <el-form :model="form" label-position="top" class="settings-form">
                <el-row :gutter="24">
                  <el-col :span="12" :xs="24">
                    <el-form-item label="昵称">
                      <el-input v-model="form.nickname" placeholder="请输入昵称" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12" :xs="24">
                    <el-form-item label="性别">
                      <el-select v-model="form.gender" style="width: 100%">
                        <el-option label="未知" :value="0" />
                        <el-option label="男" :value="1" />
                        <el-option label="女" :value="2" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12" :xs="24">
                    <el-form-item label="手机">
                      <el-input v-model="form.phone" placeholder="请输入手机号" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12" :xs="24">
                    <el-form-item label="邮箱">
                      <el-input v-model="form.email" placeholder="请输入邮箱" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="个人介绍">
                      <el-input 
                        v-model="form.bio" 
                        type="textarea" 
                        :rows="4" 
                        placeholder="个人介绍..." 
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item>
                      <el-button type="primary" :loading="loading" @click="onSubmit">更新基本信息</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </el-tab-pane>

          <el-tab-pane label="安全设置" name="password">
             <div class="tab-content-password">
               <el-form :model="pwdForm" label-position="top" style="max-width: 500px">
                 <el-form-item label="旧密码">
                   <el-input v-model="pwdForm.oldPassword" type="password" show-password />
                 </el-form-item>
                 <el-form-item label="新密码">
                   <el-input v-model="pwdForm.newPassword" type="password" show-password />
                 </el-form-item>
                 <el-form-item label="确认新密码">
                   <el-input v-model="pwdForm.confirmPassword" type="password" show-password />
                 </el-form-item>
                 <el-form-item>
                   <el-button type="primary" :loading="pwdLoading" @click="onChangePassword">修改密码</el-button>
                 </el-form-item>
               </el-form>
             </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { updateProfile, updatePassword } from '../api/auth'
import { uploadFile } from '../api/common'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, User, Message, Iphone, Location } from '@element-plus/icons-vue'

const apiBase = import.meta.env.VITE_API_BASE || 'http://localhost:8080'
const auth = useAuthStore()
const router = useRouter()
const form = ref({
  nickname: '',
  phone: '',
  email: '',
  gender: 0,
  avatarPath: ''
})

const pwdForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const pwdLoading = ref(false)

const loading = ref(false)
const activeTab = ref('info')

onMounted(() => {
  form.value = {
    nickname: auth.nickname,
    phone: auth.phone,
    email: auth.email,
    gender: auth.gender,
    avatarPath: auth.avatarPath
  }
})

async function handleAvatarUpload(options) {
  try {
    const res = await uploadFile(options.file)
    form.value.avatarPath = res.url
    await updateProfile(form.value)
    await auth.fetchMe()
    ElMessage.success('头像已更新')
  } catch (e) {
    ElMessage.error(e?.response?.data?.message || '上传失败')
  }
}

function beforeAvatarUpload(rawFile) {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

async function onSubmit() {
  loading.value = true
  try {
    await updateProfile(form.value)
    ElMessage.success('更新成功')
    await auth.fetchMe() // refresh store
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

async function onChangePassword() {
  if (!pwdForm.oldPassword || !pwdForm.newPassword || !pwdForm.confirmPassword) {
    ElMessage.warning('请填写完整密码信息')
    return
  }
  if (pwdForm.newPassword !== pwdForm.confirmPassword) {
    ElMessage.warning('两次输入的新密码不一致')
    return
  }
  pwdLoading.value = true
  try {
    await updatePassword({
      oldPassword: pwdForm.oldPassword,
      newPassword: pwdForm.newPassword
    })
    ElMessage.success('密码修改成功，请重新登录')
    pwdForm.oldPassword = ''
    pwdForm.newPassword = ''
    pwdForm.confirmPassword = ''
    
    // Logout and redirect to login
    auth.logout()
    router.replace('/login')
  } catch (e) {
    ElMessage.error(e?.response?.data?.message || '密码修改失败')
  } finally {
    pwdLoading.value = false
  }
}
</script>

<style scoped>
.profile-card {
  text-align: center;
  padding-bottom: 20px;
  min-height: 438px;
}

.profile-header {
  position: relative;
  margin-bottom: 50px;
}

.cover-image {
  width: 100%;
  height: 160px;
  object-fit: cover;
}

.avatar-wrapper {
  position: absolute;
  left: 50%;
  bottom: -40px;
  transform: translateX(-50%);
  z-index: 10;
}

.profile-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 4px solid #fff;
  object-fit: cover;
  background-color: #fff;
}

.profile-avatar-placeholder {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 4px solid #fff;
  background-color: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  opacity: 0;
  transition: opacity 0.3s;
  cursor: pointer;
}

.avatar-wrapper:hover .avatar-mask {
  opacity: 1;
}

.profile-info {
  padding: 0 24px;
}

.profile-name {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 4px;
  color: #303133;
}

.profile-bio {
  color: #909399;
  font-size: 14px;
  margin: 0 0 24px;
}

.profile-details {
  display: flex;
  flex-direction: column;
  gap: 12px;
  text-align: left;
  margin-bottom: 24px;
  margin-top: 24px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
  color: #606266;
}

.profile-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: center;
}

.tab-title {
  font-size: 20px;
  font-weight: 500;
  margin-bottom: 24px;
  color: #303133;
}

.tab-content-base {
  /* margin-top: 58px; */
  padding: 0 12px;
}
.tab-content-password {
  margin-bottom: 76px;
  padding: 0 12px;
}

</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>
