<script setup lang="ts">
import {
  Bell,
  Briefcase,
  ChatDotRound,
  Coin,
  DataLine,
  Document,
  DocumentChecked,
  Expand,
  Fold,
  House,
  Lock,
  Message,
  Money,
  Operation,
  Picture,
  ScaleToOriginal,
  Service,
  Shop,
  Setting,
  SwitchButton,
  Tickets,
  Tools,
  User,
  UserFilled,
  Wallet,
  CreditCard,
} from '@element-plus/icons-vue'
import { ElMessage, ElSubMenu } from 'element-plus'
import type { Component } from 'vue'
import { computed, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { changeAdminPassword, logoutAdmin, updateSupportStatus } from '@/features/admin'
import { useAdminNotificationUnreadCount } from '@/features/admin/composables/useAdminNotificationUnreadCount'
import { useAdminSessionStore } from '@/stores/adminSession'
import { adminPath, ADMIN_DASHBOARD_PATH, ADMIN_LOGIN_PATH } from '@/shared/utils/adminPath'
import { readError } from '@/shared/utils/error'

const router = useRouter()
const route = useRoute()
const adminSession = useAdminSessionStore()
const isCollapsed = ref(false)
const updatingStatus = ref(false)
const passwordSubmitting = ref(false)
const passwordForm = reactive({
  old_password: '',
  new_password: '',
  confirm_password: '',
})
const shouldForcePasswordChange = computed(
  () => adminSession.passwordMustChange && adminSession.isSuperAdmin
)

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

interface NavGroup {
  label: string
  index: string
  icon: Component
  children: NavItem[]
}

const allNavGroups: NavGroup[] = [
  {
    label: '工作台',
    index: 'workspace',
    icon: House,
    children: [
      { label: '仪表盘', to: ADMIN_DASHBOARD_PATH, icon: DataLine, permission: 'dashboard:view' },
    ],
  },
  {
    label: '业务管理',
    index: 'business',
    icon: Briefcase,
    children: [
      { label: '用户管理', to: adminPath('users'), icon: User, permission: 'user:view' },
      { label: '订单管理', to: adminPath('orders'), icon: Tickets, permission: 'order:view' },
      { label: '商品管理', to: adminPath('listings'), icon: Shop, permission: 'listing:view' },
      {
        label: '商品审核',
        to: adminPath('listings/review'),
        icon: DocumentChecked,
        permission: 'listing:approve',
      },
    ],
  },
  {
    label: '客服与风控',
    index: 'support-risk',
    icon: Service,
    children: [
      {
        label: '仲裁中心',
        to: adminPath('disputes'),
        icon: ScaleToOriginal,
        permission: 'dispute:view',
      },
      { label: '客服群聊', to: adminPath('chats'), icon: ChatDotRound, permission: 'chat:view' },
      { label: '二维码池', to: adminPath('qrcode-pool'), icon: Picture, permission: 'chat:view' },
      { label: '客服分组', to: adminPath('support-groups'), icon: User, permission: 'chat:manage' },
    ],
  },
  {
    label: '财务管理',
    index: 'finance',
    icon: Coin,
    children: [
      {
        label: '财务仪表盘',
        to: adminPath('finance/dashboard'),
        icon: DataLine,
        permission: 'wallet:view',
      },
      {
        label: '财务明细',
        to: adminPath('finance/details'),
        icon: Document,
        permission: 'wallet:view',
      },
      {
        label: '资金流水',
        to: adminPath('wallet-ledger'),
        icon: Wallet,
        permission: 'wallet:view',
      },
      { label: '支付流水', to: adminPath('payments'), icon: CreditCard, permission: 'wallet:view' },
      {
        label: '提现审核',
        to: adminPath('withdrawals'),
        icon: Money,
        permission: 'withdrawal:list',
      },
      {
        label: '支付配置',
        to: adminPath('payment-configs'),
        icon: CreditCard,
        permission: 'payment_config:list',
      },
    ],
  },
  {
    label: '内容与配置',
    index: 'content-config',
    icon: Tools,
    children: [
      {
        label: '公告管理',
        to: adminPath('announcements'),
        icon: Bell,
        permission: 'announcement:view',
      },
      {
        label: '通知中心',
        to: adminPath('notifications'),
        icon: Message,
        permission: 'notification:view',
      },
      {
        label: '系统配置',
        to: adminPath('system-configs'),
        icon: Operation,
        permission: 'system_config:view',
      },
    ],
  },
  {
    label: '系统权限',
    index: 'system-auth',
    icon: Lock,
    children: [
      {
        label: '审计日志',
        to: adminPath('audit-logs'),
        icon: Document,
        permission: 'audit_log:view',
      },
      {
        label: '管理员管理',
        to: adminPath('admin-users'),
        icon: UserFilled,
        permission: 'admin_user:manage',
      },
      { label: '角色管理', to: adminPath('roles'), icon: Setting, permission: 'role:manage' },
    ],
  },
]

const allNavItems = allNavGroups.flatMap(group => group.children)

function canAccessNavItem(item: NavItem) {
  if (adminSession.isSuperAdmin) return true
  if (!item.permission) return true
  return adminSession.hasPermission(item.permission)
}

const navGroups = computed(() => {
  return allNavGroups
    .map(group => ({
      ...group,
      children: group.children.filter(item => canAccessNavItem(item)),
    }))
    .filter(group => group.children.length > 0)
})

const activeMenu = computed(() => {
  const currentPath = route.path
  const matchedItem = allNavItems
    .slice()
    .sort((a, b) => b.to.length - a.to.length)
    .find(item => currentPath === item.to || currentPath.startsWith(`${item.to}/`))

  return matchedItem?.to || currentPath
})

const defaultOpeneds = computed(() => {
  const activeGroup = allNavGroups.find(group =>
    group.children.some(item => item.to === activeMenu.value)
  )

  return activeGroup ? [activeGroup.index] : []
})

const adminName = computed(() => adminSession.nickname || adminSession.username || '管理员')
const adminRoleText = computed(() => {
  if (adminSession.isSuperAdmin) return '超级管理员'
  const names = adminSession.roles.map(role => role.name).filter(Boolean)
  return names.join(' / ') || '管理员'
})
const supportStatus = computed(() => adminSession.supportStatus || 'offline')
const hasChatPermission = computed(() => adminSession.hasPermission('chat:view'))
const hasNotificationPermission = computed(
  () => adminSession.isSuperAdmin || adminSession.hasPermission('notification:view')
)
const {
  unreadCount: adminNotificationUnreadCount,
  unreadLabel: adminNotificationUnreadLabel,
} = useAdminNotificationUnreadCount(route)

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_PATH)
}

