<template>
  <div class="children-page">
    <div class="page-header">
      <h2>子女账号管理</h2>
      <a-button type="primary" shape="round" @click="openCreateModal">
        <plus-outlined /> 创建子女账号
      </a-button>
    </div>

    <div v-if="loading" class="loading-wrap"><a-spin /></div>

    <div v-else-if="childAccounts.length === 0" class="empty-wrap">
      <a-empty description="还没有创建子女账号">
        <a-button type="primary" shape="round" @click="openCreateModal">创建子女账号</a-button>
      </a-empty>
    </div>

    <div v-else class="children-list">
      <div v-for="child in childAccounts" :key="child.id" class="child-card">
        <a-avatar :size="48" :src="child.avatar" class="child-avatar">
          {{ child.nickname?.charAt(0) }}
        </a-avatar>
        <div class="child-info">
          <h3>{{ child.nickname }}</h3>
          <div class="child-meta">
            <span>@{{ child.username }}</span>
            <span v-if="child.gender">{{ child.gender === 'male' ? '男' : '女' }}</span>
            <span v-if="getAge(child.birthday)">{{ getAge(child.birthday) }}岁</span>
            <span v-if="child.city">{{ child.city }}</span>
          </div>
          <div class="child-status">
            <a-tag :color="child.status === 'enabled' ? 'green' : 'red'" size="small">
              {{ child.status === 'enabled' ? '正常' : '已禁用' }}
            </a-tag>
            <a-tag v-if="child.controlMode === 'restricted'" color="orange" size="small">受限模式</a-tag>
          </div>
        </div>
        <div class="child-actions">
          <a-button type="primary" size="small" shape="round" @click="handleSwitch(child)" :loading="switchingId === child.id">
            切换身份
          </a-button>
          <a-button type="text" size="small" @click="openEditModal(child)">
            <edit-outlined />
          </a-button>
        </div>
      </div>
    </div>

    <!-- 旧版子女信息（兼容，折叠显示） -->
    <template v-if="legacyChildren.length > 0">
      <a-divider>
        <span class="divider-text">旧版子女信息（{{ legacyChildren.length }}条）</span>
      </a-divider>
      <div class="legacy-list">
        <div v-for="child in legacyChildren" :key="child.id" class="legacy-card">
          <span class="legacy-name">{{ child.name }}</span>
          <div class="legacy-meta">
            <span v-if="child.grade">{{ child.grade }}</span>
            <span v-if="child.city">{{ child.city }}</span>
          </div>
        </div>
      </div>
    </template>

    <!-- 创建子女账号弹窗 -->
    <a-modal
      v-model:open="createModalVisible"
      title="创建子女账号"
      :footer="null"
      :width="440"
    >
      <a-form :model="createForm" layout="vertical" @finish="handleCreate" class="child-form">
        <a-form-item label="用户名" name="username" :rules="[{ required: true, message: '请输入用户名' }, { min: 4, message: '至少4个字符' }]">
          <a-input v-model:value="createForm.username" placeholder="子女登录用的用户名" />
        </a-form-item>
        <a-form-item label="密码" name="password" :rules="[{ required: true, message: '请输入密码' }, { min: 6, message: '至少6个字符' }]">
          <a-input-password v-model:value="createForm.password" placeholder="设置登录密码" />
        </a-form-item>
        <a-form-item label="昵称" name="nickname" :rules="[{ required: true, message: '请输入昵称' }, { min: 2, message: '至少2个字符' }]">
          <a-input v-model:value="createForm.nickname" placeholder="在平台上显示的名字" />
        </a-form-item>
        <a-row :gutter="12">
          <a-col :span="12">
            <a-form-item label="性别" name="gender">
              <a-select v-model:value="createForm.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-col>
          <a-col :span="12">
            <a-form-item label="出生日期" name="birthday">
              <a-date-picker v-model:value="createForm.birthday" style="width: 100%" placeholder="选择日期" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="所在城市" name="city">
          <a-input v-model:value="createForm.city" placeholder="如：广州" />
        </a-form-item>
        <a-button type="primary" html-type="submit" block size="large" :loading="submitting" class="submit-btn">
          创建账号
        </a-button>
      </a-form>
    </a-modal>

    <!-- 编辑子女账号弹窗 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑子女账号"
      :footer="null"
      :width="440"
    >
      <a-form :model="editForm" layout="vertical" @finish="handleEdit" class="child-form">
        <a-form-item label="昵称" name="nickname">
          <a-input v-model:value="editForm.nickname" placeholder="显示名称" />
        </a-form-item>
        <a-form-item label="重置密码" name="password">
          <a-input-password v-model:value="editForm.password" placeholder="不修改请留空" />
        </a-form-item>
        <a-row :gutter="12">
          <a-col :span="12">
            <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-col>
          <a-col :span="12">
            <a-form-item label="出生日期">
              <a-date-picker v-model:value="editForm.birthday" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="所在城市">
          <a-input v-model:value="editForm.city" placeholder="如：广州" />
        </a-form-item>
        <a-form-item label="管控模式">
          <a-radio-group v-model:value="editForm.controlMode">
            <a-radio value="open">自主模式（子女自由操作）</a-radio>
            <a-radio value="restricted">受限模式（发布需确认）</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-button type="primary" html-type="submit" block size="large" :loading="submitting" class="submit-btn">
          保存修改
        </a-button>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { PlusOutlined, EditOutlined } from '@ant-design/icons-vue'
import { publicChildAccountApi, publicChildrenApi, type ChildAccount, type Child } from '@/api/public'
import dayjs from 'dayjs'

