import { Layout, useParams, type AppShellPageProps } from "@tailor-platform/app-shell";
import { useQuery } from "urql";
import { EditRoleForm, EditRoleFormFragment } from "./components/edit-role-form";
import { graphql } from "@/graphql";
import { ErrorFallback } from "@/components/composed/error-fallback";
import { Loading } from "@/components/composed/loading";

const RoleForEditQuery = graphql(
  `
    query RoleForEdit($id: ID!) {
      role(id: $id) {
        ...EditRoleForm
      }
    }
  `,
  [EditRoleFormFragment],
);

const EditRolePage = () => {
  const { id } = useParams();
  const [{ data, error, fetching }, reexecuteQuery] = useQuery({
    query: RoleForEditQuery,
    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 columns={1} title="Edit Role">
      <Layout.Column>
        <EditRoleForm role={data.role} />
      </Layout.Column>
    </Layout>
  );
};

EditRolePage.appShellPageProps = {
  meta: { title: "Edit Role" },
} satisfies AppShellPageProps;

export default EditRolePage;
