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 { EditUserForm, EditUserFormFragment } from "./components/edit-user-form";

const UserQuery = graphql(
  `
    query UserForEdit($id: ID!) {
      user(id: $id) {
        ...EditUserForm
      }
    }
  `,
  [EditUserFormFragment],
);

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

  if (fetching) return <Loading />;

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

  return (
    <Layout>
      <Layout.Header title="Edit User" />
      <Layout.Column>
        <EditUserForm user={data.user} />
      </Layout.Column>
    </Layout>
  );
};

EditUserPage.appShellPageProps = {
  meta: { title: "Edit User" },
} satisfies AppShellPageProps;

export default EditUserPage;
