import { Button, Layout, Link, type AppShellPageProps } from "@tailor-platform/app-shell";
import { useQuery } from "urql";
import { ErrorFallback } from "@/components/composed/error-fallback";
import { Loading } from "@/components/composed/loading";
import { graphql } from "@/graphql";
import { RolesTable, RolesTableFragment } from "./components/roles-table";

const RolesQuery = graphql(
  `
    query Roles {
      roles {
        ...RolesTable
      }
    }
  `,
  [RolesTableFragment],
);

const RolesPage = () => {
  const [{ data, error, fetching }, reexecuteQuery] = useQuery({
    query: RolesQuery,
    context: { additionalTypenames: ["Role"] },
  });

  if (fetching) return <Loading />;

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

  return (
    <Layout>
      <Layout.Header
        title="Roles"
        actions={[
          <Button key="create" render={<Link to="create" />}>
            Create Role
          </Button>,
        ]}
      />
      <Layout.Column>
        <RolesTable data={data.roles} />
      </Layout.Column>
    </Layout>
  );
};

RolesPage.appShellPageProps = {
  meta: {
    title: "Roles",
  },
  guards: [],
} satisfies AppShellPageProps;

export default RolesPage;
