import {
  Button,
  Layout,
  Link,
  useParams,
  type AppShellPageProps,
} from "@tailor-platform/app-shell";
import { useQuery } from "urql";
import { AuditEntryDetail, AuditEntryDetailFragment } from "./components/audit-entry-detail";
import { graphql } from "@/graphql";
import { ErrorFallback } from "@/components/composed/error-fallback";
import { Loading } from "@/components/composed/loading";

const AuditEntryQuery = graphql(
  `
    query AuditEntryDetail($id: ID!) {
      auditEntry(id: $id) {
        ...AuditEntryDetail
      }
    }
  `,
  [AuditEntryDetailFragment],
);

const AuditEntryPage = () => {
  const { id } = useParams();
  const [{ data, error, fetching }, reexecuteQuery] = useQuery({
    query: AuditEntryQuery,
    variables: { id: id! },
  });

  if (fetching) return <Loading />;

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

  return (
    <Layout
      columns={1}
      title="Audit Entry Detail"
      actions={[
        <Button key="back" variant="outline" render={<Link to=".." />}>
          Back to Audit Log
        </Button>,
      ]}
    >
      <Layout.Column>
        <AuditEntryDetail entry={data.auditEntry} />
      </Layout.Column>
    </Layout>
  );
};

AuditEntryPage.appShellPageProps = {
  meta: { title: "Audit Entry Detail" },
} satisfies AppShellPageProps;

export default AuditEntryPage;
