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

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

// Header badges: how many jobs are running (→ the running job) and queued (→ the queue).
//
// Shown only to an account that holds `tasks`, which today means the owner — the queue runs scripts as the
// server owner and is `kind: 'execution'`. It used to render for everyone and poll `/jobs/counts` every
// three seconds regardless, so a member's console filled with 403s at 20 a minute and the header offered two
// links to a screen they cannot open. Neither is a security problem; both are the app lying about what it is.
export const JobsIndicator = () => {
  const client = useClient();
  const { can } = useCapabilities();
  const allowed = can('tasks');
  const [counts, setCounts] = useState<Counts>({ running: 0, runningJobId: null, queued: 0 });

  useEffect(() => {
    // Guarded inside the effect as well as at the render below, because the timer is the expensive half:
    // an early return in the body would still leave an interval running from a previous render.
    if (!allowed) return;
    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);
    };
  }, [allowed]);

  if (!allowed) return null;

  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>
  );
};
