<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, updateSupportStatus } from '@/features/admin'
import { useAdminSessionStore } from '@/stores/adminSession'

const router = useRouter()
const route = useRoute()
const adminSession = useAdminSessionStore()
const isCollapsed = ref(false)
const updatingStatus = 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 || '管理员')
const supportStatus = computed(() => adminSession.supportStatus || 'offline')
const hasChatPermission = computed(() => adminSession.hasPermission('chat:view'))

const statusLabels: Record<string, string> = {
  online: '在线',
  offline: '离线',
  busy: '忙碌',
}

const statusColors: Record<string, string> = {
  online: '#10b981',
  offline: '#9ca3af',
  busy: '#f59e0b',
}

async function handleStatusChange(status: 'online' | 'offline' | 'busy') {
  if (updatingStatus.value) return
  updatingStatus.value = true
  try {
    await updateSupportStatus(status)
    adminSession.setSupportStatus(status)
    ElMessage.success(`已切换为${statusLabels[status]}`)
  } catch {
    ElMessage.error('状态更新失败')
  } finally {
    updatingStatus.value = false
  }
}

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 v-if="hasChatPermission" trigger="click" @command="handleStatusChange" :disabled="updatingStatus">
            <span class="status-badge" :style="{ borderColor: statusColors[supportStatus] }">
              <span class="status-dot" :style="{ backgroundColor: statusColors[supportStatus] }"></span>
              <span class="status-text">{{ statusLabels[supportStatus] }}</span>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="online">
                  <span class="status-dot" style="background-color: #10b981;"></span>
                  在线
                </el-dropdown-item>
                <el-dropdown-item command="busy">
                  <span class="status-dot" style="background-color: #f59e0b;"></span>
                  忙碌
                </el-dropdown-item>
                <el-dropdown-item command="offline">
                  <span class="status-dot" style="background-color: #9ca3af;"></span>
                  离线
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <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;
  gap: 16px;
}

.status-badge {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border: 1px solid;
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.2s;
}

.status-badge:hover {
  background-color: #f5f7fa;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  display: inline-block;
}

.status-text {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

:deep(.el-dropdown-menu__item .status-dot) {
  margin-right: 8px;
}

.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>
