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

type OnboardServizioProps = {
  servizioId: ServizioServizioId;
};

const OnboardServizio: NextPageWithLayout<OnboardServizioProps> = ({
  servizioId,
}: OnboardServizioProps) => {
  const { data, isLoading } = api.servizio.getAcquistoData.useQuery({
    servizioId: servizioId,
  });

  if (isLoading) {
    return <LoadingPage />;
  }
  if (!data) {
    return <Status500 />;
  }
  return (
    <div className="mx-auto w-full max-w-6xl grow space-y-6 p-2 sm:px-8 sm:py-6">
      <div className="flex justify-center">
        <h3 className="text-3xl font-bold text-primary">
          Dettagli del servizio
        </h3>
      </div>

      <FormNewServizioAcquisto initialData={data} userId={data.userData.id} />
    </div>
  );
};

OnboardServizio.getLayout = function getLayout(page) {
  return (
    <AreaRiservataLayout noSidebar noFooter>
      {page}
    </AreaRiservataLayout>
  );
};

export default OnboardServizio;

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/dashboard",
          permanent: false,
        },
      };
    }
    return {
      props: {
        trpcState: helper.trpc.dehydrate(),
        servizioId: parsed.data,
      },
    };
  }

  return {
    redirect: {
      destination: `/servizio/pre-onboard/${parsed.data}`,
      permanent: false,
    },
  };
}) satisfies GetServerSideProps<OnboardServizioProps>;
