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 { UsersTable, UsersTableFragment } from "./components/users-table";

const UsersQuery = graphql(
  `
    query Users {
      users {
        ...UsersTable
      }
    }
  `,
  [UsersTableFragment],
);

const UsersPage = () => {
  const [{ data, error, fetching }, reexecuteQuery] = useQuery({
    query: UsersQuery,
    context: { additionalTypenames: ["User"] },
  });

  if (fetching) return <Loading />;

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

  return (
    <Layout>
      <Layout.Header
        title="Users"
        actions={[
          <Button key="create" render={<Link to="create" />}>
            Create User
          </Button>,
        ]}
      />
      <Layout.Column>
        <UsersTable data={data.users} />
      </Layout.Column>
    </Layout>
  );
};

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

export default UsersPage;
