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 { AttributeActions, AttributeActionsFragment } from "./components/attribute-actions";
import { AttributeDetail, AttributeDetailFragment } from "./components/attribute-detail";

const AttributeQuery = graphql(
  `
    query ProductAttribute($id: ID!) {
      productAttribute(id: $id) {
        ...AttributeDetail
        ...AttributeActions
      }
    }
  `,
  [AttributeDetailFragment, AttributeActionsFragment],
);

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

  if (fetching) return <Loading />;

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

  return (
    <Layout>
      <Layout.Header title="Attribute Detail" />
      <Layout.Column>
        <AttributeDetail attribute={data.productAttribute} />
      </Layout.Column>
      <Layout.Column area="right">
        <AttributeActions attribute={data.productAttribute} />
      </Layout.Column>
    </Layout>
  );
};

AttributePage.appShellPageProps = {
  meta: { title: "Attribute Detail" },
} satisfies AppShellPageProps;

export default AttributePage;
