import { useEffect, useState } from 'react'
import { Outlet, Navigate, NavLink, useNavigate } from 'react-router-dom'
import {
  LayoutDashboard, Store, Flower2, Boxes, ShoppingBag, Users, Crown, Megaphone,
  Repeat, CalendarClock, BarChart3, UserCog, ScrollText, Settings, LogOut, UserCircle, ArrowLeftRight, Smartphone,
} from 'lucide-react'
import { getMe } from '../api/client'

const links = [
  { to: '/admin/dashboard', label: '대시보드', icon: LayoutDashboard, roles: ['ADMIN', 'MANAGER'] },
  { to: '/admin/stores', label: '매장 관리', icon: Store, roles: ['ADMIN', 'MANAGER'] },
  { to: '/admin/products', label: '상품 관리', icon: Flower2, roles: ['ADMIN', 'MANAGER'] },
  { to: '/admin/inventory', label: '매장별 재고', icon: Boxes, roles: ['ADMIN', 'MANAGER'] },
  { to: '/admin/orders', label: '주문 (라이브)', icon: ShoppingBag, roles: ['ADMIN', 'MANAGER'] },
  { to: '/admin/transfers', label: '재고 이양', icon: ArrowLeftRight, roles: ['ADMIN', 'MANAGER'] },
  { to: '/admin/members', label: '회원 (CRM)', icon: Users, roles: ['ADMIN', 'MANAGER'] },
  { to: '/admin/loyalty', label: '등급·포인트', icon: Crown, roles: ['ADMIN', 'MANAGER'] },
  { to: '/admin/events', label: '이벤트·캠페인', icon: Megaphone, roles: ['ADMIN', 'MANAGER'] },
  { to: '/admin/subscriptions', label: '구독', icon: Repeat, roles: ['ADMIN', 'MANAGER'] },
  { to: '/admin/schedule', label: '스케줄·서지', icon: CalendarClock, roles: ['ADMIN', 'MANAGER'] },
  { to: '/admin/analytics', label: '매출 분석 (BI)', icon: BarChart3, roles: ['ADMIN', 'MANAGER'] },
]
const adminLinks = [
  { to: '/admin/users', label: '사용자/권한', icon: UserCog, roles: ['ADMIN'] },
  { to: '/admin/audit', label: '감사 로그', icon: ScrollText, roles: ['ADMIN', 'MANAGER'] },
  { to: '/admin/settings', label: '게이트웨이 설정', icon: Settings, roles: ['ADMIN'] },
  { to: '/admin/app', label: '관리자앱 설치', icon: Smartphone, roles: ['ADMIN', 'MANAGER'] },
]
const linkClass = ({ isActive }: { isActive: boolean }) =>
  `flex items-center gap-3 px-5 py-2.5 text-sm transition-colors ${isActive ? 'bg-card text-brand border-r-2 border-brand' : 'text-slate-300 hover:bg-card/60'}`

export default function AdminLayout() {
  const token = localStorage.getItem('mall_admin_token')
  const [role, setRole] = useState(() => localStorage.getItem('mall_role') || '')
  const [who, setWho] = useState(() => localStorage.getItem('mall_admin_user') || '')
  const nav = useNavigate()

  useEffect(() => {
    document.documentElement.classList.add('admin-shell')
    return () => document.documentElement.classList.remove('admin-shell')
  }, [])

  useEffect(() => {
    if (!token) return
    getMe().then((me: any) => {
      if (me?.role) { localStorage.setItem('mall_role', me.role); setRole(me.role) }
      if (me?.username) { localStorage.setItem('mall_admin_user', me.username); setWho(me.username) }
    }).catch(() => {})
  }, [token])

  if (!token) return <Navigate to="/admin/login" replace />
  // USER 역할은 관리자 영역 접근 차단
  if (role && role === 'USER') return <Navigate to="/admin/login" replace />

  const visible = links.filter(l => !role || l.roles.includes(role))
  const visibleAdmin = adminLinks.filter(l => l.roles.includes(role))

  const logout = () => {
    localStorage.removeItem('mall_admin_token'); localStorage.removeItem('mall_role'); localStorage.removeItem('mall_admin_user')
    nav('/admin/login')
  }

  return (
    <div className="admin-shell flex h-screen bg-ink text-[#e6edf6]">
      <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">
          <Flower2 className="text-brand" size={22} />
          <div><div className="font-bold text-base leading-tight">GUARDiA Mall</div><div className="text-[11px] text-slate-400">관리자 콘솔</div></div>
        </div>
        <nav className="flex-1 py-2 overflow-auto">
          {visible.map(({ to, label, icon: Icon }) => <NavLink key={to} to={to} className={linkClass}><Icon size={18} />{label}</NavLink>)}
          {visibleAdmin.length > 0 && (<>
            <div className="px-5 pt-4 pb-1.5 text-[10px] font-semibold tracking-wider text-slate-500 uppercase border-t border-edge mt-3">시스템</div>
            {visibleAdmin.map(({ to, label, icon: Icon }) => <NavLink key={to} to={to} className={linkClass}><Icon size={18} />{label}</NavLink>)}
          </>)}
        </nav>
        <div className="p-4 text-[11px] text-slate-500 border-t border-edge">Ollama 온프레미스 · 옴니채널</div>
      </aside>
      <div className="flex-1 flex flex-col overflow-hidden">
        <header className="h-16 bg-panel border-b border-edge flex items-center justify-between px-6">
          <div className="text-sm text-slate-400">미국 다지점 꽃집 옴니채널 e-커머스 · AI 수요예측 · BI</div>
          <div className="flex items-center gap-4">
            <span className="flex items-center gap-1.5 text-sm text-slate-300"><UserCircle size={18} /> {who || 'admin'} <span className="text-[10px] text-brand">{role}</span></span>
            <button onClick={logout} className="flex items-center gap-1.5 text-sm text-slate-400 hover:text-brand"><LogOut size={16} /> 로그아웃</button>
          </div>
        </header>
        <main className="flex-1 overflow-auto p-6">
          <Outlet />
        </main>
      </div>
    </div>
  )
}
