import type { GetServerSideProps } from "next";
import type { NextPageWithLayout } from "~/pages/_app";
import { AreaRiservataLayoutUserView } from "~/components/Layout";
import { type ServizioServizioId } from "~/schemas/public/Servizio";
import { api } from "~/utils/api";
import { zServizioId } from "~/server/utils/zod_types";
import { FormNewServizioAcquisto } from "~/forms/FormNewServizioAcquisto";
import { LoadingPage } from "~/components/loading";
import { Status500 } from "~/components/status-page";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import type { UsersId } from "~/schemas/public/Users";

type OnboardUserProps = {
  servizioId: ServizioServizioId;
  userId: UsersId;
};
const OnboardUser: NextPageWithLayout<OnboardUserProps> = ({
  servizioId,
}: OnboardUserProps) => {
  const { data, isLoading } = api.servizio.getAcquistoData.useQuery({
    servizioId,
  });

  if (isLoading) {
    return <LoadingPage />;
  }
  if (!data) {
    return <Status500 />;
  }
  return (
    <div className="mx-auto max-w-7xl grow space-y-4">
      <div className="flex justify-between">
        <h3 className="text-primary text-2xl font-bold">
          Onboarding Utente (Versione Admin)
        </h3>
      </div>
      <FormNewServizioAcquisto
        initialData={data}
        userId={data.userData.id}
        isAdmin
      />
    </div>
  );
};
export default OnboardUser;

export const getServerSideProps = (async (context) => {
  const id = context.params?.servizioId;

  if (typeof id !== "string") {
    console.error("Error: servizioId is not a string");
    return {
      redirect: {
        destination: "/500",
        permanent: false,
      },
    };
  }

  const parsed = zServizioId.safeParse(id);
  if (!parsed.success) {
    console.error("Error parsing servizioId", parsed.error);
    return {
      redirect: {
        destination: "/500",
        permanent: false,
      },
    };
  }

  const access_token = context.req.cookies.access_token;

  const helper = await TrpcAuthedFetchingIstance({ access_token });
  if (helper) {
    await helper.trpc.servizio.getAcquistoData.prefetch({
      servizioId: parsed.data,
    });
    const servizio = await helper.trpc.servizio.getServizio.fetch({
      servizioId: parsed.data,
    });

    if (
      !servizio ||
      servizio.isOkAcconto ||
      servizio.isInterrotto ||
      servizio.decorrenza !== null
    ) {
      return {
        redirect: {
          destination: `/area-riservata/admin/user-view/servizio/${servizio.user_id}`,
          permanent: false,
        },
      };
    }
    return {
      props: {
        trpcState: helper.trpc.dehydrate(),
        userId: servizio.user_id,
        servizioId: parsed.data,
      },
    };
  }

  return {
    redirect: {
      destination: `/area-riservata/admin/utenti`,
      permanent: false,
    },
  };
}) satisfies GetServerSideProps<OnboardUserProps>;

OnboardUser.getLayout = function getLayout(page) {
  return <AreaRiservataLayoutUserView>{page}</AreaRiservataLayoutUserView>;
};