function passwordStrongEnough(value: string) {
  return value.length >= 8 && /[A-Za-z]/.test(value) && /\d/.test(value)
}

async function handleForcedPasswordChange() {
  if (!passwordForm.old_password || !passwordForm.new_password) {
    ElMessage.error('请输入原密码和新密码')
    return
  }
  if (!passwordStrongEnough(passwordForm.new_password)) {
    ElMessage.error('新密码至少 8 位且需包含字母和数字')
    return
  }
  if (passwordForm.new_password !== passwordForm.confirm_password) {
    ElMessage.error('两次输入的新密码不一致')
    return
  }
  passwordSubmitting.value = true
  try {
    await changeAdminPassword({
      old_password: passwordForm.old_password,
      new_password: passwordForm.new_password,
    })
    ElMessage.success('密码已修改，请重新登录')
    adminSession.logout()
    await router.replace(ADMIN_LOGIN_PATH)
  } catch (error) {
    ElMessage.error(readError(error, '密码修改失败'))
  } finally {
    passwordSubmitting.value = false
  }
}
</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_PATH">
          <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"
        :default-openeds="defaultOpeneds"
        :collapse="isCollapsed"
        :collapse-transition="false"
        unique-opened
        router
        class="admin-menu"
      >
        <el-sub-menu
          v-for="group in navGroups"
          :key="group.index"
          :index="group.index"
          popper-class="admin-menu-popper"
        >
          <template #title>
            <el-icon><component :is="group.icon" /></el-icon>
            <span>{{ group.label }}</span>
          </template>
          <el-menu-item v-for="item in group.children" :key="item.to" :index="item.to">
            <el-icon><component :is="item.icon" /></el-icon>
            <template #title>{{ item.label }}</template>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>

      <div class="admin-sidebar-footer">
        <RouterLink
          v-if="hasNotificationPermission"
          class="sidebar-notification"
          :to="adminPath('notifications')"
        >
          <span class="sidebar-notification-icon">
            <el-icon><Message /></el-icon>
            <em v-if="adminNotificationUnreadCount > 0" class="sidebar-badge">
              {{ adminNotificationUnreadLabel }}
            </em>
          </span>
          <span v-show="!isCollapsed" class="sidebar-notification-text">通知中心</span>
        </RouterLink>
        <el-dropdown
          v-if="hasChatPermission"
          trigger="click"
          @command="handleStatusChange"
          :disabled="updatingStatus"
        >
          <span class="sidebar-status" :style="{ borderColor: statusColors[supportStatus] }">
            <span
              class="status-dot"
              :style="{ backgroundColor: statusColors[supportStatus] }"
            ></span>
            <span v-show="!isCollapsed" 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="sidebar-user">
            <el-avatar :size="32" :icon="User" />
            <span v-show="!isCollapsed" class="sidebar-user-text">
              <strong>{{ adminName }}</strong>
              <small>{{ adminRoleText }}</small>
            </span>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :icon="SwitchButton" @click="handleLogout"
                >退出登录</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </aside>

    <section class="admin-workspace">
      <main class="admin-main">
        <slot />
      </main>
    </section>

    <el-dialog
      :model-value="shouldForcePasswordChange"
      title="修改初始密码"
      width="420px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      append-to-body
      class="force-password-dialog"
    >
      <el-form class="force-password-form" label-position="top" @submit.prevent>
        <el-form-item label="原密码">
          <el-input
            v-model="passwordForm.old_password"
            type="password"
            show-password
            autocomplete="current-password"
          />
        </el-form-item>
        <el-form-item label="新密码">
          <el-input
            v-model="passwordForm.new_password"
            type="password"
            show-password
            autocomplete="new-password"
          />
        </el-form-item>
        <el-form-item label="确认新密码">
          <el-input
            v-model="passwordForm.confirm_password"
            type="password"
            show-password
            autocomplete="new-password"
            @keyup.enter="handleForcedPasswordChange"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button :disabled="passwordSubmitting" @click="handleLogout">退出登录</el-button>
        <el-button type="primary" :loading="passwordSubmitting" @click="handleForcedPasswordChange">
          确认修改
        </el-button>
      </template>
    </el-dialog>
  </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 {
  --el-menu-bg-color: transparent;
  --el-menu-text-color: #bfcbd9;
  --el-menu-active-color: #409eff;
  --el-menu-hover-bg-color: #263445;

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

.admin-sidebar-footer {
  display: grid;
  flex: none;
  gap: 10px;
  padding: 12px;
  border-top: 1px solid #3d4e5f;
  background: rgba(16, 24, 39, 0.18);
}

.admin-shell--collapsed .admin-sidebar-footer {
  padding: 10px 8px;
}

.sidebar-notification {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  min-height: 32px;
  padding: 0 10px;
  border: 1px solid rgba(64, 158, 255, 0.35);
  border-radius: 8px;
  color: #d7dfec;
  text-decoration: none;
  transition:
    background-color 0.2s,
    border-color 0.2s;
}

.sidebar-notification:hover,
.sidebar-notification.router-link-active {
  background-color: rgba(64, 158, 255, 0.14);
  border-color: rgba(64, 158, 255, 0.8);
  color: #fff;
}

.admin-shell--collapsed .sidebar-notification {
  padding: 0;
}

.sidebar-notification-icon {
  position: relative;
  display: grid;
  width: 20px;
  height: 20px;
  place-items: center;
}

.sidebar-notification-text {
  font-size: 13px;
  font-weight: 700;
}

.sidebar-badge {
  position: absolute;
  top: -8px;
  right: -13px;
  min-width: 16px;
  height: 16px;
  padding: 0 4px;
  border: 2px solid #304156;
  border-radius: 999px;
  background: #ef4444;
  color: #fff;
  font-size: 10px;
  font-style: normal;
  font-weight: 800;
  line-height: 12px;
  text-align: center;
  box-sizing: border-box;
}

.sidebar-status {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 7px;
  width: 100%;
  min-height: 30px;
  padding: 0 10px;
  border: 1px solid;
  border-radius: 8px;
  color: #d7dfec;
  cursor: pointer;
  transition:
    background-color 0.2s,
    border-color 0.2s;
}

.sidebar-status:hover {
  background-color: rgba(255, 255, 255, 0.08);
}

.admin-shell--collapsed .sidebar-status {
  padding: 0;
}

.sidebar-user {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
  width: 100%;
  padding: 8px;
  border-radius: 10px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.sidebar-user:hover {
  background-color: rgba(255, 255, 255, 0.08);
}

.admin-shell--collapsed .sidebar-user {
  justify-content: center;
  padding: 8px 0;
}

.sidebar-user-text {
  display: grid;
  min-width: 0;
  gap: 2px;
}

.sidebar-user-text strong {
  overflow: hidden;
  color: #fff;
  font-size: 13px;
  line-height: 18px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.sidebar-user-text small {
  overflow: hidden;
  color: #8fa0ba;
  font-size: 12px;
  line-height: 16px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

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

:deep(.el-menu) {
  background-color: transparent;
}

:deep(.el-sub-menu__title) {
  color: #bfcbd9;
}

:deep(.el-sub-menu__title:hover) {
  background-color: #263445;
}

:deep(.el-sub-menu.is-active > .el-sub-menu__title) {
  color: #409eff;
}

: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;
}

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

:deep(.el-menu--inline .el-menu-item) {
  height: 46px;
  background-color: #263445;
  font-size: 14px;
}

:deep(.el-menu--inline .el-menu-item:hover),
:deep(.el-menu--inline .el-menu-item.is-active) {
  background-color: #1f2d3d;
}

:global(.admin-menu-popper) {
  --el-menu-bg-color: #304156;
  --el-menu-text-color: #bfcbd9;
  --el-menu-active-color: #409eff;
  --el-menu-hover-bg-color: #263445;
}

:global(.admin-menu-popper .el-menu) {
  border-right: none;
  background-color: #304156;
}

:global(.admin-menu-popper .el-menu-item) {
  color: #bfcbd9;
}

:global(.admin-menu-popper .el-menu-item:hover),
:global(.admin-menu-popper .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;
}

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

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

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

.admin-main {
  flex: 1;
  min-height: 0;
  padding: 18px 24px 24px;
  overflow-y: auto;
}

:global(.force-password-dialog) {
  max-width: calc(100vw - 32px);
}

.force-password-form {
  display: grid;
  gap: 2px;
}
</style>
