import { ReactNode, useState } from 'react'
import { Link, useLocation } from 'react-router-dom'
import { LayoutDashboard, Store, ClipboardList, TrendingUp, Settings, LogOut, Menu, X, Package, DollarSign, ShoppingBag, Users, AlertTriangle, Clock, Database, MapPin, PieChart, Wallet, CalendarClock, Activity, Crown, BarChart3, Receipt, Utensils, Landmark, ChefHat, Truck, Network, TrendingUp as TrendingUpIcon, Building2 } from 'lucide-react'
import { cn } from '@/lib/utils'
import { StatusBanner } from '@/components/StatusBanner'

interface LayoutProps {
  children: ReactNode
  user: { name: string; role: string } | null
  onLogout: () => void
}

interface MenuItem {
  path: string
  label: string
  icon: any
  roles: string[]
}

interface MenuGroup {
  title: string
  items: MenuItem[]
}

const menuGroups: MenuGroup[] = [
  {
    title: '经营总览',
    items: [
      { path: '/boss', label: '老板驾驶舱', icon: Crown, roles: ['hq', 'dept'] },
      { path: '/', label: '总部驾驶舱', icon: LayoutDashboard, roles: ['hq', 'dept'] },
      { path: '/situational-awareness', label: '态势感知', icon: Activity, roles: ['hq', 'dept', 'regional', 'store'] },
      { path: '/bank', label: '银行授信', icon: Landmark, roles: ['hq'] },
    ],
  },
  {
    title: '角色工作台',
    items: [
      { path: '/regional', label: '区域经理', icon: Store, roles: ['hq', 'dept', 'regional'] },
      { path: '/region-comparison', label: '区域对比', icon: Store, roles: ['hq', 'dept', 'regional'] },
      { path: '/store', label: '店长工作台', icon: ClipboardList, roles: ['hq', 'dept', 'store'] },
      { path: '/tasks', label: '任务管理', icon: ClipboardList, roles: ['hq', 'regional', 'store', 'dept'] },
      { path: '/monthly-review', label: '月度验收', icon: TrendingUp, roles: ['hq', 'dept', 'regional'] },
    ],
  },
  {
    title: '收入分析',
    items: [
      { path: '/revenue', label: '营收分析', icon: BarChart3, roles: ['hq', 'dept'] },
      { path: '/platform', label: '平台优惠', icon: ShoppingBag, roles: ['hq', 'dept'] },
      { path: '/member', label: '会员复购', icon: Users, roles: ['hq', 'dept'] },
      { path: '/member-ltv', label: '会员LTV', icon: Users, roles: ['hq', 'dept'] },
    ],
  },
  {
    title: '成本与费用',
    items: [
      { path: '/cost-analysis', label: '菜品成本', icon: PieChart, roles: ['hq', 'dept'] },
      { path: '/cost', label: '成本库存', icon: Utensils, roles: ['hq', 'dept'] },
      { path: '/inventory-turnover', label: '库存周转', icon: Utensils, roles: ['hq', 'dept'] },
      { path: '/central-kitchen', label: '中央厨房', icon: ChefHat, roles: ['hq', 'dept'] },
      { path: '/distribution-reconciliation', label: '配送对账', icon: Truck, roles: ['hq', 'dept'] },
      { path: '/bom-penetration', label: 'BOM穿透', icon: Network, roles: ['hq', 'dept'] },
      { path: '/production-plan', label: '生产要货', icon: TrendingUpIcon, roles: ['hq', 'dept'] },
      { path: '/store-expense', label: '门店费用', icon: Wallet, roles: ['hq', 'dept'] },
    ],
  },
  {
    title: '运营分析',
    items: [
      { path: '/sku', label: '商品SKU', icon: Package, roles: ['hq', 'dept'] },
      { path: '/menu-engineering', label: '菜单工程', icon: Package, roles: ['hq', 'dept'] },
      { path: '/time', label: '时间分析', icon: Clock, roles: ['hq', 'dept'] },
      { path: '/smart-scheduling', label: '智能排班', icon: CalendarClock, roles: ['hq', 'dept', 'regional', 'store'] },
      { path: '/employee-performance', label: '员工绩效', icon: CalendarClock, roles: ['hq', 'dept'] },
    ],
  },
  {
    title: '风险与选址',
    items: [
      { path: '/risk', label: '风险内控', icon: AlertTriangle, roles: ['hq', 'dept'] },
      { path: '/site-selection', label: '门店选址', icon: MapPin, roles: ['hq', 'dept'] },
    ],
  },
  {
    title: '系统管理',
    items: [
      { path: '/tenant-users', label: '用户管理', icon: Users, roles: ['hq'] },
      { path: '/data-quality', label: '数据质量', icon: Database, roles: ['hq', 'dept'] },
      { path: '/indicators', label: '指标字典', icon: Settings, roles: ['hq', 'dept', 'regional', 'store'] },
      { path: '/ontology', label: '本体标准', icon: Receipt, roles: ['hq', 'dept'] },
    ],
  },
  {
    title: '平台管理',
    items: [
      { path: '/tenant-management', label: '租户管理', icon: Building2, roles: ['platform_admin'] },
    ],
  },
]

