'use client'

import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import type { ReactNode } from 'react'
import { useEffect, useMemo, useRef, useState } from 'react'
import {
  Activity,
  AlertTriangle,
  BarChart3,
  Bell,
  Building2,
  ChevronRight,
  ClipboardList,
  Database,
  FileText,
  LayoutDashboard,
  Newspaper,
  Package,
  Percent,
  Search,
  ShieldCheck,
  SlidersHorizontal,
  UserCog,
  UsersRound,
  WalletCards,
} from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import { AdminMetricPanel, type AdminMetricItem } from '@/components/admin/AdminMetrics'
import { backend, getStaffToken, type StaffAccount } from '@/lib/backend'
import { safeInternalHref } from '@/lib/navigation'

type NavNode = {
  label: string
  href?: string
  icon?: LucideIcon
  disabled?: boolean
  permissions?: string[]
  activeExclusions?: string[]
  children?: NavNode[]
}

type NavSection = { label: string; hideLabel?: boolean; items: NavNode[] }

const sections: NavSection[] = [
  {
    label: '经营看板',
    items: [
      { label: '经营看板', href: '/admin', icon: LayoutDashboard, permissions: ['order:read', 'settlement:read', 'product:read', 'news:read', 'user:read', 'expert_profile:read', 'expert_application:read', 'expert_booking:read', 'site:read'] },
      { label: '编号搜索', href: '/admin/search', icon: Search, permissions: ['order:read', 'user:read', 'expert_profile:read', 'expert_application:read', 'expert_booking:read', 'cooperation:read'] },
    ],
  },
  {
    label: '产品与服务',
    hideLabel: true,
    items: [
      {
        label: '产品与服务',
        icon: Package,
        permissions: ['data_service:read', 'consulting:read', 'task:read', 'product:read', 'event:read', 'membership_plan:read', 'membership_benefit:read', 'membership_subscription:update', 'membership_entitlement:update', 'user:read'],
        children: [
          {
            label: '服务履约',
            icon: ClipboardList,
            permissions: ['data_service:read', 'consulting:read', 'task:read'],
            children: [
              { label: '数据服务需求', href: '/admin/data-service/requests', permissions: ['data_service:read'] },
              { label: '咨询服务需求', href: '/admin/consulting-requests', permissions: ['consulting:read'] },
              { label: '交付任务', href: '/admin/tasks', permissions: ['task:read'] },
            ],
          },
          {
            label: '产品管理',
            icon: BarChart3,
            permissions: ['product:read', 'event:read'],
            children: [
              { label: '智能体产品', href: '/admin/products/agents', permissions: ['product:read'] },
              { label: '课程产品', href: '/admin/products/courses', permissions: ['product:read'] },
              { label: '活动管理', href: '/admin/events', activeExclusions: ['/admin/events/checkin'], permissions: ['event:read'] },
            ],
          },
          {
            label: '会员运营',
            icon: WalletCards,
            permissions: ['membership_plan:read', 'membership_benefit:read', 'membership_subscription:update', 'membership_entitlement:update', 'product:read', 'user:read'],
            children: [
              { label: '会员方案', href: '/admin/products/membership', permissions: ['membership_plan:read', 'product:read'] },
              { label: '会员权益', href: '/admin/membership/benefits', permissions: ['membership_benefit:read', 'membership_entitlement:update', 'product:read'] },
            ],
          },
        ],
      },
    ],
  },
  {
    label: '现场核销',
    items: [
      { label: '现场核销', href: '/admin/events/checkin', icon: UsersRound, permissions: ['event:checkin', 'event_checkin:update', 'course_checkin:update'] },
    ],
  },
  {
    label: '内容与营销',
    items: [
      {
        label: '内容发布',
        icon: Newspaper,
        permissions: ['news:read', 'news_category:read'],
        children: [
          { label: '资讯发布', href: '/admin/news', permissions: ['news:read'] },
          { label: '资讯分类', href: '/admin/content/news/categories', permissions: ['news_category:read', 'news:read'] },
        ],
      },
      {
        label: '页面配置',
        icon: FileText,
        permissions: ['site:read', 'site_block:read', 'site_recommendation:read', 'consulting_option:read'],
        children: [
          { label: '首页配置', href: '/admin/site/home', icon: FileText, permissions: ['site:read'] },
          { label: '推荐位配置', href: '/admin/site/recommendations', icon: SlidersHorizontal, permissions: ['site_recommendation:read', 'site:read'] },
          { label: '数据页面维护', href: '/admin/data-service/page', icon: Database, permissions: ['data_service_page:read', 'data_page:read', 'product:read'] },
          { label: '数据服务选项', href: '/admin/data-service/options', icon: SlidersHorizontal, permissions: ['data_service_option:read', 'data_page:read'] },
          { label: '关于我们配置', href: '/admin/site/about', icon: FileText, permissions: ['site:read'] },
          { label: '规划咨询配置', href: '/admin/site/consulting', icon: FileText, permissions: ['site:read', 'consulting_option:read'] },
        ],
      },
      {
        label: '线索与营销',
        icon: ClipboardList,
        permissions: ['cooperation:read', 'coupon:read', 'notification:read'],
        children: [
          { label: '合作咨询', href: '/admin/site/cooperation', icon: ClipboardList, permissions: ['cooperation:read'] },
          { label: '优惠码', href: '/admin/coupons', icon: Percent, permissions: ['coupon:read'] },
          { label: '消息通知', href: '/admin/notifications', icon: Bell, permissions: ['notification:read'] },
        ],
      },
      {
        label: '协议法务',
        icon: ShieldCheck,
        permissions: ['site:read'],
        children: [
          { label: '协议配置', href: '/admin/site/agreements', permissions: ['site:read'] },
        ],
      },
    ],
  },
  {
    label: '专家中心',
    items: [
      {
        label: '专家中心',
        icon: UsersRound,
        permissions: ['expert_profile:read', 'expert_application:read', 'expert_booking:read', 'expert_schedule:read', 'settlement:read'],
        children: [
          { label: '专家资源库', href: '/admin/experts', activeExclusions: ['/admin/experts/directions'], permissions: ['expert_profile:read'] },
          { label: '专家申请审核', href: '/admin/expert-applications', permissions: ['expert_application:read'] },
          { label: '专家预约管理', href: '/admin/expert-bookings', permissions: ['expert_booking:read'] },
          { label: '专家排期', href: '/admin/schedules', permissions: ['expert_schedule:read'] },
          { label: '专家方向配置', href: '/admin/experts/directions', permissions: ['expert_profile:read'] },
        ],
      },
    ],
  },
  {
    label: '财务中心',
    items: [
      {
        label: '交易管理',
        icon: ClipboardList,
        permissions: ['order:read', 'payment:read'],
        children: [
          { label: '订单流水', href: '/admin/orders', permissions: ['order:read'] },
          { label: '支付记录', href: '/admin/payments', permissions: ['payment:read'] },
        ],
      },
      {
        label: '财务结算',
        icon: WalletCards,
        permissions: ['settlement:read', 'invoice:read', 'reconcile:export'],
        children: [
          { label: '专家分账', href: '/admin/settlements', permissions: ['settlement:read'] },
          { label: '提现申请', href: '/admin/expert-withdrawals', permissions: ['settlement:read'] },
          { label: '平台收入', href: '/admin/revenue', permissions: ['settlement:read'] },
          { label: '发票中心', href: '/admin/invoices', permissions: ['invoice:read'] },
          { label: '对账导出', href: '/admin/reconcile', permissions: ['reconcile:export'] },
        ],
      },
    ],
  },
  {
    label: '组织权限',
    items: [
      { label: '组织架构', href: '/admin/org', icon: Building2, permissions: ['org:read'] },
      { label: '员工账号', href: '/admin/staff-accounts', icon: UserCog, permissions: ['staff:read'] },
      { label: '角色与权限', href: '/admin/staff-roles', icon: ShieldCheck, permissions: ['role:read'] },
      { label: '操作审计', href: '/admin/staff-audit', icon: Activity, permissions: ['audit:read'] },
    ],
  },
  {
    label: '用户与会员',
    items: [
      { label: '用户档案', href: '/admin/users', icon: UsersRound, permissions: ['user:read'] },
      { label: '会员订阅', href: '/admin/memberships', icon: WalletCards, permissions: ['membership_subscription:read', 'membership_subscription:update'] },
      { label: '权益额度账户', href: '/admin/membership/entitlements', icon: SlidersHorizontal, permissions: ['membership_entitlement:read', 'membership_entitlement:update', 'user:read'] },
      { label: '通行证核验', href: '/admin/passports', icon: Search, permissions: ['passport:read', 'user:read'] },
    ],
  },
  {
    label: '系统运维',
    items: [
      { label: '系统健康', href: '/admin/system', icon: Activity, permissions: ['operations:read'] },
      { label: '异常中心', href: '/admin/exceptions', icon: AlertTriangle, permissions: ['operations:read'] },
      { label: '配置检查', href: '/admin/ops/config-checks', icon: SlidersHorizontal, permissions: ['config_check:read', 'operations:read'] },
      { label: '运维任务', href: '/admin/ops/jobs', icon: ClipboardList, permissions: ['ops_job:read', 'operations:read'] },
    ],
  },
]

