import { Layout, useParams, 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 { ProductActions, ProductActionsFragment } from "./components/product-actions";
import { ProductDetail, ProductDetailFragment } from "./components/product-detail";

const ProductQuery = graphql(
  `
    query Product($id: ID!) {
      product(id: $id) {
        ...ProductDetail
        ...ProductActions
      }
    }
  `,
  [ProductDetailFragment, ProductActionsFragment],
);

const ProductPage = () => {
  const { id } = useParams();
  const [{ data, error, fetching }, reexecuteQuery] = useQuery({
    query: ProductQuery,
    variables: { id: id! },
    context: {
      additionalTypenames: [
        "Product",
        "ProductCategoryAssignment",
        "ProductAttributeAssignment",
        "ProductVariant",
      ],
    },
  });

  if (fetching) return <Loading />;

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

  return (
    <Layout>
      <Layout.Header title="Product Detail" />
      <Layout.Column>
        <ProductDetail product={data.product} />
      </Layout.Column>
      <Layout.Column area="right">
        <ProductActions product={data.product} />
      </Layout.Column>
    </Layout>
  );
};

ProductPage.appShellPageProps = {
  meta: { title: "Product Detail" },
} satisfies AppShellPageProps;

export default ProductPage;
