<script setup>
import { computed, onBeforeUnmount, onMounted, provide, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import {
  Bell,
  ChatLineSquare,
  DataAnalysis,
  Document,
  List,
  Message,
  Setting,
  Tools,
  User,
} from '@element-plus/icons-vue'

import { api } from '../api/client'
import { fetchFeedbackStats } from '../api/feedbacks'
import { fetchPasswordResets } from '../api/passwordResets'
import { fetchSystemStats } from '../api/stats'
import StatsCards from '../components/StatsCards.vue'

const route = useRoute()
const router = useRouter()

const stats = ref({})
const loadingStats = ref(false)

const adminUsername = computed(() => stats.value?.admin_username || '')

async function refreshStats() {
  loadingStats.value = true
  try {
    stats.value = await fetchSystemStats()
  } finally {
    loadingStats.value = false
  }
}

const loadingBadges = ref(false)
const pendingResetsCount = ref(0)
const pendingFeedbackCount = ref(0)
let badgeTimer

async function refreshNavBadges(partial = null) {
  if (partial && typeof partial === 'object') {
    if (Object.prototype.hasOwnProperty.call(partial, 'pendingResets')) {
      pendingResetsCount.value = Number(partial.pendingResets || 0)
    }
    if (Object.prototype.hasOwnProperty.call(partial, 'pendingFeedbacks')) {
      pendingFeedbackCount.value = Number(partial.pendingFeedbacks || 0)
    }
    return
  }

  if (loadingBadges.value) return
  loadingBadges.value = true

  try {
    const [resetsResult, feedbackResult] = await Promise.allSettled([
      fetchPasswordResets(),
      fetchFeedbackStats(),
    ])

    if (resetsResult.status === 'fulfilled') {
      pendingResetsCount.value = Array.isArray(resetsResult.value) ? resetsResult.value.length : 0
    }

    if (feedbackResult.status === 'fulfilled') {
      pendingFeedbackCount.value = Number(feedbackResult.value?.pending || 0)
    }
  } finally {
    loadingBadges.value = false
  }
}

provide('refreshStats', refreshStats)
provide('adminStats', stats)
provide('refreshNavBadges', refreshNavBadges)

const isMobile = ref(false)
const drawerOpen = ref(false)
let mediaQuery

function syncIsMobile() {
  isMobile.value = Boolean(mediaQuery?.matches)
  if (!isMobile.value) drawerOpen.value = false
}

onMounted(async () => {
  mediaQuery = window.matchMedia('(max-width: 768px)')
  mediaQuery.addEventListener?.('change', syncIsMobile)
  syncIsMobile()

  await refreshStats()
  await refreshNavBadges()
  badgeTimer = window.setInterval(refreshNavBadges, 60_000)
})

onBeforeUnmount(() => {
  mediaQuery?.removeEventListener?.('change', syncIsMobile)
  window.clearInterval(badgeTimer)
})

const menuItems = [
  { path: '/reports', label: '报表', icon: Document },
  { path: '/users', label: '用户', icon: User, badgeKey: 'resets' },
  { path: '/feedbacks', label: '反馈', icon: ChatLineSquare, badgeKey: 'feedbacks' },
  { path: '/stats', label: '统计', icon: DataAnalysis },
  { path: '/logs', label: '任务日志', icon: List },
  { path: '/announcements', label: '公告', icon: Bell },
  { path: '/email', label: '邮件', icon: Message },
  { path: '/system', label: '系统配置', icon: Tools },
  { path: '/settings', label: '设置', icon: Setting },
]

const activeMenu = computed(() => route.path)

function badgeFor(item) {
  if (!item?.badgeKey) return 0
  if (item.badgeKey === 'resets') return Number(pendingResetsCount.value || 0)
  if (item.badgeKey === 'feedbacks') {
    return Number(pendingFeedbackCount.value || 0)
  }
  return 0
}

async function logout() {
  try {
    await ElMessageBox.confirm('确定退出管理员登录吗？', '退出登录', {
      confirmButtonText: '退出',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }

  try {
    await api.post('/logout')
  } finally {
    window.location.href = '/yuyx'
  }
}

async function go(path) {
  await router.push(path)
  drawerOpen.value = false
}
</script>

<template>
  <el-container class="layout-root">
    <el-aside v-if="!isMobile" width="220px" class="layout-aside">
      <div class="brand">
        <div class="brand-title">后台管理</div>
        <div class="brand-sub app-muted">知识管理平台</div>
      </div>

      <el-menu :default-active="activeMenu" class="aside-menu" router @select="go">
        <el-menu-item v-for="item in menuItems" :key="item.path" :index="item.path">
          <el-icon><component :is="item.icon" /></el-icon>
          <el-badge v-if="badgeFor(item) > 0" :value="badgeFor(item)" :max="99" class="menu-badge">
            <span class="menu-label">{{ item.label }}</span>
          </el-badge>
          <span v-else class="menu-label">{{ item.label }}</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <el-container>
      <el-header class="layout-header">
        <div class="header-left">
          <el-button v-if="isMobile" text class="header-menu-btn" @click="drawerOpen = true">
            菜单
          </el-button>
          <div class="header-title">后台管理系统</div>
        </div>

        <div class="header-right">
          <div class="admin-name">
            <span class="app-muted">管理员</span>
            <strong>{{ adminUsername || '-' }}</strong>
          </div>
          <el-button type="primary" plain @click="logout">退出</el-button>
        </div>
      </el-header>

      <el-main class="layout-main">
        <StatsCards :stats="stats" :loading="loadingStats" />
        <Suspense>
          <template #default>
            <RouterView />
          </template>
          <template #fallback>
            <el-card shadow="never" :body-style="{ padding: '16px' }" class="fallback-card">
              <el-skeleton :rows="5" animated />
            </el-card>
          </template>
        </Suspense>
      </el-main>
    </el-container>

    <el-drawer v-model="drawerOpen" size="240px" :with-header="false">
      <div class="drawer-brand">
        <div class="brand-title">后台管理</div>
        <div class="brand-sub app-muted">知识管理平台</div>
      </div>
      <el-menu :default-active="activeMenu" class="aside-menu" router @select="go">
        <el-menu-item v-for="item in menuItems" :key="item.path" :index="item.path">
          <el-icon><component :is="item.icon" /></el-icon>
          <el-badge v-if="badgeFor(item) > 0" :value="badgeFor(item)" :max="99" class="menu-badge">
            <span class="menu-label">{{ item.label }}</span>
          </el-badge>
          <span v-else class="menu-label">{{ item.label }}</span>
        </el-menu-item>
      </el-menu>
    </el-drawer>
  </el-container>
</template>

<style scoped>
.layout-root {
  height: 100%;
}

.layout-aside {
  background: #ffffff;
  border-right: 1px solid var(--app-border);
}

.brand {
  padding: 18px 16px 10px;
}

.drawer-brand {
  padding: 18px 16px 10px;
}

.brand-title {
  font-size: 15px;
  font-weight: 800;
  letter-spacing: 0.2px;
}

.brand-sub {
  margin-top: 2px;
  font-size: 12px;
}

.aside-menu {
  border-right: none;
}

.menu-label {
  display: inline-flex;
  align-items: center;
  min-width: 0;
}

.menu-badge {
  display: inline-flex;
  align-items: center;
}

.fallback-card {
  border-radius: var(--app-radius);
  border: 1px solid var(--app-border);
}

.layout-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  background: rgba(246, 247, 251, 0.6);
  backdrop-filter: saturate(180%) blur(10px);
  border-bottom: 1px solid var(--app-border);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
}

.header-title {
  font-size: 14px;
  font-weight: 800;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.header-menu-btn {
  padding-left: 0;
  padding-right: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.admin-name {
  display: flex;
  align-items: baseline;
  gap: 8px;
  font-size: 13px;
}

.layout-main {
  padding: 16px;
}

@media (max-width: 768px) {
  .layout-header {
    flex-wrap: wrap;
    height: auto;
    padding-top: 10px;
    padding-bottom: 10px;
  }

  .header-right {
    width: 100%;
    justify-content: flex-end;
  }

  .admin-name .app-muted {
    display: none;
  }

  .layout-main {
    padding: 12px;
  }
}
</style>