const router = useRouter()

const childAccounts = ref<ChildAccount[]>([])
const legacyChildren = ref<Child[]>([])
const loading = ref(true)
const submitting = ref(false)
const switchingId = ref<number | null>(null)

// 创建弹窗
const createModalVisible = ref(false)
const createForm = reactive({
  username: '',
  password: '',
  nickname: '',
  gender: undefined as string | undefined,
  birthday: null as any,
  city: '',
})

// 编辑弹窗
const editModalVisible = ref(false)
const editingId = ref<number | null>(null)
const editForm = reactive({
  nickname: '',
  password: '',
  gender: undefined as string | undefined,
  birthday: null as any,
  city: '',
  controlMode: 'open',
})

const getAge = (birthday: string | null) => {
  if (!birthday) return null
  return dayjs().diff(dayjs(birthday), 'year')
}

const fetchData = async () => {
  loading.value = true
  try {
    const [accounts, legacy] = await Promise.all([
      publicChildAccountApi.list(),
      publicChildrenApi.list(),
    ])
    childAccounts.value = accounts
    legacyChildren.value = legacy
  } catch { /* */ }
  finally { loading.value = false }
}

const openCreateModal = () => {
  createForm.username = ''
  createForm.password = ''
  createForm.nickname = ''
  createForm.gender = undefined
  createForm.birthday = null
  createForm.city = ''
  createModalVisible.value = true
}

const handleCreate = async () => {
  submitting.value = true
  try {
    await publicChildAccountApi.create({
      username: createForm.username,
      password: createForm.password,
      nickname: createForm.nickname,
      gender: createForm.gender,
      birthday: createForm.birthday ? dayjs(createForm.birthday).format('YYYY-MM-DD') : undefined,
      city: createForm.city || undefined,
    })
    message.success('子女账号创建成功')
    createModalVisible.value = false
    fetchData()
  } catch (err: any) {
    message.error(err?.response?.data?.message || '创建失败')
  } finally {
    submitting.value = false
  }
}

const openEditModal = (child: ChildAccount) => {
  editingId.value = child.id
  editForm.nickname = child.nickname
  editForm.password = ''
  editForm.gender = child.gender || undefined
  editForm.birthday = child.birthday ? dayjs(child.birthday) : null
  editForm.city = child.city || ''
  editForm.controlMode = child.controlMode || 'open'
  editModalVisible.value = true
}

const handleEdit = async () => {
  if (!editingId.value) return
  submitting.value = true
  try {
    await publicChildAccountApi.update(editingId.value, {
      nickname: editForm.nickname || undefined,
      password: editForm.password || undefined,
      gender: editForm.gender,
      birthday: editForm.birthday ? dayjs(editForm.birthday).format('YYYY-MM-DD') : undefined,
      city: editForm.city || undefined,
      controlMode: editForm.controlMode,
    })
    message.success('修改成功')
    editModalVisible.value = false
    fetchData()
  } catch (err: any) {
    message.error(err?.response?.data?.message || '修改失败')
  } finally {
    submitting.value = false
  }
}

const handleSwitch = async (child: ChildAccount) => {
  switchingId.value = child.id
  try {
    const result = await publicChildAccountApi.switchToChild(child.id)
    // 保存子女的 token 和用户信息，记住家长 token 用于切回
    const parentToken = localStorage.getItem('public_token')
    const parentUser = localStorage.getItem('public_user')
    localStorage.setItem('parent_token_backup', parentToken || '')
    localStorage.setItem('parent_user_backup', parentUser || '')

    localStorage.setItem('public_token', result.token)
    localStorage.setItem('public_user', JSON.stringify(result.user))

    message.success(`已切换到 ${child.nickname} 的身份`)
    router.push('/p/mine')
  } catch (err: any) {
    message.error(err?.response?.data?.message || '切换失败')
  } finally {
    switchingId.value = null
  }
}

onMounted(fetchData)
</script>

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

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

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

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

.loading-wrap, .empty-wrap {
  padding: 60px 0;
  display: flex;
  justify-content: center;
}

.children-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.child-card {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 18px;
  background: #fff;
  border-radius: 16px;
  border: 1px solid rgba($primary, 0.06);
  transition: box-shadow 0.2s;

  &:hover { box-shadow: 0 4px 16px rgba($primary, 0.08); }

  .child-avatar {
    background: linear-gradient(135deg, $primary, #ec4899);
    font-size: 18px;
    font-weight: 700;
    flex-shrink: 0;
  }

  .child-info {
    flex: 1;
    min-width: 0;

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

    .child-meta {
      display: flex;
      gap: 6px;
      flex-wrap: wrap;
      margin-bottom: 4px;
      span { font-size: 11px; color: #9ca3af; background: #f5f3ff; padding: 1px 6px; border-radius: 8px; }
    }

    .child-status {
      display: flex;
      gap: 4px;
    }
  }

  .child-actions {
    display: flex;
    flex-direction: column;
    gap: 4px;
    flex-shrink: 0;
    align-items: flex-end;
  }
}

.divider-text { font-size: 12px; color: #9ca3af; }

.legacy-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.legacy-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #faf9fe;
  border-radius: 10px;

  .legacy-name { font-weight: 600; color: #6b7280; }
  .legacy-meta {
    display: flex;
    gap: 6px;
    span { font-size: 11px; color: #9ca3af; }
  }
}

.child-form {
  .submit-btn {
    margin-top: 8px;
    height: 44px !important;
    border-radius: 12px !important;
    font-weight: 600 !important;
  }
}
</style>
