<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import AppLayout from '@/components/layout/AppLayout.vue'

const authStore = useAuthStore()

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

const user = computed(() => authStore.user)

const profileForm = reactive({
  userName: user.value?.userName || '',
  avatar: user.value?.avatar || ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = {
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: Function) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const profileFormRef = ref()
const passwordFormRef = ref()

async function handleUpdateProfile() {
  loading.value = true
  try {
    const response = await authStore.updateProfile({
      userName: profileForm.userName,
      avatar: profileForm.avatar || undefined
    })
    if (response.success) {
      ElMessage.success('保存成功')
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '保存失败')
  } finally {
    loading.value = false
  }
}

async function handleChangePassword() {
  try {
    await passwordFormRef.value.validate()
  } catch {
    return
  }

  loading.value = true
  try {
    const response = await authStore.changePassword(
      passwordForm.oldPassword,
      passwordForm.newPassword
    )
    if (response.success) {
      ElMessage.success('密码修改成功')
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    } else {
      ElMessage.error(response.message || '密码修改失败')
    }
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '密码修改失败')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <AppLayout>
    <div class="settings-view">
      <div class="page-header">
        <h1>设置</h1>
      </div>

      <el-tabs v-model="activeTab" class="settings-tabs">
        <el-tab-pane label="个人资料" name="profile">
          <div class="settings-card">
            <el-form
              ref="profileFormRef"
              :model="profileForm"
              label-width="100px"
            >
              <el-form-item label="邮箱">
                <el-input :value="user?.email" disabled />
              </el-form-item>

              <el-form-item label="用户名">
                <el-input v-model="profileForm.userName" placeholder="请输入用户名" />
              </el-form-item>

              <el-form-item label="头像URL">
                <el-input v-model="profileForm.avatar" placeholder="请输入头像URL（可选）" />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" :loading="loading" @click="handleUpdateProfile">
                  保存修改
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <el-tab-pane label="修改密码" name="password">
          <div class="settings-card">
            <el-form
              ref="passwordFormRef"
              :model="passwordForm"
              :rules="passwordRules"
              label-width="100px"
            >
              <el-form-item label="原密码" prop="oldPassword">
                <el-input
                  v-model="passwordForm.oldPassword"
                  type="password"
                  show-password
                  placeholder="请输入原密码"
                />
              </el-form-item>

              <el-form-item label="新密码" prop="newPassword">
                <el-input
                  v-model="passwordForm.newPassword"
                  type="password"
                  show-password
                  placeholder="请输入新密码"
                />
              </el-form-item>

              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  show-password
                  placeholder="请确认新密码"
                />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" :loading="loading" @click="handleChangePassword">
                  修改密码
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </AppLayout>
</template>

<style lang="scss" scoped>
.settings-view {
  max-width: 600px;
  margin: 0 auto;
}

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

  h1 {
    font-size: 24px;
    font-weight: 600;
    color: #333;
  }
}

.settings-tabs {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.settings-card {
  padding: 20px 0;
}
</style>

