import { useEffect, useState } from 'react'
import { NavLink } from 'react-router-dom'
import {
  LayoutDashboard, ClipboardList, Wrench, Factory, Columns3, GitMerge, Activity,
  Gauge, Network, CalendarRange, PackagePlus, Truck, Boxes, ClipboardCheck, Barcode,
  ScanSearch, Ruler, AlertTriangle, ListChecks, LineChart, FileBadge, Package, ListTree,
  Route as RouteIcon, Building2, Warehouse, BarChart3, Sparkles, ShieldCheck, ScrollText,
  Settings, Cpu, NotebookPen, CalendarDays, Mail, PieChart, Smartphone,
  KeyRound, ShieldHalf, ListTodo, Menu as MenuIcon, Users2, Contact,
} from 'lucide-react'
import { currentRole, hasRole } from './rbac'
import ThemeToggle from './uiws/ThemeToggle'

interface Link { to: string; label: string; icon: any; min?: string }

const mainLinks: Link[] = [
  { to: '/dashboard', label: '대시보드', icon: LayoutDashboard },
]
const mesLinks: Link[] = [
  { to: '/jobs', label: '작업관리 ★', icon: Wrench },
  { to: '/progress', label: '진행관리 ★', icon: Activity },
  { to: '/workorders', label: '작업지시', icon: ClipboardList },
  { to: '/production', label: '생산실적', icon: Factory },
  { to: '/process-board', label: '공정진행', icon: Columns3 },
  { to: '/oee', label: '설비 / OEE', icon: Gauge },
  { to: '/tracking', label: 'LOT 추적', icon: Network },
  { to: '/plans', label: '생산계획', icon: CalendarRange },
]
const wmsLinks: Link[] = [
  { to: '/receiving', label: '입고', icon: PackagePlus },
  { to: '/shipping', label: '출하관리 ★', icon: Truck },
  { to: '/inventory', label: '재고', icon: Boxes },
  { to: '/stocktake', label: '재고실사', icon: ClipboardCheck },
  { to: '/lotserial', label: 'LOT / 시리얼', icon: Barcode },
]
const qmsLinks: Link[] = [
  { to: '/inspection', label: '검사', icon: ScanSearch },
  { to: '/spec', label: '검사기준', icon: Ruler },
  { to: '/ncr', label: '부적합 NCR', icon: AlertTriangle },
  { to: '/capa', label: '시정조치 CAPA', icon: ListChecks },
  { to: '/spc', label: 'SPC 관리도', icon: LineChart },
  { to: '/certificate', label: '성적서', icon: FileBadge },
]
const masterLinks: Link[] = [
  { to: '/items', label: '품목', icon: Package },
  { to: '/bom', label: 'BOM', icon: ListTree },
  { to: '/routing', label: '라우팅', icon: RouteIcon },
  { to: '/partners', label: '거래처', icon: Building2, min: 'MANAGER' },
  { to: '/warehouses', label: '창고/로케이션', icon: Warehouse },
]
const commonLinks: Link[] = [
  { to: '/analytics', label: '분석 / KPI', icon: BarChart3 },
  { to: '/ai-tools', label: 'AI 도구', icon: Sparkles },
  { to: '/ai-techniques', label: 'AI 기법 설정', icon: Cpu, min: 'MANAGER' },
]
// 업무 (UIWS 이식) — 업무일지/일정/쪽지/업무통계
const uiwsLinks: Link[] = [
  { to: '/uiws/worklog', label: '업무일지', icon: NotebookPen },
  { to: '/uiws/schedule', label: '일정', icon: CalendarDays },
  { to: '/uiws/message', label: '쪽지', icon: Mail },
  { to: '/uiws/stats', label: '업무통계', icon: PieChart },
]
// 시스템관리(권한) (UIWS 이식) — SUPERADMIN 전용
const sysLinks: Link[] = [
  { to: '/uiws/system/roles', label: '권한 관리', icon: KeyRound, min: 'SUPERADMIN' },
  { to: '/uiws/system/role-menus', label: '역할-메뉴 권한', icon: ShieldHalf, min: 'SUPERADMIN' },
  { to: '/uiws/system/codes', label: '공통코드', icon: ListTodo, min: 'SUPERADMIN' },
  { to: '/uiws/system/menus', label: '메뉴 관리', icon: MenuIcon, min: 'SUPERADMIN' },
  { to: '/uiws/system/depts', label: '부서 관리', icon: Users2, min: 'SUPERADMIN' },
  { to: '/uiws/system/companies', label: '거래처 관리', icon: Contact, min: 'SUPERADMIN' },
]
const adminLinks: Link[] = [
  { to: '/admin/users', label: '사용자/권한', icon: ShieldCheck, min: 'SUPERADMIN' },
  { to: '/admin/ai-platform', label: 'AI 플랫폼 설정', icon: Cpu, min: 'SUPERADMIN' },
  { to: '/admin/audit', label: '감사 로그', icon: ScrollText, min: 'MANAGER' },
  { to: '/admin/settings', label: '시스템 설정', icon: Settings, min: 'MANAGER' },
]
// 통합 메신저 앱(읽기전용 QR 설치) — 인증 사용자 전체
const mobileLinks: Link[] = [
  { to: '/admin/mobile-app', label: '모바일 앱 설치', icon: Smartphone },
]

