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 { RoleActions, RoleActionsFragment } from "./components/role-actions";
import { RoleDetail, RoleDetailFragment } from "./components/role-detail";

const RoleQuery = graphql(
  `
    query Role($id: ID!) {
      role(id: $id) {
        ...RoleDetail
        ...RoleActions
      }
    }
  `,
  [RoleDetailFragment, RoleActionsFragment],
);

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

  if (fetching) return <Loading />;

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

  return (
    <Layout>
      <Layout.Header title="Role Detail" />
      <Layout.Column>
        <RoleDetail role={data.role} />
      </Layout.Column>
      <Layout.Column area="right">
        <RoleActions role={data.role} />
      </Layout.Column>
    </Layout>
  );
};

RolePage.appShellPageProps = {
  meta: { title: "Role Detail" },
} satisfies AppShellPageProps;

export default RolePage;
