'use client';

import { useEffect, useState } from 'react';
import { apiFetch } from '@/lib/api';
import { StatusPill } from '@/components/status-pill';

interface Row {
  build: {
    id: string;
    version: number;
    prompt: string;
    status: string;
    errorMessage: string | null;
    startedAt: string | null;
    finishedAt: string | null;
    createdAt: string;
  };
  server: { id: string; name: string; slug: string };
  org: { id: string; name: string };
}

const STATUS_FILTERS = ['', 'success', 'failed', 'queued', 'generating', 'building', 'deploying', 'cancelled'];

export default function AdminBuildsPage() {
  const [rows, setRows] = useState<Row[] | null>(null);
  const [status, setStatus] = useState('');

  useEffect(() => {
    apiFetch<{ builds: Row[] }>(`/v1/admin/builds${status ? `?status=${status}` : ''}`)
      .then((r) => setRows(r.builds))
      .catch(() => setRows([]));
  }, [status]);

  return (
    <div className="px-8 py-8">
      <header className="mb-6">
        <h1 className="text-[22px] font-semibold tracking-tight">Builds</h1>
        <p className="mt-1 text-[13px] text-[--color-fg-muted]">
          Every spec → image → deploy run across the fleet.
        </p>
      </header>

      <div className="mb-4 flex gap-2">
        <select
          value={status}
          onChange={(e) => setStatus(e.target.value)}
          className="h-8 rounded-md border border-[--color-border] bg-[--color-bg-subtle] px-2 text-[13px] focus:border-[--color-accent] focus:outline-none"
        >
          {STATUS_FILTERS.map((s) => (
            <option key={s} value={s}>
              {s ? s : 'All statuses'}
            </option>
          ))}
        </select>
      </div>

      <div className="panel">
        {rows === null && (
          <p className="px-4 py-3 text-[12.5px] text-[--color-fg-muted]">Loading…</p>
        )}
        {rows && rows.length === 0 && (
          <p className="px-4 py-12 text-center text-[13px] text-[--color-fg-muted]">No builds.</p>
        )}
        {rows && rows.length > 0 && (
          <table className="w-full text-[12px]">
            <thead className="border-b border-[--color-border] text-[--color-fg-subtle]">
              <tr>
                <th className="px-4 py-2 text-left font-medium">When</th>
                <th className="px-4 py-2 text-left font-medium">Server</th>
                <th className="px-4 py-2 text-left font-medium">Org</th>
                <th className="px-4 py-2 text-left font-medium">Status</th>
                <th className="px-4 py-2 text-left font-medium">Prompt / Error</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((r) => (
                <tr key={r.build.id} className="border-b border-[--color-border] last:border-0 align-top">
                  <td className="px-4 py-2 mono text-[--color-fg-muted] whitespace-nowrap">
                    {new Date(r.build.createdAt).toLocaleString()}
                    <div className="text-[10px] text-[--color-fg-subtle]">v{r.build.version}</div>
                  </td>
                  <td className="px-4 py-2">
                    <div className="font-medium">{r.server.name}</div>
                    <div className="mono text-[10.5px] text-[--color-fg-subtle]">{r.server.slug}</div>
                  </td>
                  <td className="px-4 py-2 text-[--color-fg-muted]">{r.org.name}</td>
                  <td className="px-4 py-2">
                    <StatusPill status={r.build.status as never} />
                  </td>
                  <td className="px-4 py-2 mono text-[--color-fg-muted] max-w-[500px]">
                    {r.build.errorMessage ? (
                      <div className="text-[--color-danger] whitespace-pre-wrap">
                        {r.build.errorMessage}
                      </div>
                    ) : (
                      <div className="line-clamp-3 whitespace-pre-wrap">{r.build.prompt}</div>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