export function hasAdminPermission(account: StaffAccount | null, permissions?: string | string[]) {
  if (!account) return false
  const permissionList = Array.isArray(permissions) ? permissions : permissions ? [permissions] : []
  if (!permissionList.length) return true
  if (account.permissions?.includes('*')) return true
  return permissionList.some((permission) => account.permissions?.includes(permission))
}

function visibleNavNode(item: NavNode, account: StaffAccount): NavNode | null {
  const children = item.children?.map((child) => visibleNavNode(child, account)).filter(Boolean) as NavNode[] | undefined
  if (children?.length) return { ...item, children }
  return hasAdminPermission(account, item.permissions) ? { ...item, children } : null
}

function visibleSectionsFor(account: StaffAccount): NavSection[] {
  return sections
    .map((section) => ({
      ...section,
      items: section.items.map((item) => visibleNavNode(item, account)).filter(Boolean) as NavNode[],
    }))
    .filter((section) => section.items.length > 0)
}

function hasAdminHref(item: NavNode): boolean {
  return Boolean(item.href?.startsWith('/admin') || item.children?.some(hasAdminHref))
}

function canAccessAdmin(account: StaffAccount) {
  if (account.defaultEntry?.startsWith('/admin')) return true
  return visibleSectionsFor(account).some((section) => section.items.some(hasAdminHref))
}

