<template>
  <div class="mine-page">
    <!-- 子女身份提示栏 -->
    <div v-if="isChildMode" class="child-mode-bar">
      <span>当前身份：<strong>{{ user?.nickname }}</strong>（子女账号）</span>
      <a-button type="link" size="small" @click="handleSwitchBackToParent">切换回家长</a-button>
    </div>

    <!-- 用户卡片 -->
    <div class="user-card">
      <a-avatar :size="56" :src="user?.avatar" class="user-avatar">
        {{ user?.nickname?.charAt(0) }}
      </a-avatar>
      <div class="user-info">
        <h2>{{ user?.nickname || "未登录" }}</h2>
        <p>{{ user?.city || "未设置城市" }}{{ user?.phone ? ' · ' + user.phone : '' }}</p>
      </div>
      <a-button type="text" size="small" @click="showEditModal = true" class="edit-btn">
        <edit-outlined /> 编辑
      </a-button>
    </div>

    <!-- 功能入口 -->
    <div class="menu-group">
      <div class="menu-item" @click="$router.push('/p/mine/registrations')">
        <div class="menu-icon" style="background: #eef2ff; color: #6366f1">
          <file-text-outlined />
        </div>
        <div class="menu-content">
          <span class="menu-label">我的报名</span>
          <span class="menu-desc">{{ regCount > 0 ? `${regCount} 个活动` : '查看已报名的活动' }}</span>
        </div>
        <right-outlined class="menu-arrow" />
      </div>

      <div class="menu-item" @click="$router.push('/p/mine/works')">
        <div class="menu-icon" style="background: #fdf2f8; color: #ec4899">
          <picture-outlined />
        </div>
        <div class="menu-content">
          <span class="menu-label">我的作品</span>
          <span class="menu-desc">{{ workCount > 0 ? `${workCount} 个作品` : '管理提交的作品' }}</span>
        </div>
        <right-outlined class="menu-arrow" />
      </div>

      <div v-if="!isChildMode" class="menu-item" @click="$router.push('/p/mine/children')">
        <div class="menu-icon" style="background: #ecfdf5; color: #10b981">
          <team-outlined />
        </div>
        <div class="menu-content">
          <span class="menu-label">子女账号</span>
          <span class="menu-desc">{{ childrenDesc }}</span>
        </div>
        <right-outlined class="menu-arrow" />
      </div>
    </div>

    <!-- 退出登录 -->
    <div class="menu-group">
      <div class="menu-item logout" @click="handleLogout">
        <div class="menu-icon" style="background: #fff1f2; color: #f43f5e">
          <logout-outlined />
        </div>
        <div class="menu-content">
          <span class="menu-label">退出登录</span>
        </div>
      </div>
    </div>

    <!-- 编辑个人信息弹窗 -->
    <a-modal v-model:open="showEditModal" title="编辑个人信息" :footer="null" :width="400">
      <a-form layout="vertical" @finish="handleSaveProfile" style="margin-top: 16px;">
        <a-form-item label="昵称" :rules="[{ required: true, message: '请输入昵称' }]">
          <a-input v-model:value="editForm.nickname" placeholder="你的昵称" :maxlength="20" />
        </a-form-item>
        <a-form-item label="性别">
          <a-select v-model:value="editForm.gender" placeholder="选择性别" allow-clear>
            <a-select-option value="male">男</a-select-option>
            <a-select-option value="female">女</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="城市">
          <a-input v-model:value="editForm.city" placeholder="你所在的城市" :maxlength="50" />
        </a-form-item>
        <a-button type="primary" html-type="submit" block :loading="editLoading"
          style="height: 40px; border-radius: 10px; font-weight: 600;">
          保存
        </a-button>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue"
import { useRouter } from "vue-router"
import { message } from "ant-design-vue"
import {
  FileTextOutlined,
  PictureOutlined,
  TeamOutlined,
  RightOutlined,
  LogoutOutlined,
  EditOutlined,
} from "@ant-design/icons-vue"
import { publicProfileApi, publicMineApi } from "@/api/public"

const router = useRouter()
const user = ref<any>(null)
const showEditModal = ref(false)
const editLoading = ref(false)
const regCount = ref(0)
const workCount = ref(0)

// 判断当前是否子女身份
const isChildMode = computed(() => {
  const u = localStorage.getItem('public_user')
  if (!u) return false
  try { return JSON.parse(u).userType === 'child' } catch { return false }
})

