import type { GetServerSideProps } from "next";
import dynamic from "next/dynamic";
import { useEffect, useState } from "react";
import { AreaRiservataLayout } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { Status500 } from "~/components/status-page";
import { Button } from "~/components/ui/button";
import { redirectTo500 } from "~/lib/utils";
import type { NextPageWithLayout } from "~/pages/_app";
import type { OrdiniOrdineId } from "~/schemas/public/Ordini";
import { generateSSGHelper } from "~/server/utils/ssgHelper";
import { zOrdineId } from "~/server/utils/zod_types";
import { api } from "~/utils/api";

const PDFViewer = dynamic(
	() => import("~/components/pdf-viewer").then((mod) => mod.PDFViewer),
	{
		ssr: false,
		loading: () => <LoadingPage />,
	},
);
type PagamentoRecapProps = {
	ordineId: OrdiniOrdineId;
};

/**
 * Pagina di ricevuta di cortesia dopo un acquisto: /servizio/ricevuta-cortesia/[ordineId]?raw=true|false
 */
const PaymentRecapPage: NextPageWithLayout<PagamentoRecapProps> = ({
	ordineId,
}: PagamentoRecapProps) => {
	const { data, isLoading } =
		api.pagamenti.getRicevutaCortesiaPdfQuery.useQuery({
			ordineId,
		});
	const [pdfUrl, setPdfUrl] = useState<string | null>(null);

	const handleDownload = (pdfData: string, title: string) => {
		const binaryString = atob(pdfData);
		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 = title;
		document.body.appendChild(link);
		link.click();
		link.remove();
		window.URL.revokeObjectURL(url);
	};

	const handlePrint = (pdfUrl: string) => {
		// 1. Create a hidden iframe
		const iframe = document.createElement("iframe");
		iframe.style.display = "none";
		iframe.src = pdfUrl;

		// 2. Wait for the PDF to load inside the iframe
		iframe.onload = () => {
			iframe.contentWindow?.focus();
			iframe.contentWindow?.print();

			// 3. Clean up (optional: wait a bit to ensure print dialog opened)
			setTimeout(() => {
				document.body.removeChild(iframe);
			}, 1000);
		};

		document.body.appendChild(iframe);
	};

	useEffect(() => {
		if (data) {
			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);
			setPdfUrl(url);
		}
	}, [data]);
	if (isLoading) {
		return <LoadingPage />;
	}
	if (!data || !pdfUrl) {
		return <Status500 />;
	}
	return (
		<div className="mx-auto w-full max-w-4xl p-4">
			<div className="space-y-6">
				<div className="flex items-center justify-between">
					<h1 className="font-bold text-2xl">Ricevuta di cortesia</h1>
					<div className="flex gap-2">
						<Button
							className="hidden sm:flex"
							onClick={() => handlePrint(pdfUrl)}
							variant="outline"
						>
							Stampa
						</Button>
						<Button onClick={() => handleDownload(data.pdf, data.title)}>
							Scarica
						</Button>
					</div>
				</div>

				<PDFViewer url={pdfUrl} />
			</div>
		</div>
	);
};

PaymentRecapPage.getLayout = function getLayout(page) {
	if (page.props.raw) {
		return <>{page}</>;
	}
	return <AreaRiservataLayout noSidebar>{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 redirectTo500;
	}

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

	const helper = generateSSGHelper();
	if (helper) {
		await helper.pagamenti.getRicevutaCortesiaPdfQuery.prefetch({
			ordineId: parsed.data,
		});

		return {
			props: {
				ordineId: parsed.data,
				trpcState: helper.dehydrate(),
			},
		};
	}
	return redirectTo500;
}) satisfies GetServerSideProps<PagamentoRecapProps>;
