import { NavLink, useLocation } from 'react-router-dom'
import { useState, useEffect, useRef } from 'react'
import {
  LayoutDashboard, LayoutGrid, ShoppingBag,
  BookUser, Users, Receipt, CreditCard,
  Package, TableProperties, UserCog, CalendarDays, Trash2, Boxes,
  BarChart2, TrendingUp, Users2, ShoppingCart, Tag, Activity, Printer, Ban, Percent, ConciergeBell, FileText,
  AppWindow, Settings, ChevronDown, CookingPot, StickyNote,
} from 'lucide-react'
import { getIncomingOrders } from '../api/client'
import { isFeatureEnabled } from '../hooks/usePhase2Features'
import usePermissions from '../hooks/usePermissions'

// ─── Nav structure ────────────────────────────────────────────────────────────

// `perm` — key from usePermissions(). If set, item is hidden when user lacks that permission.
function buildNav(pendingCount) {
  return [
    {
      category: 'Operation',
      items: [
        { type: 'solo', to: '/dashboard',     icon: LayoutDashboard, label: 'Εικόνα' },
        { type: 'solo', to: '/tables',         icon: LayoutGrid,      label: 'Τραπέζια' },
        { type: 'solo', to: '/online-orders',  icon: ShoppingBag,     label: 'Online Παραγγ.', badge: pendingCount, phase2: 'online-orders' },
      ],
    },
    {
      category: 'Financial',
      items: [
        {
          type: 'group', id: 'crm', icon: BookUser, label: 'CRM',
          children: [
            { to: '/crm/contacts',  icon: BookUser, label: 'Επαφές',   phase2: 'contacts' },
            { to: '/crm/customers', icon: Users,    label: 'Πελάτες',  phase2: 'customers' },
          ],
        },
        {
          type: 'group', id: 'financials', icon: Receipt, label: 'Οικονομικά',
          children: [
            { to: '/financials/expenses', icon: Receipt,    label: 'Έξοδα',          phase2: 'expenses' },
            { to: '/financials/tabs',     icon: CreditCard, label: 'Καρτέλες Πελ.',  phase2: 'tabs' },
          ],
        },
      ],
    },
    {
      category: 'Headquarters',
      items: [
        {
          type: 'group', id: 'management', icon: Package, label: 'Διαχείριση',
          children: [
            { to: '/management/products',   icon: Package,         label: 'Προϊόντα',          perm: 'manageMenu' },
            { to: '/management/tables',     icon: TableProperties, label: 'Τραπέζια',           perm: 'manageTables' },
            { to: '/management/staff',      icon: UserCog,         label: 'Προσωπικό',          perm: 'manageStaff' },
            { to: '/management/schedule',   icon: CalendarDays,    label: 'Πρόγραμμα',          perm: 'manageStaff', phase2: 'schedule' },
            { to: '/management/prep-zones', icon: CookingPot,      label: 'Ζώνες Ετοιμασίας',  perm: 'manageMenu' },
            { to: '/management/pricing',    icon: Percent,         label: 'Προσφορές & Τιμές',  perm: 'manageMenu' },
            { to: '/notes',                 icon: StickyNote,      label: 'Σημειώσεις' },
          ],
        },
        {
          type: 'group', id: 'inventory', icon: Boxes, label: 'Αποθήκη',
          children: [
            { to: '/inventory/throwaways', icon: Trash2, label: 'Απορρίμματα', phase2: 'waste' },
            { to: '/inventory/stock',      icon: Boxes,  label: 'Απόθεμα',     placeholder: true },
          ],
        },
      ],
    },
    {
      category: 'Overwatch',
      perm: 'viewReports',
      items: [
        {
          type: 'group', id: 'reports', icon: BarChart2, label: 'Αναφορές',
          children: [
            { to: '/reports/today',      icon: Activity,       label: 'Σήμερα' },
            { to: '/reports/store',      icon: TrendingUp,     label: 'Κατάστημα' },
            { to: '/reports/staff',      icon: Users2,         label: 'Προσωπικό' },
            { to: '/reports/products',   icon: ShoppingCart,   label: 'Προϊόντα' },
            { to: '/reports/prep-zones', icon: ConciergeBell,  label: 'Ζώνες Ετοιμασίας' },
            { to: '/reports/expenses',   icon: FileText,        label: 'Έξοδα' },
            { to: '/reports/technical',  icon: Printer,        label: 'Τεχνικά' },
            { to: '/reports/misc',       icon: Tag,            label: 'Λοιπά' },
          ],
        },
      ],
    },
  ]
}

