import { useQuery } from "@tanstack/react-query";

import { api } from "../../api/client";
import { Page } from "../../components/Page";
import { Table } from "../../components/Table";

const columns = [
  { key: "event", label: "Event" },
  { key: "entity", label: "Entity" },
  { key: "status", label: "Status" },
  { key: "time", label: "Time" }
];

export function AuditPage() {
  const query = useQuery({
    queryKey: ["audit"],
    queryFn: api.audit
  });

  const rows = query.data?.map((event) => ({
    event: event.event_type,
    entity: event.entity_type,
    status: event.status,
    time: event.created_at
  })) ?? [];

  return (
    <Page title="Audit Logs" subtitle="Review authentication, provisioning, and admin activity.">
      {query.isError ? <p className="notice">Unable to load audit events from the API.</p> : null}
      <Table
        columns={columns}
        rows={rows}
        renderCell={(row, column) => <span>{row[column.key as keyof (typeof rows)[number]]}</span>}
      />
    </Page>
  );
}