function isActive(currentHref: string, item: NavNode) {
  if (!item.href || item.disabled) return false
  const pathname = currentHref.split('?')[0]
  if (item.href.includes('?')) return currentHref === item.href
  const base = item.href.split('?')[0]
  if (item.activeExclusions?.some((excluded) => pathname === excluded || pathname.startsWith(`${excluded}/`))) return false
  if (base === '/admin') return pathname === '/admin'
  return pathname === base || pathname.startsWith(`${base}/`)
}

function hasActiveChild(currentHref: string, item: NavNode): boolean {
  return Boolean(item.children?.some((child) => isActive(currentHref, child) || hasActiveChild(currentHref, child)))
}

function collectActiveBranchKeys(sections: NavSection[], currentHref: string) {
  const keys = new Set<string>()

  function visit(item: NavNode, itemKey: string): boolean {
    const selfActive = isActive(currentHref, item)
    const childActive: boolean = item.children?.some((child, index) => visit(child, `${itemKey}/${index}:${child.label}:${child.href || 'group'}`)) || false

    if (childActive) keys.add(itemKey)
    return selfActive || childActive
  }

  sections.forEach((section) => {
    section.items.forEach((item, index) => {
      visit(item, `${section.label}/${index}:${item.label}:${item.href || 'group'}`)
    })
  })

  return keys
}

function collectActiveSectionKeys(sections: NavSection[], currentHref: string) {
  return new Set(
    sections
      .filter((section) => section.items.some((item) => isActive(currentHref, item) || hasActiveChild(currentHref, item)))
      .map((section) => section.label),
  )
}