const BOTTOM_ITEMS = [
  { to: '/apps',     icon: AppWindow, label: 'Εφαρμογές' },
  { to: '/settings', icon: Settings,  label: 'Ρυθμίσεις', perm: 'manageSettings' },
]

// ─── Helpers ──────────────────────────────────────────────────────────────────

function isChildActive(children, pathname) {
  return children.some(c => pathname === c.to || pathname.startsWith(c.to + '/'))
}

// ─── Child link ───────────────────────────────────────────────────────────────

function ChildLink({ to, icon: Icon, label, placeholder }) {
  if (placeholder) {
    return (
      <div className="flex items-center gap-2.5 px-3 py-2 mx-2 rounded-md text-[13px] text-primary-400 cursor-default select-none">
        <Icon size={14} className="shrink-0 opacity-50" />
        <span>{label}</span>
        <span className="ml-auto text-[10px] font-semibold bg-primary-700 text-primary-300 px-1.5 py-0.5 rounded">soon</span>
      </div>
    )
  }

  return (
    <NavLink
      to={to}
      end
      className={({ isActive }) =>
        `flex items-center gap-2.5 px-3 py-2 mx-2 rounded-md text-[13px] font-medium transition-colors ` +
        (isActive
          ? 'bg-primary-600 text-white'
          : 'text-primary-200 hover:bg-primary-700 hover:text-white')
      }
    >
      {({ isActive }) => (
        <>
          <Icon size={14} className="shrink-0" />
          <span>{label}</span>
          {isActive && <span className="ml-auto w-1 h-1 rounded-full bg-sky-400 shrink-0" />}
        </>
      )}
    </NavLink>
  )
}

// ─── Group item (collapsible parent) ─────────────────────────────────────────

