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 { CategoriesTable, CategoriesTableFragment } from "./components/categories-table";

const ProductCategoriesQuery = graphql(
  `
    query ProductCategories {
      productCategories {
        ...CategoriesTable
      }
    }
  `,
  [CategoriesTableFragment],
);

const CategoriesPage = () => {
  const [{ data, error, fetching }, reexecuteQuery] = useQuery({
    query: ProductCategoriesQuery,
    context: { additionalTypenames: ["ProductCategory"] },
  });

  if (fetching) return <Loading />;

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

  return (
    <Layout>
      <Layout.Header
        title="Categories"
        actions={[
          <Button key="create" render={<Link to="create" />}>
            Create Category
          </Button>,
        ]}
      />
      <Layout.Column>
        <CategoriesTable data={data.productCategories} />
      </Layout.Column>
    </Layout>
  );
};

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

export default CategoriesPage;
