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 { AttributesTable, AttributesTableFragment } from "./components/attributes-table";

const ProductAttributesQuery = graphql(
  `
    query ProductAttributes {
      productAttributes {
        ...AttributesTable
      }
    }
  `,
  [AttributesTableFragment],
);

const AttributesPage = () => {
  const [{ data, error, fetching }, reexecuteQuery] = useQuery({
    query: ProductAttributesQuery,
    context: { additionalTypenames: ["ProductAttribute"] },
  });

  if (fetching) return <Loading />;

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

  return (
    <Layout>
      <Layout.Header
        title="Attributes"
        actions={[
          <Button key="create" render={<Link to="create" />}>
            Create Attribute
          </Button>,
        ]}
      />
      <Layout.Column>
        <AttributesTable data={data.productAttributes} />
      </Layout.Column>
    </Layout>
  );
};

AttributesPage.appShellPageProps = {
  meta: {
    title: "Attributes",
  },
} satisfies AppShellPageProps;

export default AttributesPage;
