"use client";

import { useQuery } from "@tanstack/react-query";
import { Activity } from "lucide-react";
import Link from "next/link";
import { PageHeader } from "@/components/page-header";
import { StatusPill } from "@/components/status";
import { Badge, EmptyState, Mono, Panel, PageLoader } from "@/components/ui";
import { api } from "@/lib/api";
import { relativeTime } from "@/lib/utils";

export default function RunsPage() {
  const runs = useQuery({ queryKey: ["runs"], queryFn: api.listRuns, refetchInterval: 5000 });

  return (
    <div>
      <PageHeader
        eyebrow="Operate"
        title="Runs"
        description="Every agent and workflow execution, reconstructable step by step."
      />
      {runs.isLoading ? (
        <PageLoader />
      ) : (runs.data ?? []).length === 0 ? (
        <EmptyState
          icon={<Activity className="h-8 w-8" />}
          title="No runs yet"
          description="Run an agent or fire a workflow to see it appear here in real time."
        />
      ) : (
        <Panel className="p-0">
          <div className="divide-y divide-line">
            {(runs.data ?? []).map((run) => (
              <Link
                key={run.id}
                href={`/runs/${run.id}`}
                className="flex items-center gap-4 px-5 py-4 transition-colors hover:bg-surface-2/40"
              >
                <StatusPill status={run.status} />
                <Mono className="text-faint">{run.id.slice(0, 8)}</Mono>
                <Badge>{run.workflow_id ? "workflow" : "agent"}</Badge>
                <div className="flex-1" />
                <span className="hidden text-xs text-muted sm:block">{run.total_steps} steps</span>
                <span className="hidden font-mono text-xs text-faint md:block">
                  {run.total_tokens.toLocaleString()} tok
                </span>
                <span className="text-xs text-faint">{relativeTime(run.created_at)}</span>
              </Link>
            ))}
          </div>
        </Panel>
      )}
    </div>
  );
}
