import { NavLink } from 'react-router-dom'
import { useState, useEffect, useRef } from 'react'
import { BarChart2, LayoutGrid, ClipboardList, Package, Settings, ChevronRight, ChevronLeft, ShoppingBag, NotebookPen, Receipt, BookUser, Users, CreditCard, Trash2 } from 'lucide-react'
import { getIncomingOrders } from '../api/client'

export default function Sidebar() {
  const [collapsed, setCollapsed] = useState(false)
  const [pendingCount, setPendingCount] = useState(0)
  const pollRef = useRef(null)

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

  const NAV = [
    { to: '/dashboard',     icon: BarChart2,     label: 'Dashboard' },
    { to: '/tables',        icon: LayoutGrid,    label: 'Τραπέζια' },
    { to: '/online-orders', icon: ShoppingBag,   label: 'Online Orders', badge: pendingCount },
    { to: '/reports',       icon: ClipboardList, label: 'Αναφορές' },
    { to: '/management',    icon: Package,       label: 'Διαχείριση' },
    { to: '/notes',         icon: NotebookPen,   label: 'Σημειώσεις' },
    { to: '/expenses',      icon: Receipt,       label: 'Έξοδα' },
    { to: '/contacts',      icon: BookUser,      label: 'Επαφές' },
    { to: '/customers',     icon: Users,         label: 'Πελάτες' },
    { to: '/tabs',          icon: CreditCard,    label: 'Καρτέλες' },
    { to: '/waste',         icon: Trash2,        label: 'Αποβλήτα' },
    { to: '/settings',      icon: Settings,      label: 'Ρυθμίσεις' },
  ]

  return (
    <aside className={`flex flex-col bg-primary-800 text-white shrink-0 transition-all duration-200 ${collapsed ? 'w-16' : 'w-56'}`}>
      {/* Logo / collapse toggle */}
      <div className="flex items-center justify-between px-4 py-4 border-b border-primary-700">
        {!collapsed && <span className="font-bold text-lg tracking-wide">XeniaPOS</span>}
        <button
          onClick={() => setCollapsed(c => !c)}
          className="p-1 rounded hover:bg-primary-700 transition-colors ml-auto"
          aria-label="Toggle sidebar"
        >
          {collapsed ? <ChevronRight size={18} /> : <ChevronLeft size={18} />}
        </button>
      </div>

      <nav className="flex-1 py-4 space-y-1 px-2">
        {NAV.map(({ to, icon: Icon, label, badge }) => (
          <NavLink
            key={to}
            to={to}
            className={({ isActive }) =>
              `flex items-center gap-3 px-3 py-3 rounded-lg font-medium transition-colors min-h-[44px] ` +
              (isActive ? 'bg-primary-600 text-white' : 'text-primary-100 hover:bg-primary-700')
            }
          >
            <div className="relative shrink-0">
              <Icon size={20} />
              {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>
            {!collapsed && <span className="text-sm">{label}</span>}
          </NavLink>
        ))}
      </nav>
    </aside>
  )
}
