<script setup lang="ts">
import {
  ChatDotRound,
  DataLine,
  Document,
  DocumentChecked,
  Operation,
  Fold,
  Expand,
  ScaleToOriginal,
  Shop,
  SwitchButton,
  Tickets,
  User,
  UserFilled,
  Wallet,
  Setting
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { logoutAdmin } from '@/features/admin'
import { useAdminSessionStore } from '@/stores/adminSession'

const router = useRouter()
const route = useRoute()
const adminSession = useAdminSessionStore()
const isCollapsed = ref(false)

interface NavItem {
  label: string
  to: string
  icon: any
  permission?: string
}

const allNavItems: NavItem[] = [
  { label: '仪表盘', to: '/admin/dashboard', icon: DataLine, permission: 'dashboard:view' },
  { label: '用户管理', to: '/admin/users', icon: User, permission: 'user:view' },
  { label: '订单管理', to: '/admin/orders', icon: Tickets, permission: 'order:view' },
  { label: '商品管理', to: '/admin/listings', icon: Shop, permission: 'listing:view' },
  { label: '商品审核', to: '/admin/listings/review', icon: DocumentChecked, permission: 'listing:approve' },
  { label: '仲裁中心', to: '/admin/disputes', icon: ScaleToOriginal, permission: 'dispute:view' },
  { label: '客服群聊', to: '/admin/chats', icon: ChatDotRound, permission: 'chat:view' },
  { label: '资金流水', to: '/admin/wallet-ledger', icon: Wallet, permission: 'wallet:view' },
  { label: '系统配置', to: '/admin/system-configs', icon: Operation, permission: 'system_config:view' },
  { label: '审计日志', to: '/admin/audit-logs', icon: Document, permission: 'audit_log:view' },
  { label: '管理员管理', to: '/admin/admin-users', icon: UserFilled, permission: 'admin_user:manage' },
  { label: '角色管理', to: '/admin/roles', icon: Setting, permission: 'role:manage' },
]

const navItems = computed(() => {
  if (adminSession.isSuperAdmin) return allNavItems
  return allNavItems.filter((item) => {
    if (!item.permission) return true
    return adminSession.hasPermission(item.permission)
  })
})

const activeMenu = computed(() => route.path)
const adminName = computed(() => adminSession.nickname || adminSession.username || '管理员')

async function handleLogout() {
  try {
    await logoutAdmin()
  } catch {
    // Local logout should still happen if the development API is unavailable.
  }
  adminSession.logout()
  ElMessage.success('已退出后台')
  await router.push('/admin/login')
}
</script>

<template>
  <div class="admin-shell" :class="{ 'admin-shell--collapsed': isCollapsed }">
    <aside class="admin-sidebar">
      <div class="admin-sidebar-header">
        <RouterLink class="admin-brand" to="/admin/dashboard">
          <span class="brand-mark">H</span>
          <span class="brand-text" v-show="!isCollapsed">哈夫币后台</span>
        </RouterLink>
        <el-icon class="collapse-btn" @click="isCollapsed = !isCollapsed">
          <Fold v-if="!isCollapsed" />
          <Expand v-else />
        </el-icon>
      </div>

      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapsed"
        :collapse-transition="false"
        router
        class="admin-menu"
      >
        <el-menu-item v-for="item in navItems" :key="item.to" :index="item.to">
          <el-icon><component :is="item.icon" /></el-icon>
          <template #title>{{ item.label }}</template>
        </el-menu-item>
      </el-menu>
    </aside>

    <section class="admin-workspace">
      <header class="admin-topbar">
        <div class="topbar-left">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/admin/dashboard' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item v-if="route.meta.title">{{ route.meta.title }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="topbar-right">
          <el-dropdown trigger="click">
            <span class="user-info">
              <el-avatar :size="32" :icon="User" />
              <span class="username">{{ adminName }}</span>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :icon="SwitchButton" @click="handleLogout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </header>
      <main class="admin-main">
        <slot />
      </main>
    </section>
  </div>
</template>

<style scoped>
.admin-shell {
  display: flex;
  height: 100vh;
  min-height: 100vh;
  background-color: #f5f7fa;
  overflow: hidden;
}

.admin-sidebar {
  width: 220px;
  height: 100vh;
  flex: none;
  background-color: #304156;
  transition: width 0.3s ease;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.admin-shell--collapsed .admin-sidebar {
  width: 64px;
}

.admin-sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #3d4e5f;
}

.admin-brand {
  display: flex;
  align-items: center;
  gap: 8px;
  text-decoration: none;
  color: #fff;
  overflow: hidden;
}

.brand-mark {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #409eff;
  border-radius: 4px;
  font-size: 18px;
  font-weight: 700;
  flex-shrink: 0;
}

.brand-text {
  font-size: 16px;
  font-weight: 600;
  white-space: nowrap;
}

.collapse-btn {
  color: #bfcbd9;
  cursor: pointer;
  font-size: 20px;
  flex-shrink: 0;
}

.collapse-btn:hover {
  color: #fff;
}

.admin-menu {
  flex: 1;
  min-height: 0;
  border-right: none;
  background-color: transparent;
  overflow-y: auto;
  overflow-x: hidden;
}

.admin-menu:not(.el-menu--collapse) {
  width: 100%;
}

:deep(.el-menu-item) {
  color: #bfcbd9;
}

:deep(.el-menu-item:hover) {
  background-color: #263445;
}

:deep(.el-menu-item.is-active) {
  color: #409eff;
  background-color: #263445;
}

.admin-workspace {
  flex: 1;
  min-width: 0;
  min-height: 0;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.admin-topbar {
  height: 56px;
  flex: none;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.topbar-left {
  display: flex;
  align-items: center;
}

.topbar-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  color: #606266;
}

.username {
  font-size: 14px;
}

.admin-main {
  flex: 1;
  min-height: 0;
  padding: 24px;
  overflow-y: auto;
}
</style>
