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 { UserActions, UserActionsFragment } from "./components/user-actions";
import { UserDetail, UserDetailFragment } from "./components/user-detail";

const UserQuery = graphql(
  `
    query User($id: ID!) {
      user(id: $id) {
        ...UserDetail
        ...UserActions
      }
    }
  `,
  [UserDetailFragment, UserActionsFragment],
);

const UserPage = () => {
  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="User Detail" />
      <Layout.Column>
        <UserDetail user={data.user} />
      </Layout.Column>
      <Layout.Column area="right">
        <UserActions user={data.user} />
      </Layout.Column>
    </Layout>
  );
};

UserPage.appShellPageProps = {
  meta: { title: "User Detail" },
} satisfies AppShellPageProps;

export default UserPage;