function NavItem({
  item,
  itemKey,
  depth = 0,
  currentHref,
  expandedKeys,
  collapsedKeys,
  activeBranchKeys,
  onToggleGroup,
  onNavigate,
}: {
  item: NavNode
  itemKey: string
  depth?: number
  currentHref: string
  expandedKeys: Set<string>
  collapsedKeys: Set<string>
  activeBranchKeys: Set<string>
  onToggleGroup: (itemKey: string, expanded: boolean, activeBranch: boolean) => void
  onNavigate: (href: string) => void
}) {
  const active = isActive(currentHref, item)
  const childActive = hasActiveChild(currentHref, item)
  const activeBranch = activeBranchKeys.has(itemKey)
  const expanded = Boolean(item.children?.length) && (expandedKeys.has(itemKey) || (activeBranch && !collapsedKeys.has(itemKey)))
  const Icon = item.icon
  const content = (
    <span
      data-admin-nav-active={active ? 'true' : undefined}
      className={`flex h-8 min-w-0 items-center gap-2 px-2.5 text-xs font-bold ${
        active
          ? 'bg-ink text-white'
          : childActive
            ? 'bg-bg text-ink'
            : item.disabled
              ? 'text-soft opacity-55'
              : 'text-muted hover:bg-bg hover:text-ink'
      }`}
      style={{ paddingLeft: depth ? `${12 + depth * 14}px` : undefined }}
    >
      {Icon ? <Icon className="h-3.5 w-3.5 shrink-0" /> : <span className="h-1.5 w-1.5 shrink-0 rounded-full bg-current opacity-45" />}
      <span className="min-w-0 flex-1 truncate">{item.label}</span>
      {item.disabled ? <span className="text-[10px] font-extrabold text-soft">待接</span> : item.children ? <ChevronRight className={`h-3 w-3 shrink-0 text-soft transition-transform ${expanded ? 'rotate-90' : ''}`} /> : null}
    </span>
  )

  return (
    <div>
      {item.children?.length ? (
        <button
          type="button"
          className="block w-full text-left"
          onClick={() => onToggleGroup(itemKey, expanded, activeBranch)}
          aria-expanded={expanded}
        >
          {content}
        </button>
      ) : item.href && !item.disabled ? (
        <Link href={item.href} onClick={() => onNavigate(item.href || '')}>{content}</Link>
      ) : (
        <div>{content}</div>
      )}
      {item.children && expanded && (
        <div className="mt-1 space-y-0.5">
          {item.children.map((child, index) => (
            <NavItem
              key={`${itemKey}/${index}:${child.label}:${child.href || 'group'}`}
              item={child}
              itemKey={`${itemKey}/${index}:${child.label}:${child.href || 'group'}`}
              depth={depth + 1}
              currentHref={currentHref}
              expandedKeys={expandedKeys}
              collapsedKeys={collapsedKeys}
              activeBranchKeys={activeBranchKeys}
              onToggleGroup={onToggleGroup}
              onNavigate={onNavigate}
            />
          ))}
        </div>
      )}
    </div>
  )
}