// 切换回家长身份
const handleSwitchBackToParent = () => {
  const parentToken = localStorage.getItem('parent_token_backup')
  const parentUser = localStorage.getItem('parent_user_backup')
  if (parentToken && parentUser) {
    localStorage.setItem('public_token', parentToken)
    localStorage.setItem('public_user', parentUser)
    localStorage.removeItem('parent_token_backup')
    localStorage.removeItem('parent_user_backup')
    message.success('已切换回家长身份')
    fetchProfile()
  } else {
    // 没有备份，直接退出登录
    handleLogout()
  }
}

const editForm = reactive({
  nickname: "",
  city: "",
  gender: "",
})

const childrenDesc = computed(() => {
  const count = user.value?.childrenCount || 0
  return count > 0 ? `已创建 ${count} 个子女账号` : "为子女创建独立账号"
})

const fetchProfile = async () => {
  try {
    user.value = await publicProfileApi.getProfile()
    editForm.nickname = user.value?.nickname || ""
    editForm.city = user.value?.city || ""
    editForm.gender = user.value?.gender || ""
  } catch {
    handleLogout()
  }
}

const fetchCounts = async () => {
  try {
    const [regs, works] = await Promise.all([
      publicMineApi.registrations({ page: 1, pageSize: 1 }),
      publicMineApi.works({ page: 1, pageSize: 1 }),
    ])
    regCount.value = regs?.total || 0
    workCount.value = works?.total || 0
  } catch { /* ignore */ }
}

const handleSaveProfile = async () => {
  editLoading.value = true
  try {
    await publicProfileApi.updateProfile({
      nickname: editForm.nickname,
      city: editForm.city || undefined,
      gender: editForm.gender || undefined,
    })
    message.success("保存成功")
    showEditModal.value = false
    fetchProfile()
  } catch {
    message.error("保存失败")
  } finally {
    editLoading.value = false
  }
}

const handleLogout = () => {
  localStorage.removeItem("public_token")
  localStorage.removeItem("public_user")
  localStorage.removeItem("parent_token_backup")
  localStorage.removeItem("parent_user_backup")
  router.push("/p/login")
}

onMounted(() => {
  fetchProfile()
  fetchCounts()
})
</script>

<style scoped lang="scss">
$primary: #6366f1;

.child-mode-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
  background: linear-gradient(135deg, #fdf2f8, #ede9fe);
  border-radius: 12px;
  margin-bottom: 16px;
  font-size: 13px;
  color: #6b21a8;

  strong { font-weight: 700; }
}

.mine-page {
  max-width: 600px;
  margin: 0 auto;
}

.user-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 24px;
  background: linear-gradient(135deg, #eef2ff 0%, #fdf2f8 100%);
  border-radius: 20px;
  margin-bottom: 20px;

  .user-avatar {
    border: 3px solid rgba(255, 255, 255, 0.8);
    box-shadow: 0 4px 12px rgba($primary, 0.15);
    font-size: 22px;
    font-weight: 700;
    background: linear-gradient(135deg, $primary, #ec4899);
  }

  .edit-btn {
    color: #6b7280;
    font-size: 13px;
    margin-left: auto;
  }

  .user-info {
    flex: 1;

    h2 {
      font-size: 18px;
      font-weight: 700;
      color: #1e1b4b;
      margin: 0 0 4px;
    }

    p {
      font-size: 13px;
      color: #6b7280;
      margin: 0;
    }
  }
}

.menu-group {
  background: #fff;
  border-radius: 16px;
  overflow: hidden;
  margin-bottom: 16px;
  border: 1px solid rgba($primary, 0.06);
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 16px 18px;
  cursor: pointer;
  transition: background 0.2s;

  &:not(:last-child) {
    border-bottom: 1px solid #f0ecf9;
  }

  &:hover {
    background: rgba($primary, 0.02);
  }

  &.logout:hover {
    background: rgba(244, 63, 94, 0.02);
  }

  .menu-icon {
    width: 40px;
    height: 40px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    flex-shrink: 0;
  }

  .menu-content {
    flex: 1;
    min-width: 0;

    .menu-label {
      display: block;
      font-size: 14px;
      font-weight: 600;
      color: #1e1b4b;
    }

    .menu-desc {
      display: block;
      font-size: 12px;
      color: #9ca3af;
      margin-top: 2px;
    }
  }

  .menu-arrow {
    color: #d1d5db;
    font-size: 12px;
  }
}
</style>
