import * as React from 'react';
import { NavLink, Outlet } from 'react-router-dom';
import { LogOut, FolderKanban, Bot, Sparkles, Inbox, LayoutDashboard } from 'lucide-react';

import { api, clearToken, type Proposal } from '../api';
import { Badge } from './ui/badge';
import { cn } from '../lib/utils';

/**
 * Sidebar layout. Pending-proposals badge polls every 30 s so reviewers
 * see a queue building up without having to refresh the page.
 */
export function Layout(): React.JSX.Element {
  const [pendingCount, setPendingCount] = React.useState<number | null>(null);

  React.useEffect(() => {
    let cancelled = false;
    async function poll(): Promise<void> {
      try {
        const proposals = await api.get<Proposal[]>('/api/v1/proposals?status=pending');
        if (!cancelled) setPendingCount(proposals.length);
      } catch {
        if (!cancelled) setPendingCount(null);
      }
    }
    void poll();
    const id = setInterval(poll, 30_000);
    return () => {
      cancelled = true;
      clearInterval(id);
    };
  }, []);

  return (
    <div className="flex min-h-screen">
      <aside className="flex w-56 shrink-0 flex-col border-r border-(--color-border) bg-(--color-surface)">
        <div className="flex items-center gap-2 px-5 py-5">
          <span className="text-base font-bold tracking-tight">mcpctl</span>
          <span className="text-xs text-(--color-fg-muted)">UI</span>
        </div>

        <nav className="flex flex-1 flex-col gap-0.5 px-2 py-2">
          <NavItem to="/dashboard" icon={LayoutDashboard}>
            Dashboard
          </NavItem>
          <NavItem to="/projects" icon={FolderKanban}>
            Projects
          </NavItem>
          <NavItem to="/agents" icon={Bot}>
            Agents
          </NavItem>
          <NavItem to="/skills" icon={Sparkles}>
            Skills
          </NavItem>
          <NavItem to="/proposals" icon={Inbox} badge={pendingCount}>
            Proposals
          </NavItem>
        </nav>

        <div className="border-t border-(--color-border) p-2">
          <button
            onClick={() => {
              clearToken();
              window.location.assign('/ui/');
            }}
            className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-sm text-(--color-fg-muted) transition-colors hover:bg-(--color-surface-hi) hover:text-(--color-fg)"
          >
            <LogOut className="size-4" />
            Logout
          </button>
        </div>
      </aside>

      <main className="flex-1 overflow-y-auto px-8 py-8">
        <Outlet />
      </main>
    </div>
  );
}

function NavItem({
  to,
  icon: Icon,
  children,
  badge,
}: {
  to: string;
  icon: React.ComponentType<{ className?: string }>;
  children: React.ReactNode;
  badge?: number | null;
}): React.JSX.Element {
  return (
    <NavLink
      to={to}
      className={({ isActive }) =>
        cn(
          'flex items-center justify-between gap-2 rounded-md px-3 py-2 text-sm transition-colors',
          isActive
            ? 'bg-(--color-surface-hi) text-(--color-fg) font-medium'
            : 'text-(--color-fg-muted) hover:bg-(--color-surface-hi) hover:text-(--color-fg)',
        )
      }
    >
      <span className="flex items-center gap-2">
        <Icon className="size-4" />
        {children}
      </span>
      {typeof badge === 'number' && badge > 0 && (
        <Badge variant="warning" className="px-1.5 py-0">
          {badge}
        </Badge>
      )}
    </NavLink>
  );
}