const linkClass = ({ isActive }: { isActive: boolean }) =>
  `flex items-center gap-3 px-5 py-1.5 text-sm transition-colors ${
    isActive ? 'bg-card text-brand border-r-2 border-brand' : 'text-slate-300 hover:bg-card/60'
  }`

function Section({ title, links, role }: { title?: string; links: Link[]; role: string }) {
  const visible = links.filter(l => hasRole(l.min || 'VIEWER', role))
  if (!visible.length) return null
  return (
    <>
      {title && (
        <div className="px-5 pt-3 pb-1 text-[10px] font-semibold tracking-wider text-slate-500 uppercase">
          {title}
        </div>
      )}
      {visible.map(({ to, label, icon: Icon }) => (
        <NavLink key={to} to={to} className={linkClass}>
          <Icon size={16} />{label}
        </NavLink>
      ))}
    </>
  )
}

export default function Sidebar() {
  const [role, setRole] = useState(currentRole)

  useEffect(() => {
    const sync = () => {
      const r = currentRole()
      setRole(prev => (prev === r ? prev : r))
    }
    const t = window.setInterval(sync, 800)
    window.addEventListener('storage', sync)
    return () => { window.clearInterval(t); window.removeEventListener('storage', sync) }
  }, [])

  const visibleSys = sysLinks.filter(l => hasRole(l.min || 'VIEWER', role))
  const visibleAdmin = adminLinks.filter(l => hasRole(l.min || 'VIEWER', role))

  return (
    <aside className="w-60 bg-panel border-r border-edge flex flex-col">
      <div className="h-16 flex items-center gap-2 px-5 border-b border-edge">
        <Cpu className="text-brand" size={24} />
        <div>
          <div className="font-bold text-base leading-tight">GUARDiA MES</div>
          <div className="text-[11px] text-slate-400">AI 제조실행시스템</div>
        </div>
      </div>
      <nav className="flex-1 py-2 overflow-auto">
        <Section links={mainLinks} role={role} />
        <Section title="MES 제조실행" links={mesLinks} role={role} />
        <Section title="WMS 창고관리" links={wmsLinks} role={role} />
        <Section title="QMS 품질관리" links={qmsLinks} role={role} />
        <Section title="기준정보" links={masterLinks} role={role} />
        <Section title="공통" links={commonLinks} role={role} />
        <Section title="업무 (UIWS)" links={uiwsLinks} role={role} />
        <div className="border-t border-edge mt-3">
          <Section title="모바일" links={mobileLinks} role={role} />
        </div>
        {visibleSys.length > 0 && (
          <div className="border-t border-edge mt-3">
            <Section title="시스템관리(권한)" links={visibleSys} role={role} />
          </div>
        )}
        {visibleAdmin.length > 0 && (
          <div className="border-t border-edge mt-3">
            <Section title="관리자" links={visibleAdmin} role={role} />
          </div>
        )}
      </nav>
      <div className="p-3 border-t border-edge">
        <ThemeToggle />
      </div>
      <div className="px-4 pb-4 text-[11px] text-slate-500">
        Ollama 온프레미스 · WMS·MES·QMS 통합
      </div>
    </aside>
  )
}
