import { useState, useEffect } from 'react';
import { Link } from 'react-router';
import { Loader2, ListOrdered } from 'lucide-react';
import { useClient } from 'hooks/useClient';

type Counts = { running: number; runningJobId: string | null; queued: number };

// Always-present header badges: how many jobs are running (→ the running job) and queued (→ the queue).
export const JobsIndicator = () => {
  const client = useClient();
  const [counts, setCounts] = useState<Counts>({ running: 0, runningJobId: null, queued: 0 });

  useEffect(() => {
    let alive = true;
    const load = () => client.get<Counts>('/jobs/counts').then((c) => alive && setCounts(c)).catch(() => {});
    load();
    const timer = setInterval(load, 3000);
    return () => { alive = false; clearInterval(timer); };
  }, []);

  const pill = 'flex items-center gap-1 h-8 px-2.5 rounded-full text-xs font-semibold tabular-nums transition-colors';

  return (
    <div className="flex items-center gap-1.5">
      <Link
        to={counts.runningJobId ? `/jobs/${counts.runningJobId}` : '/jobs'}
        title={counts.running ? 'Running job' : 'Nothing running'}
        className={`${pill} text-white ${counts.running ? 'bg-blue-500/60 hover:bg-blue-500/75' : 'bg-black/25 hover:bg-black/35'}`}
      >
        <Loader2 className={`h-3.5 w-3.5 ${counts.running ? 'animate-spin' : ''}`} />
        {counts.running}
      </Link>
      <Link
        to="/jobs"
        title="Queued jobs"
        className={`${pill} text-white ${counts.queued ? 'bg-amber-500/70 hover:bg-amber-500/85' : 'bg-black/25 hover:bg-black/35'}`}
      >
        <ListOrdered className="h-3.5 w-3.5" />
        {counts.queued}
      </Link>
    </div>
  );
};