export function Layout({ children, user, onLogout }: LayoutProps) {
  const location = useLocation()
  const [sidebarOpen, setSidebarOpen] = useState(false)

  const visibleGroups = menuGroups.map(g => ({
    ...g,
    items: g.items.filter((m) => !user || m.roles.includes(user.role)),
  })).filter(g => g.items.length > 0)

  return (
    <div className="min-h-screen bg-background">
      {/* Mobile sidebar toggle */}
      <button
        onClick={() => setSidebarOpen(!sidebarOpen)}
        className="fixed left-4 top-4 z-50 rounded-md border p-2 lg:hidden"
      >
        {sidebarOpen ? <X size={20} /> : <Menu size={20} />}
      </button>

      {/* Sidebar */}
      <aside className={cn(
        'fixed left-0 top-0 z-40 h-full w-56 border-r bg-card transition-transform lg:translate-x-0',
        sidebarOpen ? 'translate-x-0' : '-translate-x-full'
      )}>
        <div className="flex h-14 items-center gap-2 border-b px-4">
          <Activity size={22} className="text-primary" />
          <span className="text-lg font-bold">态势感知系统</span>
        </div>
        <nav className="space-y-4 overflow-y-auto p-3 pb-20" style={{ maxHeight: 'calc(100vh - 3.5rem - 5rem)' }}>
          {visibleGroups.map((group) => (
            <div key={group.title}>
              <p className="mb-1 px-3 text-xs font-medium text-muted-foreground">{group.title}</p>
              <div className="space-y-1">
                {group.items.map((item) => {
                  const Icon = item.icon
                  const active = location.pathname === item.path
                  return (
                    <Link
                      key={item.path}
                      to={item.path}
                      onClick={() => setSidebarOpen(false)}
                      className={cn(
                        'flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors',
                        active ? 'bg-primary text-primary-foreground' : 'hover:bg-muted'
                      )}
                    >
                      <Icon size={18} />
                      {item.label}
                    </Link>
                  )
                })}
              </div>
            </div>
          ))}
        </nav>
        {user && (
          <div className="absolute bottom-0 left-0 right-0 border-t bg-card p-3">
            <div className="mb-2 px-3 text-sm">
              <p className="font-medium">{user.name}</p>
              <p className="text-xs text-muted-foreground">{user.role}</p>
            </div>
            <button
              onClick={onLogout}
              className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-sm text-muted-foreground hover:bg-muted"
            >
              <LogOut size={16} />
              退出登录
            </button>
          </div>
        )}
      </aside>

      {/* Main content */}
      <div className="lg:pl-56">
        <main className="min-h-screen p-4 pt-16 lg:pt-4">
          {user?.role !== 'platform_admin' && (
            <div className="mb-4">
              <StatusBanner />
            </div>
          )}
          {children}
        </main>
      </div>

      {/* Overlay for mobile */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 z-30 bg-black/40 lg:hidden"
          onClick={() => setSidebarOpen(false)}
        />
      )}
    </div>
  )
}
