import { degrees, PDFDocument } from "pdf-lib";

type RicevutaData = {
	codice_fiscale: string;
	date: string;
	indirizzo: string;
	nominativo: string;
	pack1_codice: string;
	pack1_titolo: string;
	pack1_qnt: string;
	pack1_importo: string;
	pack1_iva: string;
	totale: string;
};
export const genRicevutaUfficio = async (data: RicevutaData) => {
	try {
		// 1. Fetch the PDF template
		const formUrl = "/ricevuta_basic.pdf";
		const formPdfBytes = await fetch(formUrl).then((res) => res.arrayBuffer());

		// 2. Load the PDFDocument
		const pdfDoc = await PDFDocument.load(formPdfBytes);

		// 3. Get the form
		const form = pdfDoc.getForm();
		//console.log(form.getFields().map((field) => field.getName()));

		// 4. Safely fill fields with Type Casting
		// We use try/catch or optional checks in case the field names change in the PDF
		const codiceFiscaleField = form.getTextField("codice_fiscale");
		const dataField = form.getTextField("data");
		const indirizzoField = form.getTextField("indirizzo");
		const nominativoField = form.getTextField("nominativo");
		const pack1CodiceField = form.getTextField("pack1_codice");
		const pack1TitoloField = form.getTextField("pack1_titolo");
		const pack1QntField = form.getTextField("pack1_qnt");
		const pack1ImportoField = form.getTextField("undefined.pack1_importo");
		const pack1IvaField = form.getTextField("pack1_iva");
		const totaleField = form.getTextField("undefined.totale");

		if (codiceFiscaleField) codiceFiscaleField.setText(data.codice_fiscale);
		if (dataField) dataField.setText(data.date);
		if (indirizzoField) indirizzoField.setText(data.indirizzo);
		if (nominativoField) nominativoField.setText(data.nominativo);
		if (pack1CodiceField) pack1CodiceField.setText(data.pack1_codice);
		if (pack1TitoloField) pack1TitoloField.setText(data.pack1_titolo);
		if (pack1QntField) pack1QntField.setText(data.pack1_qnt);
		if (pack1ImportoField) pack1ImportoField.setText(data.pack1_importo);
		if (pack1IvaField) pack1IvaField.setText(data.pack1_iva);
		if (totaleField) totaleField.setText(data.totale);

		// 5. Flatten the form (prevents users from editing the values in the preview)
		//form.flatten();

		const pages = pdfDoc.getPages();
		pages[0]?.setRotation(degrees(180));

		// 6. Serialize to Uint8Array
		const pdfBytes: Uint8Array = await pdfDoc.save();

		// 7. Create Blob and Open in New Tab
		const blob = new Blob([pdfBytes.buffer as ArrayBuffer], {
			type: "application/pdf",
		});
		const url = URL.createObjectURL(blob);

		const newTab = window.open(url, "_blank");

		// Focus the new tab if it was blocked or loses focus
		if (newTab) {
			newTab.focus();
		} else {
			alert("Please allow popups to view the PDF");
		}
	} catch (error) {
		console.error("Error generating PDF:", error);
	}
};
