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 { CategoryActions, CategoryActionsFragment } from "./components/category-actions";
import { CategoryDetail, CategoryDetailFragment } from "./components/category-detail";

const ProductCategoryQuery = graphql(
  `
    query ProductCategory($id: ID!) {
      productCategory(id: $id) {
        ...CategoryDetail
        ...CategoryActions
      }
    }
  `,
  [CategoryDetailFragment, CategoryActionsFragment],
);

const CategoryPage = () => {
  const { id } = useParams();
  const [{ data, error, fetching }, reexecuteQuery] = useQuery({
    query: ProductCategoryQuery,
    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="Category Detail" />
      <Layout.Column>
        <CategoryDetail category={data.productCategory} />
      </Layout.Column>
      <Layout.Column area="right">
        <CategoryActions category={data.productCategory} />
      </Layout.Column>
    </Layout>
  );
};

CategoryPage.appShellPageProps = {
  meta: { title: "Category Detail" },
} satisfies AppShellPageProps;

export default CategoryPage;
