import type { GetServerSideProps } from "next";
import type { NextPageWithLayout } from "~/pages/_app";
import { zTestiEStringheStingaId } from "~/server/utils/zod_types";
import { AreaRiservataLayout } from "~/components/Layout";
import { api } from "~/utils/api";
import { Status500 } from "~/components/status-page";
import { LoadingPage } from "~/components/loading";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";

import type { TestiEStringheStingaId } from "~/schemas/public/TestiEStringhe";

type CondizioniProps = {
  stringaId: TestiEStringheStingaId;
};

const CondizioniPage: NextPageWithLayout<CondizioniProps> = ({
  stringaId,
}: CondizioniProps) => {
  const { data, isLoading } = api.settings.getStringa.useQuery({
    stringaId,
  });

  if (isLoading) {
    return <LoadingPage />;
  }
  if (!data) {
    return <Status500 />;
  }
  return (
    <div className="w-full grow space-y-4 p-4 sm:p-6">
      {data && (
        <div
          className="mx-auto prose max-w-5xl"
          dangerouslySetInnerHTML={{ __html: data.stringa_value || "" }}
        />
      )}
    </div>
  );
};

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

export default CondizioniPage;

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

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

  const parsed = zTestiEStringheStingaId.safeParse(id);
  if (!parsed.success) {
    console.error("Error parsing paymentId", 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.settings.getStringa.prefetch({
      stringaId: parsed.data,
    });

    return {
      props: {
        trpcState: helper.trpc.dehydrate(),
        stringaId: parsed.data,
      },
    };
  }
  return {
    redirect: {
      destination: "/500",
      permanent: false,
    },
  };
}) satisfies GetServerSideProps<CondizioniProps>;
