import type { GetServerSideProps } from "next";
import type { NextPageWithLayout } from "~/pages/_app";
import { zOrdineId } 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 { OrdiniOrdineId } from "~/schemas/public/Ordini";
import { ReceiptGenerator } from "~/components/acquisto_receipt";

type PagamentoRecapProps = {
  ordineId: OrdiniOrdineId;
};

const PaymentRecapPage: NextPageWithLayout<PagamentoRecapProps> = ({
  ordineId,
}: PagamentoRecapProps) => {
  const { data, isLoading } = api.servizio.getOrdineRicevutaData.useQuery({
    ordineId,
  });

  if (isLoading) {
    return <LoadingPage />;
  }
  if (!data) {
    return <Status500 />;
  }
  return (
    <div className="mx-auto w-full p-4">
      <ReceiptGenerator data={data} />
    </div>
  );
};

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

export default PaymentRecapPage;

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

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

  const parsed = zOrdineId.safeParse(id);
  if (!parsed.success) {
    console.error("Error parsing ordineId", 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.getOrdineRicevutaData.prefetch({
      ordineId: parsed.data,
    });

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