import { Loader2, CheckCircle2, XCircle, Clock, Gauge, Brain, Download, Wrench } from 'lucide-react';
import type { ControlJob } from '@/hooks/useControlStream';

/**
 * B1: Unified Job Center. Surfaces every control_job (bench / eval / pull /
 * action) the operator initiated, with live status — so pull/bench/eval are no
 * longer black holes. Fed by the already-buffered fleet.jobs (deduped by jobId).
 */
export function JobsTab({ jobs }: { jobs: ControlJob[] }) {
  // Newest first.
  const ordered = [...jobs].sort((a, b) => (a.ts < b.ts ? 1 : a.ts > b.ts ? -1 : 0));

  if (ordered.length === 0) {
    return (
      <div className="flex items-center justify-center h-full">
        <p className="text-sm text-muted-foreground">No jobs yet. Bench, eval, and model-pull runs appear here live.</p>
      </div>
    );
  }

  return (
    <div className="flex-1 overflow-auto p-4">
      <div className="space-y-2">
        {ordered.map((job) => (
          <JobRow key={job.jobId} job={job} />
        ))}
      </div>
    </div>
  );
}

function kindIcon(job: ControlJob) {
  const detailKind = (job.detail as { kind?: string } | undefined)?.kind;
  if (detailKind === 'pull') return Download;
  if (job.jobType === 'bench') return Gauge;
  if (job.jobType === 'eval') return Brain;
  return Wrench;
}

function statusBits(status: ControlJob['status']) {
  switch (status) {
    case 'completed': return { Icon: CheckCircle2, cls: 'text-green-400', label: 'completed' };
    case 'failed': return { Icon: XCircle, cls: 'text-red-400', label: 'failed' };
    case 'running': return { Icon: Loader2, cls: 'text-blue-400 animate-spin', label: 'running' };
    default: return { Icon: Clock, cls: 'text-amber-400', label: 'queued' };
  }
}

function JobRow({ job }: { job: ControlJob }) {
  const KindIcon = kindIcon(job);
  const { Icon, cls, label } = statusBits(job.status);
  const detail = (job.detail ?? {}) as Record<string, unknown>;
  const kind = (detail.kind as string) ?? job.jobType;
  const repo = detail.repo as string | undefined;
  const model = detail.model as string | undefined;
  const pct = detail.percent as number | undefined;
  const err = detail.error as string | undefined;
  const summary = repo ?? model ?? job.jobId;

  return (
    <div className="border border-border/40 rounded-lg p-3 bg-card/50 flex items-center gap-3">
      <KindIcon className="size-4 text-muted-foreground shrink-0" />
      <div className="min-w-0 flex-1">
        <div className="flex items-center gap-2">
          <span className="text-sm font-medium capitalize">{kind}</span>
          <span className="text-xs font-mono text-muted-foreground truncate">{summary}</span>
        </div>
        <div className="text-[11px] text-muted-foreground mt-0.5">
          {new Date(job.ts).toLocaleTimeString()}
          {typeof pct === 'number' && job.status === 'running' && <span> · {pct}%</span>}
          {err && <span className="text-red-400"> · {String(err).slice(0, 120)}</span>}
        </div>
      </div>
      <span className={`inline-flex items-center gap-1 text-xs ${cls}`}>
        <Icon className="size-3.5" />
        {label}
      </span>
    </div>
  );
}
