import { Layout, type AppShellPageProps } from "@tailor-platform/app-shell";
import { useQuery } from "urql";
import { AuditEntriesTable, AuditEntriesTableFragment } from "./components/audit-entries-table";
import { graphql } from "@/graphql";
import { ErrorFallback } from "@/components/composed/error-fallback";
import { Loading } from "@/components/composed/loading";

const AuditEntriesQuery = graphql(
  `
    query AuditEntries {
      auditEntries(order: [{ field: createdAt, direction: Desc }]) {
        ...AuditEntriesTable
      }
    }
  `,
  [AuditEntriesTableFragment],
);

const AuditPage = () => {
  const [{ data, error, fetching }, reexecuteQuery] = useQuery({
    query: AuditEntriesQuery,
  });

  if (fetching) return <Loading />;

  if (error || !data) {
    return (
      <ErrorFallback
        title="Failed to load audit log"
        message="An error occurred while fetching the audit log."
        onReset={() => reexecuteQuery({ requestPolicy: "network-only" })}
      />
    );
  }

  return (
    <Layout columns={1} title="Audit Log">
      <Layout.Column>
        <AuditEntriesTable data={data.auditEntries} />
      </Layout.Column>
    </Layout>
  );
};

AuditPage.appShellPageProps = {
  meta: {
    title: "Audit Log",
  },
  guards: [],
} satisfies AppShellPageProps;

export default AuditPage;
