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

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

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

  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
      columns={1}
      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;
