import { apiHandler, db } from "@/helpers/api";
const stripe = require("stripe")(
	"sk_test_51S13vN1KgrIVv8H79oDFDNOoHLuV82a5ewRoTYWbXOLQJRLMcMUfZa4Q90i9dD1cJSzsLAKrOqYfL55DAltqNQSn00wa2uusEe"
);
import axios from "axios";
import crypto from "crypto";

import AWS from "aws-sdk";
import { PDFDocument, StandardFonts, rgb } from "pdf-lib";
import fs from "fs";
import path from "path";

export default apiHandler({
	post: verifyOrder,
});

function removeDiacritics(text) {
	if (!text) return "";
	return text
		.replace(/ă/g, "a")
		.replace(/Ă/g, "A")
		.replace(/â/g, "a")
		.replace(/Â/g, "A")
		.replace(/î/g, "i")
		.replace(/Î/g, "I")
		.replace(/ș/g, "s")
		.replace(/Ș/g, "S")
		.replace(/ț/g, "t")
		.replace(/Ț/g, "T");
}

function stripHTML(html) {
	if (!html) return "";
	return html
		.replace(/<[^>]*>/g, " ") // Elimină toate tag-urile HTML
		.replace(/&nbsp;/g, " ") // Înlocuiește &nbsp;
		.replace(/&amp;/g, "&") // Înlocuiește &amp;
		.replace(/&lt;/g, "<") // Înlocuiește &lt;
		.replace(/&gt;/g, ">") // Înlocuiește &gt;
		.replace(/&quot;/g, '"') // Înlocuiește &quot;
		.replace(/&#39;/g, "'") // Înlocuiește &#39;
		.replace(/\s+/g, " ") // Înlocuiește multiple spații cu una singură
		.trim(); // Elimină spațiile de la început și sfârșit
}

async function generateInstructionsPDF(order, items) {
	try {
		console.log("📄 Start generare PDF instructiuni...");

		// Creează un document PDF nou
		const pdfDoc = await PDFDocument.create();

		// Încarcă fonturile
		const boldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
		const regularFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
		const italicFont = await pdfDoc.embedFont(StandardFonts.HelveticaOblique);

		// Constante pentru formatare
		const pageWidth = 595; // A4 width in points
		const pageHeight = 842; // A4 height in points
		const margin = 50;
		const contentWidth = pageWidth - margin * 2;
		const lineHeight = 20;
		const titleSize = 18;
		const subtitleSize = 14;
		const textSize = 11;

		// Prima pagină - Titlu
		let currentPage = pdfDoc.addPage([pageWidth, pageHeight]);
		let yPosition = pageHeight - 100;

		// Titlu principal centrat (fără diacritice)
		const titleText = removeDiacritics(`Instructiuni de utilizare pentru produsele`);
		const titleText2 = removeDiacritics(`comandate din comanda #${order.id}`);

		const titleWidth = boldFont.widthOfTextAtSize(titleText, titleSize);
		const titleWidth2 = boldFont.widthOfTextAtSize(titleText2, titleSize);

		currentPage.drawText(titleText, {
			x: (pageWidth - titleWidth) / 2,
			y: yPosition,
			size: titleSize,
			font: boldFont,
			color: rgb(0, 0, 0),
		});

		yPosition -= lineHeight + 5;

		currentPage.drawText(titleText2, {
			x: (pageWidth - titleWidth2) / 2,
			y: yPosition,
			size: titleSize,
			font: boldFont,
			color: rgb(0, 0, 0),
		});

		yPosition -= lineHeight * 2;

		// Linie decorativă
		currentPage.drawLine({
			start: { x: margin, y: yPosition },
			end: { x: pageWidth - margin, y: yPosition },
			thickness: 2,
			color: rgb(0, 0, 0),
		});

		yPosition -= lineHeight * 2;

		// Data generării
		const currentDate = new Date().toLocaleDateString("ro-RO", {
			year: "numeric",
			month: "long",
			day: "numeric",
		});

		const dateText = removeDiacritics(`Generat la: ${currentDate}`);
		currentPage.drawText(dateText, {
			x: margin,
			y: yPosition,
			size: textSize,
			font: italicFont,
			color: rgb(0.3, 0.3, 0.3),
		});

		yPosition -= lineHeight * 2;

		// Parcurge fiecare produs și adaugă instrucțiunile
		for (let i = 0; i < items.length; i++) {
			const item = items[i];

			// Găsește produsul în baza de date pentru a lua descrierea
			let productDesc = "";
			try {
				const product = await db.Products.findOne({
					where: { sku: item.sku || item.id },
				});

				if (product && product.desc) {
					productDesc = removeDiacritics(stripHTML(product.desc));
				} else {
					productDesc = removeDiacritics("Nu sunt disponibile instructiuni pentru acest produs.");
				}
			} catch (dbError) {
				console.error(`⚠️ Eroare citire produs ${item.sku}:`, dbError.message);
				productDesc = removeDiacritics("Nu sunt disponibile instructiuni pentru acest produs.");
			}

			// Verifică dacă trebuie o pagină nouă pentru acest produs
			if (yPosition < 150) {
				currentPage = pdfDoc.addPage([pageWidth, pageHeight]);
				yPosition = pageHeight - margin;
			}

			// Titlu produs (fără diacritice)
			// Titlu produs (fără diacritice) - cu word wrap pentru titluri lungi
			const productTitle = removeDiacritics(`${i + 1}. ${item.name || "Produs"}`);

			// Word wrap pentru titlul produsului
			const titleWords = productTitle.split(" ");
			let titleLine = "";
			const maxTitleWidth = contentWidth;

			for (const word of titleWords) {
				const testLine = titleLine + word + " ";
				const testWidth = boldFont.widthOfTextAtSize(testLine, subtitleSize);

				if (testWidth > maxTitleWidth && titleLine !== "") {
					// Verifică dacă trebuie pagină nouă
					if (yPosition < margin + 50) {
						currentPage = pdfDoc.addPage([pageWidth, pageHeight]);
						yPosition = pageHeight - margin;
					}

					currentPage.drawText(titleLine.trim(), {
						x: margin,
						y: yPosition,
						size: subtitleSize,
						font: boldFont,
						color: rgb(0, 0, 0),
					});

					titleLine = word + " ";
					yPosition -= lineHeight;
				} else {
					titleLine = testLine;
				}
			}

			// Afișează ultima linie a titlului
			if (titleLine.trim() !== "") {
				if (yPosition < margin + 50) {
					currentPage = pdfDoc.addPage([pageWidth, pageHeight]);
					yPosition = pageHeight - margin;
				}

				currentPage.drawText(titleLine.trim(), {
					x: margin,
					y: yPosition,
					size: subtitleSize,
					font: boldFont,
					color: rgb(0, 0, 0),
				});

				yPosition -= lineHeight;
			}

			// SKU și cantitate (fără diacritice)
			const productInfo = removeDiacritics(`SKU: ${item.sku || "N/A"} | Cantitate: ${item.quantity || 1} buc`);
			currentPage.drawText(productInfo, {
				x: margin + 10,
				y: yPosition,
				size: textSize - 1,
				font: italicFont,
				color: rgb(0.4, 0.4, 0.4),
			});

			yPosition -= lineHeight * 1.5;

			// Linie separatoare subtilă
			currentPage.drawLine({
				start: { x: margin, y: yPosition },
				end: { x: pageWidth - margin, y: yPosition },
				thickness: 0.5,
				color: rgb(0.7, 0.7, 0.7),
			});

			yPosition -= lineHeight;

			// Procesează și afișează descrierea (instrucțiunile) - DEJA fără diacritice
			const words = productDesc.split(" ");
			let line = "";
			const maxLineWidth = contentWidth - 20;

			for (const word of words) {
				const testLine = line + word + " ";
				const testWidth = regularFont.widthOfTextAtSize(testLine, textSize);

				if (testWidth > maxLineWidth && line !== "") {
					// Verifică dacă trebuie pagină nouă
					if (yPosition < margin + 50) {
						currentPage = pdfDoc.addPage([pageWidth, pageHeight]);
						yPosition = pageHeight - margin;
					}

					currentPage.drawText(line.trim(), {
						x: margin + 10,
						y: yPosition,
						size: textSize,
						font: regularFont,
						color: rgb(0, 0, 0),
					});

					line = word + " ";
					yPosition -= lineHeight;
				} else {
					line = testLine;
				}
			}

			// Afișează ultima linie
			if (line.trim() !== "") {
				if (yPosition < margin + 50) {
					currentPage = pdfDoc.addPage([pageWidth, pageHeight]);
					yPosition = pageHeight - margin;
				}

				currentPage.drawText(line.trim(), {
					x: margin + 10,
					y: yPosition,
					size: textSize,
					font: regularFont,
					color: rgb(0, 0, 0),
				});

				yPosition -= lineHeight;
			}

			// Spațiu între produse
			yPosition -= lineHeight * 1.5;

			// Linie separatoare între produse
			if (i < items.length - 1) {
				if (yPosition < margin + 50) {
					currentPage = pdfDoc.addPage([pageWidth, pageHeight]);
					yPosition = pageHeight - margin;
				}

				currentPage.drawLine({
					start: { x: margin, y: yPosition },
					end: { x: pageWidth - margin, y: yPosition },
					thickness: 1,
					color: rgb(0.8, 0.8, 0.8),
					dashArray: [3, 3],
				});

				yPosition -= lineHeight * 2;
			}
		}

		// Adaugă footer pe ultima pagină (fără diacritice)
		const footerText = removeDiacritics(
			"Pentru intrebari suplimentare, va rugam sa ne contactati la contact@emagyl.ro"
		);
		const footerY = 30;
		const footerWidth = regularFont.widthOfTextAtSize(footerText, textSize - 2);

		currentPage.drawText(footerText, {
			x: (pageWidth - footerWidth) / 2,
			y: footerY,
			size: textSize - 2,
			font: italicFont,
			color: rgb(0.5, 0.5, 0.5),
		});

		// Salvează PDF-ul
		const pdfBytes = await pdfDoc.save();
		console.log("✅ PDF instructiuni generat, marime:", pdfBytes.length, "bytes");

		// Configurează AWS S3
		AWS.config.update({
			accessKeyId: process.env.AWS_ACCESS_KEY_ID || "AKIA2AFW3Y3GU5WK2Y6G",
			secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || "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",
			region: "eu-north-1",
		});

		const s3 = new AWS.S3();
		const fileName = `instructions/${order.id}_${Date.now()}.pdf`;

		const s3Params = {
			Bucket: process.env.AWS_S3_BUCKET || "emagyl",
			Key: fileName,
			Body: Buffer.from(pdfBytes),
			ContentType: "application/pdf",
			ContentDisposition: `attachment; filename="instructiuni_comanda_${order.id}.pdf"`,
			ACL: "public-read",
		};

		// Upload în S3
		console.log("📤 Upload PDF instructiuni in S3...");
		const uploadResult = await s3.upload(s3Params).promise();
		console.log("✅ PDF instructiuni uploadat:", uploadResult.Location);

		// Returnează URL-ul cu CloudFront
		const formattedUrl = uploadResult.Location.replace(
			"https://emagyl.s3.eu-north-1.amazonaws.com",
			"https://d372xxb7fb1cod.cloudfront.net"
		);

		return formattedUrl;
	} catch (error) {
		console.error("❌ EROARE generare PDF instructiuni:", error.message);
		console.error("Stack:", error.stack);
		throw error;
	}
}

async function generateWarrantyCertificate(order, items) {
	try {
		const templatePath = path.join(process.cwd(), "public", "certificat.pdf");

		if (!fs.existsSync(templatePath)) {
			console.error("❌ Template-ul certificat.pdf NU EXISTĂ la calea:", templatePath);
			throw new Error(`Template certificat.pdf nu există la: ${templatePath}`);
		}

		const existingPdfBytes = fs.readFileSync(templatePath);
		const pdfDoc = await PDFDocument.load(existingPdfBytes);

		const pages = pdfDoc.getPages();
		const page = pages[0];

		const font = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
		const regularFont = await pdfDoc.embedFont(StandardFonts.Helvetica);

		const purchaseDate = new Date().toLocaleDateString("ro-RO");
		const clientName = order.Denumire || "Client";

		let deliverAddress = "";
		let deliverAddress2 = "";

		if (order.Adresa) {
			deliverAddress = order.Adresa.substring(0, Math.min(20, order.Adresa.length));
			if (order.Adresa.length > 20) {
				deliverAddress2 = order.Adresa.substring(20, Math.min(order.Adresa.length, 60));
			}
		}

		page.drawText(clientName, { x: 428, y: 724.6, size: 12, font });
		page.drawText(deliverAddress, { x: 490, y: 710, size: 12, font });
		page.drawText(deliverAddress2, { x: 389, y: 695, size: 12, font });
		page.drawText(order.IdExtern || "", { x: 485, y: 681, size: 12, font });
		page.drawText(purchaseDate, { x: 475, y: 666, size: 12, font });
		page.drawText(purchaseDate, { x: 45, y: 100, size: 12, font });

		const newPage = pdfDoc.addPage([610, 842]);
		const { width, height } = newPage.getSize();

		const margin = 40;
		const tableWidth = width - margin * 2;
		const tableX = margin;
		const tableY = height - 80;
		const rowHeight = 30;
		const col1Width = tableWidth - 100;

		newPage.drawRectangle({
			x: tableX,
			y: tableY,
			width: tableWidth,
			height: rowHeight,
			borderColor: rgb(0, 0, 0),
			borderWidth: 1,
		});

		newPage.drawLine({
			start: { x: tableX + col1Width, y: tableY },
			end: { x: tableX + col1Width, y: tableY + rowHeight },
			color: rgb(0, 0, 0),
			thickness: 1,
		});

		newPage.drawText("Denumire Produs", {
			x: tableX + 10,
			y: tableY + rowHeight / 2 - 5,
			size: 12,
			font: font,
		});

		newPage.drawText("Cantitate", {
			x: tableX + col1Width + 20,
			y: tableY + rowHeight / 2 - 5,
			size: 12,
			font: font,
		});

		items.forEach((product, index) => {
			const rowY = tableY - (index + 1) * rowHeight;

			newPage.drawRectangle({
				x: tableX,
				y: rowY,
				width: tableWidth,
				height: rowHeight,
				borderColor: rgb(0, 0, 0),
				borderWidth: 1,
			});

			newPage.drawLine({
				start: { x: tableX + col1Width, y: rowY },
				end: { x: tableX + col1Width, y: rowY + rowHeight },
				color: rgb(0, 0, 0),
				thickness: 1,
			});

			const productName = product.Denumire || "Produs necunoscut";
			const quantity = product.NrProduse || 1;

			newPage.drawText(productName, {
				x: tableX + 10,
				y: rowY + rowHeight / 2 - 5,
				size: 11,
				font: regularFont,
			});

			newPage.drawText(quantity.toString(), {
				x: tableX + col1Width + 35,
				y: rowY + rowHeight / 2 - 5,
				size: 11,
				font: regularFont,
			});
		});

		const pdfBytes = await pdfDoc.save();

		AWS.config.update({
			accessKeyId: process.env.AWS_ACCESS_KEY_ID || "AKIA2AFW3Y3GU5WK2Y6G",
			secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || "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",
			region: "eu-north-1",
		});

		const s3 = new AWS.S3();
		const fileName = `certificates/${order.IdExtern}_${Date.now()}.pdf`;

		const s3Params = {
			Bucket: process.env.AWS_S3_BUCKET || "emagyl",
			Key: fileName,
			Body: Buffer.from(pdfBytes),
			ContentType: "application/pdf",
			ContentDisposition: `attachment; filename="${fileName}"`,
			ACL: "public-read",
		};

		const uploadResult = await s3.upload(s3Params).promise();

		return uploadResult.Location;
	} catch (error) {
		console.error("❌ EROARE generare certificat:", error.message);
		console.error("Stack:", error.stack);
		throw error;
	}
}

async function verifyOrder(req, res) {
	const sessionId = req.body.sessionId;

	if (!db.initialized) await db.initialize();

	try {
		const session = await stripe.checkout.sessions.retrieve(sessionId);
		const order = await db.Orders.findOne({ where: { sessionID: session.id } });

		if (session.payment_status === "paid" && order) {
			order.status = "paid";
			order.userID = req.body.userID || 0;
			await order.save();

			let items;
			try {
				items = typeof order.items === "string" ? JSON.parse(order.items) : order.items;
				console.log("✅ Items parsed:", items.length, "produse");
			} catch (parseError) {
				console.error("❌ Eroare parsare items:", parseError.message);
				return res.status(200).json({ page: "/contul-meu" });
			}

			try {
				console.log("📄 Start generare factură FGO...");
				const fgoResponse = await generateFGOInvoice(order, items);
				if (fgoResponse && fgoResponse.Success) {
					order.bill_number = fgoResponse.Factura.Numar;
					order.bill_series = fgoResponse.Factura.Serie;
					order.bill = fgoResponse.Factura.Link;
					await order.save();
					console.log("✅ Factură FGO generată");
				}
			} catch (fgoError) {
				console.error("⚠️ Eroare FGO (non-critical):", fgoError.message);
			}

			try {
				console.log("📦 Start procesare comandă AVEX...");
				await processAvexOrder(order, items);
				console.log("✅ Comandă AVEX procesată");
			} catch (avexError) {
				console.error("⚠️ Eroare AVEX (non-critical):", avexError.message);
			}

			try {
				console.log("📜 Start generare certificat garanție...");

				const certificateOrder = {
					Denumire:
						order.pf_nume_familie && order.pf_prenume
							? `${order.pf_nume_familie} ${order.pf_prenume}`
							: order.pj_nume_firma || "Client",
					Adresa: order.pf_adresa || order.pj_adresa || "",
					IdExtern: order.id.toString(),
				};

				const certificateItems = items.map((item) => ({
					Denumire: item.name || "Produs",
					NrProduse: parseInt(item.quantity) || 1,
				}));

				const certificateUrl = await generateWarrantyCertificate(certificateOrder, certificateItems);
				const formattedUrl = certificateUrl.replace(
					"https://emagyl.s3.eu-north-1.amazonaws.com",
					"https://d372xxb7fb1cod.cloudfront.net"
				);

				order.certificate = formattedUrl;

				await order.save();

				const instructionsUrl = await generateInstructionsPDF(order, items);
				const formattedInstructionsUrl = instructionsUrl.replace(
					"https://emagyl.s3.eu-north-1.amazonaws.com",
					"https://d372xxb7fb1cod.cloudfront.net"
				);

				order.informations = formattedInstructionsUrl;

                    await order.save(); 

				console.log("✅ Certificat salvat în order.certificate:", certificateUrl);
			} catch (certificateError) {
				console.error("⚠️ Eroare generare certificat (non-critical):", certificateError.message);
			}

			return res.status(200).json({
				page: "/contul-meu",
				success: true,
			});
		} else {
			if (order) {
				order.status = "failed";
				await order.save();
			}
			return res.status(200).json({ page: "/problem-order", problemID: 3 });
		}
	} catch (error) {
		console.error("Stripe/Verify error:", error);
		return res.status(200).json({ page: "/problem-order", problemID: 4 });
	}
}

async function generateFGOInvoice(order, items) {
	try {
		const codUnic = "50155117";
		const cheiePriva = "313B37B9C004633A0C89E87179B64E01";
		const serie = "MAG";

		const clientData = prepareClientDataForFGO(order);

		const hashString = codUnic + cheiePriva + clientData.Denumire;
		const hash = crypto.createHash("sha1").update(hashString).digest("hex").toUpperCase();

		const fgoPayload = {
			CodUnic: codUnic,
			Hash: hash,
			Valuta: "RON",
			TipFactura: "Factura",
			Serie: serie,
			IdExtern: order.id.toString(),
			PlatformaUrl: process.env.SITE_URL || "https://emagyl.ro",
			Client: clientData,
			Continut: formatItemsForFGO(items),
		};

		const response = await axios.post("https://api.fgo.ro/v1/factura/emitere", fgoPayload, {
			headers: {
				"Content-Type": "application/json",
				Authorization: "Bearer 313B37B9C004633A0C89E87179B64E01",
			},
			timeout: 30000,
		});

		console.log("FGO Response:", response.data);
		return response.data;
	} catch (error) {
		console.error("Eroare FGO API:", {
			message: error.message,
			status: error.response?.status,
			data: error.response?.data,
		});
		throw error;
	}
}

function prepareClientDataForFGO(order) {
	if (order.pf_nume_familie && order.pf_prenume) {
		return {
			Denumire: `${order.pf_nume_familie} ${order.pf_prenume}`,
			CodUnic: "",
			Tip: "PF",
			Tara: "RO",
			Judet: "",
			Localitate: order.pf_judet_oras || "",
			Adresa: order.pf_adresa || "",
			Email: order.email || "",
			Telefon: order.pf_numar_telefon || "",
			IdExtern: order.id.toString(),
		};
	}

	if (order.pj_nume_firma) {
		return {
			Denumire: order.pj_nume_firma,
			CodUnic: order.pj_cui || "",
			NrRegCom: order.pj_reg_com || "",
			Tip: "PJ",
			Tara: "RO",
			Judet: order.pj_judet || "",
			Localitate: order.pj_localitate || "",
			Adresa: order.pj_adresa || "",
			Email: order.pj_email || "",
			Telefon: order.pj_numar_telefon || "",
			PlatitorTVA: true,
			IdExtern: order.id.toString(),
		};
	}

	return {
		Denumire: "Client Necunoscut",
		Tip: "PF",
		Tara: "RO",
		Judet: "",
		IdExtern: order.id.toString(),
	};
}

function formatItemsForFGO(items) {
	const products = items.map((item) => ({
		Denumire: item.name,
		CodArticol: item.sku || "",
		UM: "buc",
		NrProduse: parseFloat(item.quantity),
		PretUnitar: parseFloat(item.price),
		CotaTVA: 21,
	}));

	const transportCost = {
		Denumire: "Cost transport",
		CodArticol: "TRANSPORT",
		UM: "buc",
		NrProduse: 1,
		PretUnitar: 25.0,
		CotaTVA: 21,
	};

	return [...products, transportCost];
}

async function processAvexOrder(order, items) {
	try {
		const awbUrl = "https://emagyl.s3.eu-north-1.amazonaws.com/awb.pdf";
		const awbResponse = await axios.get(awbUrl, {
			responseType: "arraybuffer",
			timeout: 15000,
		});
		const awbBase64 = Buffer.from(awbResponse.data).toString("base64");

		const avexPayload = {
			order_id: order.id,
			notes: order.pf_mentiuni || order.pj_mentiuni || "Comanda online",
			recipient:
				order.pf_nume_familie && order.pf_prenume
					? `${order.pf_nume_familie} ${order.pf_prenume}`
					: order.pj_nume_firma,
			products: items.map((item) => ({
				product_code: item.sku,
				amount: parseInt(item.quantity),
			})),
			awb: {
				file_content: awbBase64,
			},
		};

		const avexResponse = await axios.post("https://api.avex.ro/orders/add_order", avexPayload, {
			headers: {
				"Content-Type": "application/json",
				Authorization: `Bearer ${process.env.AVEX_API_KEY}`,
			},
			timeout: 30000,
		});

		console.log("AVEX response:", avexResponse.data);

		if (avexResponse.data && avexResponse.data.id) {
			order.avex_order_id = avexResponse.data.id;
			await order.save();
		}
	} catch (avexError) {
		console.error("Eroare AVEX:", {
			message: avexError.message,
			status: avexError.response?.status,
			data: avexError.response?.data,
		});
		throw avexError;
	}
}
