import { db } from "@/db/client";
import { maintenanceJobs } from "@/db/schema";
import { desc, sql } from "drizzle-orm";

export const dynamic = "force-dynamic";

function formatWhen(value: Date | null) {
  return value ? value.toISOString().slice(0, 16).replace("T", " ") : "—";
}

function formatDuration(ms: number | null) {
  if (ms === null) return "—";
  if (ms < 1000) return ms + " ms";
  if (ms < 60_000) return (ms / 1000).toFixed(1) + " s";
  return Math.round(ms / 60_000) + " min";
}

// "skipped" is deliberately neutral rather than a warning. Backup and archive
// live on a host that is powered off most of the time, so a scan declining to
// run is the system behaving correctly, not a fault.
const STATUS_STYLE: Record<string, string> = {
  running: "border-admin-accent text-admin-accent",
  succeeded: "border-admin-good text-admin-good",
  skipped: "border-admin-line text-admin-muted",
  failed: "border-admin-warn text-admin-warn",
};

export default async function AdminJobsPage() {
  const runs = await db
    .select()
    .from(maintenanceJobs)
    .orderBy(desc(maintenanceJobs.startedAt))
    .limit(100);

  // Latest outcome per job, so the health of the whole schedule reads at a glance.
  const latest = await db.execute<{
    job: string;
    status: string;
    started_at: Date;
    duration_ms: number | null;
    detail: string | null;
    runs: number;
    failures: number;
  }>(sql`
    select distinct on (job)
           job, status, started_at, duration_ms, detail,
           count(*) over (partition by job)::int runs,
           count(*) filter (where status = 'failed') over (partition by job)::int failures
      from maintenance_jobs
     order by job, started_at desc`);

  return (
    <div className="space-y-6">
      <div>
        <p className="text-xs font-semibold uppercase tracking-[0.32em] text-admin-accent">Maintenance</p>
        <h1 className="mt-2 font-serif text-3xl font-semibold">Jobs</h1>
        <p className="mt-2 max-w-3xl text-sm text-admin-muted">
          Everything that touches the filesystem runs in the <code>ampelos-maintenance</code> container: scanning,
          probing, metadata, and the placement classifier. This dashboard only reads storage — write access lives
          in that container so nothing reachable from the network can modify media.
        </p>
      </div>

      <section className="admin-panel overflow-hidden">
        <div className="border-b border-admin-line px-5 py-4">
          <h2 className="font-serif text-xl font-semibold">Current State</h2>
        </div>
        <div className="divide-y divide-admin-line">
          {latest.rows.length ? latest.rows.map((row) => (
            <div key={row.job} className="grid gap-2 px-5 py-3 lg:grid-cols-[1fr_7rem_9rem_6rem_1fr] lg:items-center">
              <p className="font-mono text-sm">{row.job}</p>
              <span className={"justify-self-start rounded-md border px-2 py-0.5 text-xs font-semibold uppercase " + (STATUS_STYLE[row.status] ?? "border-admin-line")}>
                {row.status}
              </span>
              <p className="text-xs text-admin-muted">{formatWhen(row.started_at)}</p>
              <p className="text-xs text-admin-muted">{formatDuration(row.duration_ms)}</p>
              <p className="truncate text-xs text-admin-muted" title={row.detail ?? ""}>
                {row.detail ?? (row.failures ? row.failures + " of " + row.runs + " runs failed" : "")}
              </p>
            </div>
          )) : (
            <p className="p-5 text-sm text-admin-muted">
              No maintenance job has reported yet. Start the container with
              <code className="mx-1">docker compose -f maintenance/docker-compose.yml up -d</code>.
            </p>
          )}
        </div>
      </section>

      <section className="admin-panel overflow-hidden">
        <div className="border-b border-admin-line px-5 py-4">
          <h2 className="font-serif text-xl font-semibold">Recent Runs</h2>
        </div>
        <div className="divide-y divide-admin-line">
          {runs.map((run) => (
            <details key={run.id} className="px-5 py-3">
              <summary className="flex cursor-pointer flex-wrap items-center gap-3">
                <span className={"rounded-md border px-2 py-0.5 text-xs font-semibold uppercase " + (STATUS_STYLE[run.status] ?? "border-admin-line")}>
                  {run.status}
                </span>
                <span className="font-mono text-sm">{run.job}</span>
                <span className="text-xs text-admin-muted">{formatWhen(run.startedAt)}</span>
                <span className="text-xs text-admin-muted">{formatDuration(run.durationMs)}</span>
                <span className="text-xs text-admin-muted">{run.trigger}</span>
                {run.detail ? <span className="text-xs text-admin-warn">{run.detail}</span> : null}
              </summary>
              {run.output ? (
                <pre className="mt-2 max-h-80 overflow-auto rounded-md border border-admin-line bg-admin-subpanel p-3 text-xs text-admin-muted">
                  {run.output}
                </pre>
              ) : (
                <p className="mt-2 text-xs text-admin-muted">No output captured.</p>
              )}
            </details>
          ))}
          {!runs.length ? <p className="p-5 text-sm text-admin-muted">Nothing recorded yet.</p> : null}
        </div>
      </section>
    </div>
  );
}
