import { EmptyPanel, ErrorPanel, PageHeader, Td, Th } from "@/components/DataPanel";
import { Pager } from "@/components/Pager";
import { api } from "@/lib/api";
import { fmtDate, statusBadgeClass } from "@/lib/format";

export const dynamic = "force-dynamic";

export default async function EventsPage({
  searchParams,
}: {
  searchParams: Promise<{ cursor?: string; agent_id?: string; check_id?: string }>;
}) {
  const sp = await searchParams;
  let data;
  try {
    data = await api.queryEvents({
      agent_id: sp.agent_id,
      check_id: sp.check_id,
      cursor: sp.cursor,
    });
  } catch (e) {
    return <ErrorPanel error={e} />;
  }
  return (
    <>
      <PageHeader title="Events" count={data.items.length} />
      <form
        action="/events"
        method="get"
        className="mb-4 flex flex-wrap gap-3 text-sm items-end"
      >
        <Field label="agent_id" name="agent_id" defaultValue={sp.agent_id} />
        <Field label="check_id" name="check_id" defaultValue={sp.check_id} />
        <button
          type="submit"
          className="border border-neutral-700 px-3 py-1 hover:border-neutral-500"
        >
          query
        </button>
      </form>
      {data.items.length === 0 ? (
        <EmptyPanel />
      ) : (
        <table className="w-full text-sm">
          <thead>
            <tr>
              <Th>observed_at</Th>
              <Th>received_at</Th>
              <Th>agent_id</Th>
              <Th>check_id</Th>
              <Th>status</Th>
              <Th>exit</Th>
              <Th>duration_ms</Th>
              <Th>output</Th>
            </tr>
          </thead>
          <tbody>
            {data.items.map((e) => (
              <tr key={e.event_id}>
                <Td>{fmtDate(e.observed_at)}</Td>
                <Td>{fmtDate(e.received_at)}</Td>
                <Td>{e.agent_id}</Td>
                <Td>{e.check_id}</Td>
                <Td className={statusBadgeClass(e.status)}>{e.status}</Td>
                <Td>{e.exit_code}</Td>
                <Td>{e.duration_ms}</Td>
                <Td className="text-xs text-neutral-400 max-w-md truncate">{e.output ?? "—"}</Td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
      <Pager
        basePath="/events"
        cursor={sp.cursor}
        nextCursor={data.next_cursor}
        extra={{ agent_id: sp.agent_id, check_id: sp.check_id }}
      />
    </>
  );
}

function Field({ label, name, defaultValue }: { label: string; name: string; defaultValue?: string }) {
  return (
    <label className="flex flex-col gap-1 text-xs uppercase tracking-wide text-neutral-400">
      {label}
      <input
        name={name}
        defaultValue={defaultValue ?? ""}
        className="bg-neutral-900 border border-neutral-800 px-2 py-1 text-sm text-neutral-100 font-mono"
      />
    </label>
  );
}
