import { NavLink, useNavigate } from 'react-router-dom'
import { useState } from 'react'
import { useAuth } from '../contexts/AuthContext.jsx'
import { useChatOverlay } from '../contexts/ChatOverlayContext.jsx'
import { FEATURES } from '../featureFlags.js'
import { PRODUCT, isAdminUser, isSuperAdminUser } from '../productConfig.js'
import { getOverlayLayout } from '../services/overlayLayout.js'
import {
  BarChart3,
  CheckCircle,
  ChevronLeft,
  ChevronRight,
  FileText,
  Globe,
  KeyRound,
  Library,
  LogOut,
  MessageSquareText,
  Plug,
  ScrollText,
  Sparkles,
  User,
  Users,
  Workflow,
  ShieldCheck,
} from 'lucide-react'

// adminLevel: 'admin' = 管理员及以上可见；'superAdmin'（或 adminOnly: true）= 仅超级管理员可见
const NAV_GROUPS = [
  {
    title: '工作区',
    items: [
      { to: '/all-skills',    label: '全部 Skill',  icon: <Globe size={18} /> },
      { to: '/my-skills',     label: '我的 Skill',  icon: <User size={18} /> },
      { to: '/upload',        label: '上传 Skill',  icon: <FileText size={18} /> },
      { to: '/create-skill-chat', label: '创建 Skill',  icon: <Sparkles size={18} />, adminLevel: 'admin', overlay: 'create' },
      { to: '/skill-eval',    label: '质量评测',  icon: <CheckCircle size={18} />, flag: 'skillEval', adminLevel: 'admin', overlay: 'eval' },
      { to: '/api-access',    label: 'API 接入',     icon: <Plug size={18} /> },
    ]
  },
  {
    title: '知识库',
    module: 'knowledge',
    items: [
      { to: '/knowledge/files', label: '全部文件', icon: <Library size={18} /> },
      { to: '/knowledge/my-files', label: '我的文件', icon: <FileText size={18} /> },
      { to: '/knowledge/qa', label: '知识问答', icon: <MessageSquareText size={18} /> },
    ]
  },
  {
    title: '实用功能',
    module: 'aiFlowDrawing',
    items: [
      {
        to: '/ai-flow-drawing',
        label: 'AI绘图',
        icon: <Workflow size={18} />,
        adminLevel: 'superAdmin',
        tooltip: '帮你通过自然语言编排流程图，也可以选择流程文件生成初稿',
      },
    ]
  },
  {
    title: '治理',
    items: [
      { to: '/governance', label: '平台治理', icon: <ShieldCheck size={18} />, adminLevel: 'admin' },
      { to: '/llm-settings', label: '智能体配置', icon: <KeyRound size={18} />, flag: 'llmSettings', adminLevel: 'admin' },
      { to: '/skill-ops', label: '运营排行', icon: <BarChart3 size={18} />, adminLevel: 'superAdmin' },
      { to: '/user-management', label: '用户管理', icon: <Users size={18} />, adminLevel: 'superAdmin' },
      { to: '/audit-log', label: '操作日志', icon: <ScrollText size={18} />, adminLevel: 'superAdmin' },
    ]
  }
]

