import { NavLink } from 'react-router-dom';
import {
  Building2,
  Radio,
  Send,
  Activity,
  Inbox,
  ScrollText,
  ShieldCheck,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useAuth } from '@/lib/auth-context';
import { canManageCompanies, canManageSources, canManageTelegram, canViewDLQ } from '@/lib/scope';

interface NavItem {
  to: string;
  label: string;
  icon: typeof Building2;
  show?: (role: ReturnType<typeof useAuth>['user']) => boolean;
  badge?: string;
}

const NAV: NavItem[] = [
  { to: '/companies', label: 'Companies', icon: Building2, show: (u) => canManageCompanies(u?.role) },
  { to: '/sources', label: 'Sources', icon: Radio, show: (u) => canManageSources(u?.role) },
  { to: '/telegram', label: 'Telegram', icon: Send, show: (u) => canManageTelegram(u?.role) },
  { to: '/tail', label: 'Live tail', icon: Activity },
  { to: '/dlq', label: 'DLQ', icon: Inbox, show: (u) => canViewDLQ(u?.role), badge: 'M13c' },
  { to: '/audit', label: 'Audit log', icon: ScrollText, badge: 'M13c' },
];

export function Sidebar() {
  const { user } = useAuth();
  const visible = NAV.filter((item) => !item.show || item.show(user));

  return (
    <aside className="hidden w-56 shrink-0 border-r bg-card md:block">
      <nav className="flex flex-col gap-0.5 p-3">
        {visible.map((item) => (
          <NavLink
            key={item.to}
            to={item.to}
            className={({ isActive }) =>
              cn(
                'flex items-center justify-between rounded-md px-3 py-2 text-sm transition-colors',
                isActive
                  ? 'bg-primary/10 text-primary'
                  : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',
              )
            }
          >
            <span className="flex items-center gap-2">
              <item.icon className="h-4 w-4" aria-hidden />
              {item.label}
            </span>
            {item.badge ? (
              <span className="rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
                {item.badge}
              </span>
            ) : null}
          </NavLink>
        ))}
      </nav>
      <div className="border-t p-3 text-xs text-muted-foreground">
        <div className="flex items-center gap-1.5">
          <ShieldCheck className="h-3.5 w-3.5" />
          <span>M13b W3 · SPA shell</span>
        </div>
      </div>
    </aside>
  );
}