function GroupItem({ id, icon: Icon, label, children, openGroup, onToggle, perms }) {
  const location = useLocation()
  const hasActive = isChildActive(children, location.pathname)
  const isOpen = openGroup === id

  // Filter out phase2-gated children and children the user lacks permission for
  const visibleChildren = children.filter(c => {
    if (c.phase2 && !isFeatureEnabled(c.phase2)) return false
    if (c.perm && !perms[c.perm]) return false
    return true
  })

  if (visibleChildren.length === 0) return null

  return (
    <div>
      <button
        onClick={() => onToggle(id)}
        className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ` +
          (hasActive
            ? 'text-white bg-primary-700'
            : 'text-primary-100 hover:bg-primary-700 hover:text-white')}
      >
        <Icon size={18} className="shrink-0" />
        <span className="flex-1 text-left">{label}</span>
        <ChevronDown
          size={14}
          className={`shrink-0 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`}
        />
      </button>

      {isOpen && (
        <div className="mt-0.5 mb-1 space-y-0.5 py-1 border-l border-primary-600 ml-5">
          {visibleChildren.map(child => (
            <ChildLink key={child.to} {...child} />
          ))}
        </div>
      )}
    </div>
  )
}

// ─── Solo item (direct link) ──────────────────────────────────────────────────

function SoloItem({ to, icon: Icon, label, badge, onNavigate }) {
  return (
    <NavLink
      to={to}
      end
      onClick={onNavigate}
      className={({ isActive }) =>
        `flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ` +
        (isActive ? 'bg-primary-600 text-white' : 'text-primary-100 hover:bg-primary-700 hover:text-white')
      }
    >
      <div className="relative shrink-0">
        <Icon size={18} />
        {badge > 0 && (
          <span className="absolute -top-1.5 -right-1.5 bg-red-500 text-white text-[10px] font-bold w-4 h-4 rounded-full flex items-center justify-center leading-none">
            {badge > 9 ? '9+' : badge}
          </span>
        )}
      </div>
      <span>{label}</span>
    </NavLink>
  )
}

// ─── Sidebar ──────────────────────────────────────────────────────────────────

export default function Sidebar() {
  const [pendingCount, setPendingCount] = useState(0)
  const [openGroup, setOpenGroup] = useState(null)
  const [, featTick] = useState(0)
  const location = useLocation()
  const pollRef = useRef(null)
  const perms = usePermissions()

  // Online orders badge polling
  useEffect(() => {
    async function fetchPending() {
      try {
        const { data } = await getIncomingOrders()
        setPendingCount(data.length)
      } catch { /* non-critical */ }
    }
    fetchPending()
    pollRef.current = setInterval(fetchPending, 20_000)
    return () => clearInterval(pollRef.current)
  }, [])

  // Re-render when feature flags change
  useEffect(() => {
    const handler = () => featTick(n => n + 1)
    window.addEventListener('phase2features', handler)
    window.addEventListener('storage', handler)
    return () => {
      window.removeEventListener('phase2features', handler)
      window.removeEventListener('storage', handler)
    }
  }, [])

  // Auto-open the group that contains the active route on location change
  useEffect(() => {
    const nav = buildNav(0)
    for (const section of nav) {
      for (const item of section.items) {
        if (item.type === 'group' && isChildActive(item.children, location.pathname)) {
          setOpenGroup(item.id)
          return
        }
      }
    }
  }, [location.pathname])

  function handleGroupToggle(id) {
    setOpenGroup(prev => (prev === id ? null : id))
  }

  function handleSoloClick() {
    setOpenGroup(null)
  }

  const nav = buildNav(pendingCount)

  return (
    <aside className="flex flex-col bg-primary-800 text-white shrink-0 w-56 h-full sidebar-scroll">
      {/* Brand */}
      <div className="flex items-center px-4 py-4 border-b border-primary-700 shrink-0">
        <span className="font-bold text-lg tracking-wide">XeniaPOS</span>
      </div>

      {/* Main nav */}
      <nav className="flex-1 py-3 px-2 space-y-4">
        {nav.map(({ category, perm: sectionPerm, items }) => {
          // Hide entire section if user lacks section-level permission
          if (sectionPerm && !perms[sectionPerm]) return null

          const visibleItems = items.filter(item => {
            if (item.type === 'solo') {
              if (item.perm && !perms[item.perm]) return false
              return !item.phase2 || isFeatureEnabled(item.phase2)
            }
            if (item.type === 'group') {
              const visible = item.children.filter(c => {
                if (c.phase2 && !isFeatureEnabled(c.phase2)) return false
                if (c.perm && !perms[c.perm]) return false
                return true
              })
              return visible.length > 0
            }
            return true
          })
          if (visibleItems.length === 0) return null

          return (
            <div key={category}>
              <div className="flex items-center gap-2 px-3 mb-1.5 select-none" style={{ opacity: 0.45 }}>
                <span className="text-[9.5px] font-bold uppercase tracking-widest text-primary-100 whitespace-nowrap">
                  {category}
                </span>
                <div className="flex-1" style={{ height: 1, background: 'rgba(255,255,255,0.2)' }} />
              </div>
              <div className="space-y-0.5">
                {visibleItems.map(item =>
                  item.type === 'solo' ? (
                    <SoloItem key={item.to} {...item} onNavigate={handleSoloClick} />
                  ) : (
                    <GroupItem
                      key={item.id}
                      {...item}
                      openGroup={openGroup}
                      onToggle={handleGroupToggle}
                      perms={perms}
                    />
                  )
                )}
              </div>
            </div>
          )
        })}
      </nav>

      {/* Divider + bottom items */}
      <div className="shrink-0 px-2 pb-3 border-t border-primary-700 pt-3 space-y-0.5">
        {BOTTOM_ITEMS.filter(item => !item.perm || perms[item.perm]).map(item => (
          <SoloItem key={item.to} {...item} onNavigate={handleSoloClick} />
        ))}
      </div>
    </aside>
  )
}
