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 { EditCategoryForm, EditCategoryFormFragment } from "./components/edit-category-form";

const ProductCategoryForEditQuery = graphql(
  `
    query ProductCategoryForEdit($id: ID!) {
      productCategory(id: $id) {
        ...EditCategoryForm
      }
    }
  `,
  [EditCategoryFormFragment],
);

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

  if (fetching) return <Loading />;

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

  return (
    <Layout>
      <Layout.Header title="Edit Category" />
      <Layout.Column>
        <EditCategoryForm category={data.productCategory} />
      </Layout.Column>
    </Layout>
  );
};

EditCategoryPage.appShellPageProps = {
  meta: { title: "Edit Category" },
} satisfies AppShellPageProps;

export default EditCategoryPage;