export function AdminShell({
  title,
  description,
  topbarMetrics,
  children,
}: {
  title: string
  description?: string
  topbarMetrics?: AdminMetricItem[]
  children: ReactNode
}) {
  const pathname = usePathname()
  const router = useRouter()
  const [account, setAccount] = useState<StaffAccount | null>(null)
  const [checking, setChecking] = useState(true)
  const [currentHref, setCurrentHref] = useState(pathname)
  const [expandedSectionKeys, setExpandedSectionKeys] = useState<Set<string>>(new Set())
  const [collapsedSectionKeys, setCollapsedSectionKeys] = useState<Set<string>>(new Set())
  const [expandedKeys, setExpandedKeys] = useState<Set<string>>(new Set())
  const [collapsedKeys, setCollapsedKeys] = useState<Set<string>>(new Set())
  const navRef = useRef<HTMLElement | null>(null)

  useEffect(() => {
    queueMicrotask(async () => {
      if (!getStaffToken()) {
        router.replace(`/login?redirect=${encodeURIComponent(pathname)}`)
        return
      }
      try {
        const current = await backend.staffMe()
        if (!canAccessAdmin(current)) {
          router.replace(safeInternalHref(current.defaultEntry || '/staff', '/staff'))
          return
        }
        setAccount(current)
      } catch {
        router.replace(`/login?redirect=${encodeURIComponent(pathname)}`)
      } finally {
        setChecking(false)
      }
    })
  }, [pathname, router])

  useEffect(() => {
    const syncHref = () => setCurrentHref(`${window.location.pathname}${window.location.search}`)
    syncHref()
    window.addEventListener('popstate', syncHref)
    return () => window.removeEventListener('popstate', syncHref)
  }, [pathname])

  const visibleSections = useMemo(() => account ? visibleSectionsFor(account) : [], [account])
  const activeBranchKeys = useMemo(() => collectActiveBranchKeys(visibleSections, currentHref), [currentHref, visibleSections])
  const activeSectionKeys = useMemo(() => collectActiveSectionKeys(visibleSections, currentHref), [currentHref, visibleSections])
  const hasManualExpandedSection = expandedSectionKeys.size > 0

  useEffect(() => {
    setExpandedKeys(new Set())
    setCollapsedKeys(new Set())
    setExpandedSectionKeys(new Set())
    setCollapsedSectionKeys(new Set())
  }, [currentHref])

  useEffect(() => {
    const frame = window.requestAnimationFrame(() => {
      navRef.current?.querySelector<HTMLElement>('[data-admin-nav-active="true"]')?.scrollIntoView({
        block: 'center',
        inline: 'nearest',
      })
    })

    return () => window.cancelAnimationFrame(frame)
  }, [currentHref, activeBranchKeys])

  function handleToggleGroup(itemKey: string, expanded: boolean, activeBranch: boolean) {
    setExpandedKeys((keys) => {
      const next = new Set(keys)
      if (expanded) next.delete(itemKey)
      else next.add(itemKey)
      return next
    })
    setCollapsedKeys((keys) => {
      const next = new Set(keys)
      if (expanded && activeBranch) next.add(itemKey)
      else next.delete(itemKey)
      return next
    })
  }

  function handleToggleSection(sectionKey: string, expanded: boolean, activeSection: boolean) {
    setExpandedSectionKeys(() => (expanded ? new Set<string>() : new Set([sectionKey])))
    setCollapsedSectionKeys((keys) => {
      const next = new Set(keys)
      if (expanded && activeSection) next.add(sectionKey)
      else next.delete(sectionKey)
      return next
    })
  }

  if (checking || !account) {
    return (
      <section className="grid min-h-screen place-items-center bg-[#f5f7fb] px-6">
        <div className="text-sm font-extrabold text-muted">正在验证管理端权限...</div>
      </section>
    )
  }

  return (
    <section className="min-h-screen bg-[#f5f7fb]">
      <aside className="fixed inset-y-0 left-0 z-50 w-[248px] border-r border-line bg-white shadow-[8px_0_24px_rgba(15,23,42,0.03)]">
        <div className="flex h-full flex-col">
          <div className="border-b border-line px-3 py-2.5">
            <div className="text-[10px] font-extrabold tracking-[0.16em] text-soft">ADMIN</div>
            <div className="mt-0.5 truncate text-xs font-extrabold text-ink">大数据研究院管理端</div>
          </div>
          <nav ref={navRef} className="min-h-0 flex-1 overflow-y-auto px-2.5 py-2.5">
            <div className="space-y-1">
              {visibleSections.map((section) => (
                <div key={section.label} className="border-b border-line/70 pb-1 last:border-b-0">
                  {(() => {
                    const sectionActive = activeSectionKeys.has(section.label)
                    const sectionExpanded = expandedSectionKeys.has(section.label) || (!hasManualExpandedSection && sectionActive && !collapsedSectionKeys.has(section.label))

                    return (
                      <>
                        <button
                          type="button"
                          className={`flex h-8 w-full items-center gap-2 px-2.5 text-left text-xs font-extrabold ${
                            sectionActive ? 'bg-bg text-ink' : 'text-muted hover:bg-bg hover:text-ink'
                          }`}
                          onClick={() => handleToggleSection(section.label, sectionExpanded, sectionActive)}
                          aria-expanded={sectionExpanded}
                        >
                          <span className="min-w-0 flex-1 truncate">{section.label}</span>
                          <ChevronRight className={`h-3.5 w-3.5 shrink-0 text-soft transition-transform ${sectionExpanded ? 'rotate-90' : ''}`} />
                        </button>
                        {sectionExpanded && (
                          <div className="mt-1 space-y-0.5">
                    {section.items.map((item, index) => {
                      const itemKey = `${section.label}/${index}:${item.label}:${item.href || 'group'}`

                      return (
                        <NavItem
                          key={itemKey}
                          item={item}
                          itemKey={itemKey}
                          currentHref={currentHref}
                          expandedKeys={expandedKeys}
                          collapsedKeys={collapsedKeys}
                          activeBranchKeys={activeBranchKeys}
                          onToggleGroup={handleToggleGroup}
                          onNavigate={setCurrentHref}
                        />
                      )
                    })}
                          </div>
                        )}
                      </>
                    )
                  })()}
                </div>
              ))}
            </div>
          </nav>
        </div>
      </aside>

      <main className="admin-shell-main min-h-screen pl-[248px]">
        <div className="sticky top-0 z-30 border-b border-line bg-white/95 px-3 py-2 backdrop-blur">
          <div className="flex items-center justify-between gap-4">
            <div className="min-w-0">
              <h1 className="truncate text-sm font-extrabold text-ink">{title}</h1>
              {description && <p className="mt-0.5 truncate text-[11px] font-bold text-muted">{description}</p>}
            </div>
            <div className="flex min-w-0 shrink-0 justify-end gap-3">
              <Link href="/" className="h-8 shrink-0 border border-line px-3 py-1.5 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">返回前台</Link>
            </div>
          </div>
        </div>
        <div className="admin-compact px-2.5 py-2">
          {topbarMetrics?.length ? (
            <AdminMetricPanel items={topbarMetrics} className="mb-2" />
          ) : null}
          {children}
        </div>
      </main>
    </section>
  )
}
