import { Dot } from "lucide-react";
import type { GetServerSideProps } from "next";
import Head from "next/head";
import toast from "react-hot-toast";
import { AreaRiservataLayout } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { Status500 } from "~/components/status-page";
import { LogoSvg, WhatsAppIcon } from "~/components/svgs";
import { Button } from "~/components/ui/button";
import { Card } from "~/components/ui/card";
import { replaceWithBr } from "~/lib/newlineToBr";
import { formatCurrency, redirectTo500 } from "~/lib/utils";
import type { NextPageWithLayout } from "~/pages/_app";
import type { AnnunciId } from "~/schemas/public/Annunci";
import { generateSSGHelper } from "~/server/utils/ssgHelper";
import { zAnnuncioId } from "~/server/utils/zod_types";
import { api } from "~/utils/api";

type PageProps = {
	id: AnnunciId;
};

/**
 * Pagina della scheda annuncio stampabile: /area-riservata/scheda-annuncio-stampa/[id]?raw=true
 */
const SchedaAnnuncioPage: NextPageWithLayout<PageProps> = ({
	id,
}: PageProps) => {
	const { data, isLoading } = api.annunci.getSchedaAnnuncioData.useQuery({
		id,
	});

	const { mutate: generatePdf } = api.annunci.getSchedaAnnuncioPdf.useMutation({
		onMutate: () => {
			toast.loading("Generazione PDF in corso...", {
				id: "generate-pdf",
			});
		},
		onSuccess: (data) => {
			if (!data) {
				toast.error("PDF non disponibile al momento. Riprova più tardi.", {
					id: "generate-pdf",
				});
				return;
			}
			toast.success("PDF generato con successo!", {
				id: "generate-pdf",
			});

			const binaryString = atob(data.pdf);
			const bytes = Uint8Array.from(binaryString, (c) => c.charCodeAt(0));
			const blob = new Blob([bytes], {
				type: "application/pdf",
			});
			const url = window.URL.createObjectURL(blob);
			const link = document.createElement("a");
			link.href = url;
			link.download = data.title;
			document.body.appendChild(link);
			link.click();
			link.remove();
			window.URL.revokeObjectURL(url);
			toast.dismiss("generate-pdf");
		},
		onError: (error) => {
			toast.error(`Errore durante la generazione del PDF: ${error.message}`, {
				id: "generate-pdf",
			});
		},
	});

	const companyAddress =
		"Via Beata Giovanna, 1 a Bassano del Grappa (VI)\nTel. +39 0424529869\nEmail: arca@infoalloggi.it";

	if (isLoading) {
		return <LoadingPage />;
	}
	if (!data) {
		return <Status500 />;
	}

	return (
		<>
			<Head>
				<title>Scheda Annuncio {data.codice}</title>
			</Head>
			<div className="mx-auto w-full max-w-4xl p-4">
				<div className="space-y-6">
					<div className="flex flex-wrap items-center justify-between gap-4">
						<h1 className="font-bold text-2xl">Scheda Annuncio Stampabile</h1>
						<div className="flex gap-2">
							<Button onClick={() => generatePdf({ id })}>
								Scarica Scheda
							</Button>
						</div>
					</div>
					<Card className="p-4">
						<div className="space-y-8">
							<div className="flex items-start justify-between">
								<div>
									<LogoSvg className="h-10 w-auto" />
								</div>

								<div className="relative">
									<p className="text-right font-semibold text-lg">
										Arcenia Srl
									</p>
									<p className="whitespace-pre-line text-right text-sm">
										{companyAddress}
									</p>
								</div>
							</div>
							<div className="space-y-2 text-center">
								<h2 className="font-bold text-primary text-xl">
									{data.titolo_it || "Immobile in Affitto"}
								</h2>
								<p className="text-lg text-muted-foreground">
									Riferimento: <strong>{data.codice}</strong>
								</p>
							</div>
							<div className="rounded-lg bg-primary/5 p-4 outline-2 outline-green-500">
								<h3 className="mb-2 inline-flex items-center gap-2 font-semibold text-lg text-primary">
									<WhatsAppIcon className="size-6 fill-green-500 stroke-green-500" />{" "}
									Contatti
									<span className="text-base">
										(mandare un messaggio WhatsApp prima di chiamare)
									</span>
								</h3>
								<div className="space-y-1">
									<p>{data.nominativo}</p>
									{data.numero && (
										<p className="font-semibold">Tel. {data.numero}</p>
									)}
								</div>
							</div>

							<div className="grid grid-cols-1 gap-6 pb-1">
								<div className="space-y-3">
									<h3 className="border-b pb-1 font-semibold text-lg">
										Indirizzo
									</h3>
									<div className="flex items-center gap-8">
										<p className="font-semibold">{data.indirizzo}</p>
									</div>
								</div>
							</div>

							<div className="space-y-3">
								<div className="grid grid-cols-3 gap-4 text-sm">
									{data.tipo && (
										<div className="rounded bg-gray-100 p-3">
											<p className="font-medium text-primary">Tipologia</p>
											<p className="font-bold text-xl">Affitto {data.tipo}</p>
										</div>
									)}
									{data.prezzo && (
										<div className="rounded bg-gray-100 p-3">
											<p className="font-medium text-primary">Canone Mensile</p>
											<p className="font-bold text-xl">
												{formatCurrency(data.prezzo / 100)}
											</p>
										</div>
									)}

									<div className="rounded bg-gray-100 p-3">
										<p className="font-medium text-primary">Disponibile da</p>
										<p className="font-bold text-xl">{data.disponibile_da}</p>
									</div>
								</div>
							</div>

							<div className="space-y-3">
								<h3 className="border-b pb-1 font-semibold text-lg">
									Dotazioni e Servizi
								</h3>
								<div className="grid grid-cols-3 gap-2 text-sm">
									{data.caratteristiche.map((item) => {
										if (!item[1]) return null;
										return (
											<div
												className="flex items-center justify-start gap-1"
												key={item[0]}
											>
												<Dot className="size-5" />
												<span className="font-semibold">{item[0]}:</span>
												<span>{item[1]}</span>
											</div>
										);
									})}
								</div>
							</div>

							{/* Description */}
							{data.desc_it && (
								<>
									<div className="space-y-3">
										<h3 className="border-b pb-1 font-semibold text-lg">
											Descrizione
										</h3>
										<div className="text-justify text-sm leading-relaxed">
											<p
												dangerouslySetInnerHTML={{
													__html: replaceWithBr(data.desc_it),
												}}
											></p>
										</div>
									</div>
								</>
							)}
							<div className="mx-auto max-w-2xl pt-2 text-center text-muted-foreground text-xs">
								<p>
									Informazione strettamente riservata ed indirizzata all'Utente
									Arca-Infoalloggi nel rispetto dell' Art. F. Precisazione dei
									Tuoi Obblighi e responsabilità delle Condizioni Generali di
									Contratto (CGC) accettate
								</p>
							</div>
						</div>
					</Card>
				</div>
			</div>
		</>
	);
};

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

export default SchedaAnnuncioPage;

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

	if (typeof id !== "string") {
		console.error("Error: id is not a string");
		return redirectTo500;
	}

	const parsed = zAnnuncioId.safeParse(parseInt(id));
	if (!parsed.success) {
		console.error("Error parsing ordineId", parsed.error);
		return redirectTo500;
	}

	const helper = generateSSGHelper();

	await helper.annunci.getSchedaAnnuncioData.prefetch({
		id: parsed.data,
	});

	return {
		props: {
			id: parsed.data,
			trpcState: helper.dehydrate(),
		},
	};
}) satisfies GetServerSideProps<PageProps>;
