import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { getRunArtifacts, listRuns } from "../api/service";
import type { RunRecord } from "../api/schemas";
import { CopyableValue } from "../components/CopyableValue";
import { CursorPagerControls } from "../components/CursorPagerControls";
import { DataTable, type Column } from "../components/DataTable";
import { PageHeader } from "../components/PageHeader";
import { Panel } from "../components/Panel";
import { StatusPill } from "../components/StatusPill";
import { useCursorPager } from "../lib/cursor";
import { formatDurationMs, formatInt, formatRelative, formatUtc } from "../lib/format";
import { useRunParam } from "../lib/run";

function RunArtifacts({ runId }: { runId: string }) {
  const artifactsQuery = useQuery({
    queryKey: ["run-artifacts", runId],
    queryFn: () => getRunArtifacts(runId),
    staleTime: 5 * 60_000,
  });

  if (artifactsQuery.isPending) return <div className="run-artifacts">Loading artifacts…</div>;
  if (artifactsQuery.isError) {
    return <div className="run-artifacts">Failed to load artifacts: {artifactsQuery.error.message}</div>;
  }
  const entries = Object.entries(artifactsQuery.data).sort(([a], [b]) => a.localeCompare(b));
  return (
    <div className="run-artifacts">
      <ul>
        {entries.map(([name, path]) => (
          <li key={name}>
            <span className="text-muted">{name}</span>
            <CopyableValue value={path} max={90} label={`artifact ${name}`} />
          </li>
        ))}
      </ul>
    </div>
  );
}

export default function RunsPage() {
  const navigate = useNavigate();
  const runParam = useRunParam();
  const pager = useCursorPager("runs");
  const [expandedRun, setExpandedRun] = useState<string | null>(null);

  const runsQuery = useQuery({
    queryKey: ["runs", "page", pager.cursor],
    queryFn: () => listRuns({ limit: 25, cursor: pager.cursor }),
    placeholderData: (prev) => prev,
  });

  const columns: Column<RunRecord>[] = [
    {
      key: "run",
      header: "Run",
      render: (run) => (
        <div>
          <div className="cell-main mono">{run.runId}</div>
          <div className="text-faint text-small">seq {run.runSeq ?? "—"}</div>
        </div>
      ),
    },
    {
      key: "validated",
      header: "Validated",
      render: (run) => <span title={formatUtc(run.validationTime)}>{formatRelative(run.validationTime)}</span>,
    },
    { key: "mode", header: "Sync mode", render: (run) => <span className="chip">{run.syncMode ?? "—"}</span> },
    { key: "wall", header: "Wall time", numeric: true, render: (run) => formatDurationMs(run.wallMs) },
    { key: "objects", header: "Objects", numeric: true, render: (run) => formatInt(run.counts?.objects) },
    { key: "vrps", header: "VRPs", numeric: true, render: (run) => formatInt(run.counts?.vrps) },
    {
      key: "rejected",
      header: "Rejected",
      numeric: true,
      render: (run) =>
        run.counts?.rejectedObjects ? (
          <span style={{ color: "var(--red-700)", fontWeight: 600 }}>{formatInt(run.counts.rejectedObjects)}</span>
        ) : (
          "0"
        ),
    },
    { key: "index", header: "Index", render: (run) => <StatusPill status={run.indexStatus} /> },
    {
      key: "actions",
      header: "",
      render: (run) => {
        const active = runParam === run.runId;
        return (
          <span style={{ display: "inline-flex", gap: 6 }} onClick={(e) => e.stopPropagation()}>
            <button
              type="button"
              className="btn small"
              disabled={active}
              onClick={() => navigate(`/?run=${encodeURIComponent(run.runId)}`)}
              aria-label={active ? `Run ${run.runId} is active` : `Use run ${run.runId}`}
            >
              {active ? "Active" : "Use run"}
            </button>
            <button
              type="button"
              className="btn small"
              onClick={() => setExpandedRun((prev) => (prev === run.runId ? null : run.runId))}
              aria-expanded={expandedRun === run.runId}
              aria-label={`Show artifacts for run ${run.runId}`}
            >
              Artifacts
            </button>
          </span>
        );
      },
    },
  ];

  return (
    <div className="page">
      <PageHeader
        title="Runs"
        subtitle="Validation runs indexed by the query service (retention: last 10 by default)"
      />
      <Panel title="Run history" flush>
        <DataTable
          columns={columns}
          rows={runsQuery.data?.items ?? []}
          rowKey={(run) => run.runId}
          loading={runsQuery.isPending}
          error={runsQuery.isError ? runsQuery.error : undefined}
          onRetry={() => runsQuery.refetch()}
          emptyTitle="No runs indexed"
          caption="Validation runs"
        />
        {expandedRun ? <RunArtifacts runId={expandedRun} /> : null}
        <CursorPagerControls
          page={pager.page}
          canPrev={pager.canPrev}
          hasNext={runsQuery.data?.nextCursor != null}
          loading={runsQuery.isFetching}
          onPrev={pager.goPrev}
          onNext={() => pager.goNext(runsQuery.data?.nextCursor ?? null)}
          itemCount={runsQuery.data?.items.length}
        />
      </Panel>
    </div>
  );
}
