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 { ProductsTable, ProductsTableFragment } from "./components/products-table";

const ProductsQuery = graphql(
  `
    query Products {
      products {
        ...ProductsTable
      }
    }
  `,
  [ProductsTableFragment],
);

const ProductsPage = () => {
  const [{ data, error, fetching }, reexecuteQuery] = useQuery({
    query: ProductsQuery,
    context: { additionalTypenames: ["Product"] },
  });

  if (fetching) return <Loading />;

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

  return (
    <Layout>
      <Layout.Header
        title="Products"
        actions={[
          <Button key="create" render={<Link to="create" />}>
            Create Product
          </Button>,
        ]}
      />
      <Layout.Column>
        <ProductsTable data={data.products} />
      </Layout.Column>
    </Layout>
  );
};

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

export default ProductsPage;
