import { Layout, useParams, type AppShellPageProps } from "@tailor-platform/app-shell";
import { useQuery } from "urql";
import { RoleDetail, RoleDetailFragment } from "./components/role-detail";
import { RoleActions } from "./components/role-actions";
import { graphql } from "@/graphql";
import { ErrorFallback } from "@/components/composed/error-fallback";
import { Loading } from "@/components/composed/loading";

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

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 />
      </Layout.Column>
    </Layout>
  );
};

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

export default RolePage;
