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 { generateSSGHelper } from "~/server/utils/ssgHelper";
import { FormPwSetup } from "~/forms/FormPwSetup";
import { ComeFunziona } from "~/components/come_funziona";
import { useRouter } from "next/router";
import { Button } from "~/components/ui/button";
import { ArrowRight } from "lucide-react";
import { PrezziShow } from "~/components/prezzi";
import Link from "next/link";
import { useState } from "react";

type PreOnboardServizioProps = {
  servizioId: ServizioServizioId;
};

const PreOnboardServizio: NextPageWithLayout<PreOnboardServizioProps> = ({
  servizioId,
}: PreOnboardServizioProps) => {
  const router = useRouter();
  const { data, isLoading } = api.servizio.getPreOnboardData.useQuery({
    servizioId: servizioId,
  });
  const [discalimerAccepted, setDisclaimerAccepted] = useState(false);

  if (isLoading) {
    return <LoadingPage />;
  }
  if (!data) {
    return <Status500 />;
  }
  return (
    <main className="mx-auto w-full max-w-6xl px-2 py-5 md:px-8">
      {discalimerAccepted ? (
        <FormPwSetup user={data.userData} servizioId={servizioId} />
      ) : (
        <div className="space-y-4 pb-10">
          <ComeFunziona />
          <PrezziShow />
          <div className="flex w-full flex-wrap items-center justify-center gap-4 py-4">
            <h3 className="text-xl font-semibold">
              Hai altre domande sul servizio?
            </h3>
            <Link href="/guida#faq" target="_blank">
              <Button variant="outline">Consulta le domande frequenti</Button>
            </Link>
          </div>
          <div className="flex justify-center">
            <Button
              variant="success"
              className="flex items-center gap-2 text-xl"
              onClick={async () => {
                if (data.hasPrevious) {
                  await router.push({
                    pathname: "/login",
                    query: { redirect: `/servizio/onboard/${servizioId}` },
                  });
                } else {
                  setDisclaimerAccepted(true);
                }
              }}
              size="xl"
            >
              Procedi
              <ArrowRight />
            </Button>
          </div>
        </div>
      )}
    </main>
  );
};

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

export default PreOnboardServizio;

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 trpc = generateSSGHelper();

  await trpc.servizio.getPreOnboardData.prefetch({
    servizioId: parsed.data,
  });

  return {
    props: {
      trpcState: trpc.dehydrate(),
      servizioId: parsed.data,
    },
  };
}) satisfies GetServerSideProps<PreOnboardServizioProps>;
