<template>
  <div class="profile-page">
    <BackNav />
    <div class="profile-card" v-if="user">
      <div class="profile-header">
        <el-avatar :size="64" class="profile-avatar">{{ user.username?.charAt(0).toUpperCase() }}</el-avatar>
        <div class="profile-info">
          <h3>{{ user.username }}</h3>
          <p>{{ user.email }}</p>
          <el-tag :type="user.role === 'admin' ? 'danger' : user.role === 'supplier' ? 'warning' : 'info'" size="small">{{ roleText(user.role) }}</el-tag>
        </div>
      </div>
      <el-descriptions :column="2" border class="profile-desc">
        <el-descriptions-item label="购买资格">{{ user.purchase_credits }}</el-descriptions-item>
        <el-descriptions-item label="邀请码">{{ user.invite_code }}</el-descriptions-item>
      </el-descriptions>
      <div class="profile-actions">
        <el-button @click="$router.push('/addresses')">地址管理</el-button>
        <el-button @click="$router.push('/orders')">我的订单</el-button>
        <el-button v-if="user.role === 'admin'" type="primary" @click="$router.push('/admin')">管理后台</el-button>
        <el-button v-if="user.role === 'supplier'" type="primary" @click="$router.push('/supplier')">供应商后台</el-button>
        <el-button type="warning" @click="showEditProfile = true">编辑资料</el-button>
        <el-button type="danger" @click="showChangePassword = true">修改密码</el-button>
      </div>
    </div>

    <el-dialog v-model="showEditProfile" title="编辑资料" width="400px">
      <el-form :model="profileForm" label-width="80px">
        <el-form-item label="用户名"><el-input v-model="profileForm.username" /></el-form-item>
        <el-form-item label="邮箱"><el-input v-model="profileForm.email" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditProfile = false">取消</el-button>
        <el-button type="primary" @click="saveProfile" :loading="saving">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showChangePassword" title="修改密码" width="400px">
      <el-form :model="passwordForm" label-width="80px">
        <el-form-item label="旧密码"><el-input v-model="passwordForm.old_password" type="password" show-password /></el-form-item>
        <el-form-item label="新密码"><el-input v-model="passwordForm.new_password" type="password" show-password /></el-form-item>
        <el-form-item label="确认密码"><el-input v-model="passwordForm.confirm_password" type="password" show-password /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showChangePassword = false">取消</el-button>
        <el-button type="primary" @click="changePassword" :loading="saving">确认修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../../store/user'
import { userApi } from '../../api'
import BackNav from '../../components/BackNav.vue'

const userStore = useUserStore()
const user = computed(() => userStore.user)

const showEditProfile = ref(false)
const showChangePassword = ref(false)
const saving = ref(false)
const profileForm = reactive({ username: '', email: '' })
const passwordForm = reactive({ old_password: '', new_password: '', confirm_password: '' })

watch(() => userStore.user, (u) => {
  if (u) {
    profileForm.username = u.username || ''
    profileForm.email = u.email || ''
  }
}, { immediate: true })

async function saveProfile() {
  saving.value = true
  try {
    await userApi.updateProfile(profileForm)
    ElMessage.success('资料已更新')
    showEditProfile.value = false
    await userStore.fetchProfile()
  } catch (err: any) {
    ElMessage.error(err.response?.data?.error || '更新失败')
  } finally {
    saving.value = false
  }
}

async function changePassword() {
  if (passwordForm.new_password !== passwordForm.confirm_password) {
    ElMessage.warning('两次密码不一致')
    return
  }
  if (passwordForm.new_password.length < 6) {
    ElMessage.warning('密码至少6位')
    return
  }
  saving.value = true
  try {
    await userApi.changePassword({ old_password: passwordForm.old_password, new_password: passwordForm.new_password })
    ElMessage.success('密码已修改')
    showChangePassword.value = false
    Object.assign(passwordForm, { old_password: '', new_password: '', confirm_password: '' })
  } catch (err: any) {
    ElMessage.error(err.response?.data?.error || '修改失败')
  } finally {
    saving.value = false
  }
}

const roleMap: Record<string, string> = {
  admin: '管理员',
  supplier: '供应商',
  user: '用户',
}
function roleText(r: string) { return roleMap[r] || r }

onMounted(() => userStore.fetchProfile())
</script>

<style scoped lang="scss">
.profile-page {
  padding: 0;
}

.profile-card {
  background: #2d2d44;
  border: 1px solid rgba(255, 255, 255, 0.06);
  border-radius: 12px;
  padding: 24px;
}

.profile-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 24px;
  padding-bottom: 24px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}

.profile-avatar {
  background: linear-gradient(135deg, #4e6ef2, #7c5cfc);
  color: #fff;
  font-size: 24px;
  font-weight: 600;
}

.profile-info h3 {
  font-size: 20px;
  font-weight: 600;
  color: #fff;
  margin-bottom: 4px;
}

.profile-info p {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.5);
  margin-bottom: 8px;
}

.profile-desc {
  margin-bottom: 24px;
}

.profile-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}
</style>
