import { LogOut, Search, Loader2 } from 'lucide-react';
import { useAuth } from '../lib/auth';
import { useQuery } from '@tanstack/react-query';
import { api } from '../lib/api-client';
import { Button } from '../components/ui/primitives';
import { Badge } from '../components/ui/primitives';
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
} from '../components/ui/dropdown';

interface Props {
  onOpenPalette: () => void;
}

export function Topbar({ onOpenPalette }: Props) {
  const { user, logout } = useAuth();

  const jobsQuery = useQuery({
    queryKey: ['jobs-overview'],
    queryFn: () => api.get<{ pending: number; running: number; failed: number }>('/jobs/stats'),
    refetchInterval: 10_000,
  });

  const running = jobsQuery.data?.running ?? 0;
  const pending = jobsQuery.data?.pending ?? 0;
  const failed = jobsQuery.data?.failed ?? 0;

  return (
    <header className="h-14 flex items-center justify-between border-b border-[#333] px-6 bg-[#0A0A0A]">
      <button
        onClick={onOpenPalette}
        className="flex items-center gap-2 text-xs text-[#666] hover:text-[#F5F5F5] transition-colors bg-[#141414] border border-[#333] rounded-md px-3 py-1.5 min-w-[320px]"
      >
        <Search className="h-3.5 w-3.5" />
        <span>Zoek producten, feeds, acties…</span>
        <kbd className="ml-auto text-[10px] bg-[#0A0A0A] border border-[#333] rounded px-1.5 py-0.5">Ctrl K</kbd>
      </button>

      <div className="flex items-center gap-3">
        {(running > 0 || pending > 0 || failed > 0) && (
          <a href="/cms/jobs" className="flex items-center gap-2 text-xs">
            {running > 0 && (
              <Badge variant="info" className="flex items-center gap-1">
                <Loader2 className="h-3 w-3 animate-spin" />
                {running} draait
              </Badge>
            )}
            {pending > 0 && <Badge variant="muted">{pending} wacht</Badge>}
            {failed > 0 && <Badge variant="danger">{failed} mislukt</Badge>}
          </a>
        )}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="sm" className="text-xs">
              {user?.email}
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent>
            <DropdownMenuLabel>{user?.email}</DropdownMenuLabel>
            <DropdownMenuLabel className="text-[#999] normal-case tracking-normal">Rol: {user?.role}</DropdownMenuLabel>
            <DropdownMenuSeparator />
            <DropdownMenuItem onSelect={() => logout()}>
              <LogOut className="h-3.5 w-3.5" /> Uitloggen
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </header>
  );
}
