import type { GetServerSideProps } from "next";
import type { NextPageWithLayout } from "~/pages/_app";
import { zAnnuncioId, zServizioId } from "~/server/utils/zod_types";
import { AreaRiservataLayout } from "~/components/Layout";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { api } from "~/utils/api";
import { LoadingPage } from "~/components/loading";
import type { ServizioServizioId } from "~/schemas/public/Servizio";
import type { AnnunciId } from "~/schemas/public/Annunci";
import { Status500 } from "~/components/status-page";
import { DocNotFoundPage } from "~/components/doc_not_found";
import { FileSection } from "~/components/servizio/conferma";
import { Button } from "~/components/ui/button";
import { useRouter } from "next/router";
import { ArrowLeft } from "lucide-react";

type RiapriConfermaProps = {
  servizioId: ServizioServizioId;
  annuncioId: AnnunciId;
};

const RiapriConferma: NextPageWithLayout<RiapriConfermaProps> = ({
  servizioId,
  annuncioId,
}: RiapriConfermaProps) => {
  const { data, isLoading } = api.servizio.getServizioAnnuncio.useQuery({
    servizioId,
    annuncioId,
  });
  const router = useRouter();

  if (isLoading) return <LoadingPage />;
  if (!data) return <Status500 />;
  if (!data.doc_conferma_ref) return <DocNotFoundPage />;
  return (
    <div className="mx-2 flex flex-1 overflow-auto">
      <div className="mx-auto flex grow sm:grow-0">
        <div className="flex flex-col items-center space-y-4 py-4">
          <h1 className="text-xl font-bold">Conferma Immobile</h1>
          <p className="text-center">
            Il documento sottostante riassume le condizioni della locazione tra
            te e il proprietario
          </p>

          <FileSection storageId={data.doc_conferma_ref} />

          <div className="flex max-w-3xl flex-col gap-2 rounded-md bg-green-400 p-4 text-left">
            <p className="text-xl font-semibold">
              Per confermare l&apos;immobile procedi al bonifico di caparra!
            </p>
            <p>Coordinate bancarie:</p>
            <p>Intestazione: {data.caparra_intestazione || ""}</p>
            <p>IBAN: {data.caparra_iban || ""}</p>
            <p>Importo: {data.caparra_importo || ""}</p>
            <p>Causale: {data.caparra_causale || ""}</p>
            <p className="text-xl font-semibold">
              Mandaci la contabile del bonifico una volta effettuato!
            </p>
          </div>
          <Button
            onClick={() => router.back()}
            variant="secondary"
            className="mx-auto mb-4 flex items-center gap-2"
          >
            <ArrowLeft className="size-5" />
            Torna indietro
          </Button>
        </div>
      </div>
    </div>
  );
};

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

export default RiapriConferma;

export const getServerSideProps = (async (context) => {
  const slug = context.params?.slug;
  if (!slug || slug.length != 2) {
    return {
      notFound: true,
    };
  }
  const [servizioId, annuncioId] = slug;
  if (!servizioId || !annuncioId) {
    return {
      notFound: true,
    };
  }

  const parsedServizioId = zServizioId.safeParse(servizioId);
  const parsedAnnuncioId = zAnnuncioId.safeParse(parseInt(annuncioId));

  if (!parsedServizioId.success || !parsedAnnuncioId.success) {
    return {
      notFound: true,
    };
  }

  const access_token = context.req.cookies.access_token;

  const helper = await TrpcAuthedFetchingIstance({ access_token });
  if (helper) {
    await helper.trpc.servizio.getServizioAnnuncio.prefetch({
      servizioId: parsedServizioId.data,
      annuncioId: parsedAnnuncioId.data,
    });

    return {
      props: {
        servizioId: parsedServizioId.data,
        annuncioId: parsedAnnuncioId.data,
        trpcState: helper.trpc.dehydrate(),
      },
    };
  }
  return {
    redirect: {
      destination: "/500",
      permanent: false,
    },
  };
}) satisfies GetServerSideProps<RiapriConfermaProps>;