export default function Sidebar() {
  const { user, logout } = useAuth()
  const navigate = useNavigate()
  const { activeOverlay, openOverlay } = useChatOverlay()
  const [collapsed, setCollapsed] = useState(false)
  const overlayLayout = getOverlayLayout(activeOverlay)
  const effectiveCollapsed = collapsed || overlayLayout.sidebarShouldCollapse

  const isSuperAdmin = isSuperAdminUser(user)
  const isAdmin = isAdminUser(user)

  // 权限过滤：
  // - adminLevel='admin' → 管理员及以上可见
  // - adminLevel='superAdmin' 或 adminOnly=true → 仅超级管理员可见
  function canShow(item) {
    if (item.flag && !FEATURES[item.flag]) return false
    if (item.adminLevel === 'admin') return isAdmin
    if (item.adminLevel === 'superAdmin' || item.adminOnly) return isSuperAdmin
    return true
  }

  const visibleGroups = NAV_GROUPS
    .filter(group => !group.module || PRODUCT.modules[group.module])
    .map(group => ({ ...group, items: group.items.filter(canShow) }))
    .filter(group => group.items.length > 0)

  function handleLogout() {
    if (!confirm('确定退出登录吗？')) return
    logout()
    navigate('/login', { replace: true })
  }

  const initial = (user?.name || user?.email || '?').charAt(0).toUpperCase()
  const displayName = user?.name || user?.email || '未登录'

  return (
    <aside
      className={[
        'bg-white border-r border-gray-200 flex flex-col flex-shrink-0 transition-all duration-200 relative',
        effectiveCollapsed ? 'w-14' : 'w-56 max-lg:w-14'
      ].join(' ')}
    >
      {/* Logo */}
      <div className={['py-5 flex items-center border-b border-gray-100', effectiveCollapsed ? 'px-2.5 justify-center' : 'px-4 gap-2.5'].join(' ')}>
        <div className="w-9 h-9 rounded-lg bg-gradient-to-br from-brand-500 to-brand-700 grid place-items-center shadow-sm shadow-brand-300/40 flex-shrink-0">
          <svg viewBox="0 0 32 32" className="w-5 h-5 text-white" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <path d="M8 25 L16 7 L24 25" />
            <path d="M11.5 18 L20.5 18" />
            <circle cx="8" cy="25" r="1.6" fill="currentColor" />
            <circle cx="16" cy="7" r="1.6" fill="currentColor" />
            <circle cx="24" cy="25" r="1.6" fill="currentColor" />
          </svg>
        </div>
        {!effectiveCollapsed && (
          <div className="min-w-0 leading-tight max-lg:hidden">
            <div className="text-[16px] font-bold text-gray-900 tracking-wide">
              {PRODUCT.shortName.replace(PRODUCT.logoAccent, '')}<span className="text-brand-600">{PRODUCT.logoAccent}</span>
            </div>
            <div className="text-[11px] text-gray-500">{PRODUCT.subtitle}</div>
          </div>
        )}
      </div>

      {effectiveCollapsed && <div className="py-2" />}
      <nav className={['flex-1 space-y-0.5 overflow-y-auto scrollbar-thin', effectiveCollapsed ? 'px-1' : 'px-2'].join(' ')}>
        {visibleGroups.map(group => (
          <div key={group.title} className={effectiveCollapsed ? 'py-1' : 'py-2'}>
            {!effectiveCollapsed && (
              <div className="px-3 pb-1.5 pt-1 text-[11px] font-medium text-gray-400 max-lg:hidden">
                {group.title}
              </div>
            )}
            <div className="space-y-0.5">
              {group.items.map(item => (
                <NavLink
                  key={item.to}
                  to={item.to}
                  title={item.tooltip || (effectiveCollapsed ? item.label : undefined)}
                  onClick={item.overlay ? (e) => { e.preventDefault(); openOverlay(item.overlay) } : undefined}
                  className={({ isActive }) =>
                    [
                      'flex items-center rounded-lg transition',
                      effectiveCollapsed ? 'justify-center px-0 py-2.5' : 'gap-2 px-3 py-2 text-sm max-lg:justify-center max-lg:gap-0 max-lg:px-0 max-lg:py-2.5',
                      isActive
                        ? 'bg-brand-50 text-brand-700 font-medium'
                        : 'text-gray-700 hover:bg-gray-50'
                    ].join(' ')
                  }
                >
                  <span className="w-5 h-5 flex items-center justify-center flex-shrink-0">{item.icon}</span>
                  {!effectiveCollapsed && <span className="min-w-0 flex-1 truncate max-lg:hidden">{item.label}</span>}
                  {!effectiveCollapsed && item.dev && (
                    <span className="ml-1 text-[9px] px-1 py-0.5 rounded bg-amber-100 text-amber-600 font-medium leading-tight flex-shrink-0">开发中</span>
                  )}
                </NavLink>
              ))}
            </div>
          </div>
        ))}
      </nav>

      <button
        onClick={() => !overlayLayout.sidebarShouldCollapse && setCollapsed(c => !c)}
        className="absolute -right-3 top-1/2 z-10 grid h-6 w-6 -translate-y-1/2 place-items-center rounded-full border border-gray-200 bg-white text-gray-400 shadow-sm transition hover:bg-gray-50 hover:text-gray-700"
        title={overlayLayout.sidebarShouldCollapse ? '浮层打开时导航保持收起' : collapsed ? '展开导航' : '收起导航'}
      >
        {effectiveCollapsed ? <ChevronRight size={14} /> : <ChevronLeft size={14} />}
      </button>

      {/* 底部状态 */}
      <div className="px-2 py-3 border-t border-gray-100 text-xs">
        {effectiveCollapsed ? (
          <div className="flex flex-col items-center gap-2">
            <div className="w-7 h-7 rounded-full bg-brand-100 text-brand-700 grid place-items-center text-[12px] font-semibold" title={displayName}>
              {initial}
            </div>
            <button
              onClick={handleLogout}
              className="w-7 h-7 rounded-md text-gray-400 hover:text-rose-600 hover:bg-rose-50 grid place-items-center transition"
              title="退出登录"
            ><LogOut size={14} /></button>
          </div>
        ) : (
          <div className="flex items-center justify-between px-1 max-lg:flex-col max-lg:gap-2">
            <div className="flex items-center gap-2 min-w-0">
              <div className="w-6 h-6 rounded-full bg-brand-100 text-brand-700 grid place-items-center text-[11px] font-semibold flex-shrink-0">
                {initial}
              </div>
              <div className="min-w-0 max-lg:hidden">
                <div className="text-gray-700 truncate leading-tight">{displayName}</div>
                {user?.phone && <div className="text-[10px] text-gray-400 leading-tight">{user.phone}</div>}
              </div>
            </div>
            <button
              onClick={handleLogout}
              className="text-gray-400 hover:text-rose-600 flex-shrink-0 px-1.5 py-1 rounded hover:bg-rose-50 transition"
              title="退出登录"
            ><LogOut size={14} /></button>
          </div>
        )}
      </div>
    </aside>
  )
}
