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 { EditProductForm, EditProductFormFragment } from "./components/edit-product-form";

const ProductForEditQuery = graphql(
  `
    query ProductForEdit($id: ID!) {
      product(id: $id) {
        ...EditProductForm
      }
    }
  `,
  [EditProductFormFragment],
);

const EditProductPage = () => {
  const { id } = useParams();
  const [{ data, error, fetching }, reexecuteQuery] = useQuery({
    query: ProductForEditQuery,
    variables: { id: id! },
  });

  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="Edit Product" />
      <Layout.Column>
        <EditProductForm product={data.product} />
      </Layout.Column>
    </Layout>
  );
};

EditProductPage.appShellPageProps = {
  meta: { title: "Edit Product" },
} satisfies AppShellPageProps;

export default EditProductPage;
