import { useEffect, useState } from 'react'
import { NavLink } from 'react-router-dom'
import {
  LayoutDashboard, FileText, Image, Package, Megaphone, ListTree, Palette,
  Languages, Search, FileInput, MessageSquareWarning, Share2, UsersRound,
  Sparkles, BarChart3, ShieldCheck, ScrollText, Settings, FileStack,
  BookOpen, CalendarDays, Mail, Smartphone, Cpu,
  KeyRound, ListChecks, Hash, SquareMenu, Network, Building2,
} from 'lucide-react'
import { currentRole, hasRole } from './rbac'
import ThemeToggle from './uiws/ThemeToggle'

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

const contentLinks: Link[] = [
  { to: '/dashboard', label: '개요', icon: LayoutDashboard },
  { to: '/contents', label: '콘텐츠', icon: FileText },
  { to: '/media', label: '미디어', icon: Image },
  { to: '/products', label: '상품 콘텐츠', icon: Package },
  { to: '/banners', label: '배너/프로모션', icon: Megaphone },
  { to: '/menus', label: '메뉴/카테고리', icon: ListTree },
]
const siteLinks: Link[] = [
  { to: '/themes', label: '테마/템플릿', icon: Palette },
  { to: '/i18n', label: '다국어', icon: Languages },
  { to: '/seo', label: 'SEO', icon: Search },
  { to: '/forms', label: '폼빌더', icon: FileInput },
  { to: '/channels', label: '채널', icon: Share2 },
]
const engageLinks: Link[] = [
  { to: '/ugc', label: 'UGC 모더레이션', icon: MessageSquareWarning },
  { to: '/members', label: '회원', icon: UsersRound },
  { to: '/analytics', label: '콘텐츠 분석', icon: BarChart3 },
  { to: '/ai-tools', label: 'AI 도구', icon: Sparkles },
  { to: '/ai-techniques', label: 'AI 기법 (RAG)', icon: Cpu },
]
const adminLinks: Link[] = [
  { to: '/admin/users', label: '사용자/권한', icon: ShieldCheck, min: 'SUPERADMIN' },
  { to: '/admin/audit', label: '감사 로그', icon: ScrollText, min: 'EDITOR' },
  { to: '/admin/settings', label: '시스템 설정', icon: Settings, min: 'EDITOR' },
  { to: '/admin/ai-platform', label: 'AI 플랫폼', icon: Cpu, min: 'SUPERADMIN' },
]
// 업무(UIWS 이식) — 업무일지·일정·쪽지·통계 (인증 사용자 전체)
const uiwsLinks: Link[] = [
  { to: '/uiws/worklog', label: '업무일지', icon: BookOpen },
  { to: '/uiws/schedule', label: '일정', icon: CalendarDays },
  { to: '/uiws/message', label: '쪽지', icon: Mail },
  { to: '/uiws/stats', label: '업무통계', icon: BarChart3 },
]
// 시스템관리(권한) — UIWS RBAC/공통코드/메뉴/부서/거래처 (SUPERADMIN 전용)
const systemLinks: Link[] = [
  { to: '/uiws/system/roles', label: '권한 관리', icon: KeyRound, min: 'SUPERADMIN' },
  { to: '/uiws/system/role-menus', label: '역할-메뉴 권한', icon: ListChecks, min: 'SUPERADMIN' },
  { to: '/uiws/system/codes', label: '공통코드', icon: Hash, min: 'SUPERADMIN' },
  { to: '/uiws/system/menus', label: '메뉴 관리', icon: SquareMenu, min: 'SUPERADMIN' },
  { to: '/uiws/system/depts', label: '부서 관리', icon: Network, min: 'SUPERADMIN' },
  { to: '/uiws/system/companies', label: '거래처 관리', icon: Building2, min: 'SUPERADMIN' },
]
// 통합 메신저 앱(읽기전용 QR 설치) — 인증 사용자 전체
const appLinks: Link[] = [
  { to: '/admin/mobile-app', label: '모바일 앱 설치', icon: Smartphone },
]

const linkClass = ({ isActive }: { isActive: boolean }) =>
  `flex items-center gap-3 px-5 py-2 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 }: { title?: string; links: Link[] }) {
  return (
    <>
      {title && (
        <div className="px-5 pt-4 pb-1.5 text-[10px] font-semibold tracking-wider text-slate-500 uppercase">
          {title}
        </div>
      )}
      {links.map(({ to, label, icon: Icon }) => (
        <NavLink key={to} to={to} className={linkClass}>
          <Icon size={17} />{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 visibleAdmin = adminLinks.filter(l => hasRole(l.min || 'VIEWER', role))
  const visibleSystem = systemLinks.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">
        <FileStack className="text-brand" size={24} />
        <div>
          <div className="font-bold text-base leading-tight">GUARDiA CMS</div>
          <div className="text-[11px] text-slate-400">콘텐츠 관리 시스템</div>
        </div>
      </div>
      <nav className="flex-1 py-2 overflow-auto">
        <Section links={contentLinks} />
        <Section title="사이트" links={siteLinks} />
        <Section title="참여 · 분석" links={engageLinks} />
        <div className="border-t border-edge mt-3">
          <Section title="업무(UIWS)" links={uiwsLinks} />
        </div>
        {visibleSystem.length > 0 && (
          <div className="border-t border-edge mt-3">
            <Section title="시스템관리(권한)" links={visibleSystem} />
          </div>
        )}
        <div className="border-t border-edge mt-3">
          <Section title="모바일" links={appLinks} />
        </div>
        {visibleAdmin.length > 0 && (
          <div className="border-t border-edge mt-3">
            <Section title="관리자" links={visibleAdmin} />
          </div>
        )}
      </nav>
      <div className="px-4 pt-3 border-t border-edge">
        <ThemeToggle />
      </div>
      <div className="p-4 text-[11px] text-slate-500">
        Ollama 온프레미스 · 헤드리스 CMS
      </div>
    </aside>
  )
}
