import { db } from "@/helpers/api";
import nodemailer from "nodemailer";

const stripe = require("stripe")(
	"sk_test_51S13vN1KgrIVv8H79oDFDNOoHLuV82a5ewRoTYWbXOLQJRLMcMUfZa4Q90i9dD1cJSzsLAKrOqYfL55DAltqNQSn00wa2uusEe"
);

async function sendOrderConfirmationEmail(orderData, cartProducts) {
	try {
		const transporter = nodemailer.createTransport({
			host: "mail.emagyl.ro",
			port: 465,
			secure: "465",
			auth: {
				user: "noreply@emagyl.ro",
				pass: "$}*UC#8S-0U2XL+H",
			},
		});

		const subtotal = cartProducts.reduce((sum, product) => {
			const price =
				product.priceReduced != null ? parseFloat(product.priceReduced) : parseFloat(product.price);
			return sum + price * product.quantity;
		}, 0);

		const transport = 25;
		const totalFaraTVA = subtotal + transport;
		const TVA = totalFaraTVA * 0.21;
		const totalCuTVA = totalFaraTVA + TVA;

		const productsHTML = cartProducts
			.map((product) => {
				const price =
					product.priceReduced != null ? parseFloat(product.priceReduced) : parseFloat(product.price);
				const priceWithTVA = price * 1.21;
				const totalProduct = priceWithTVA * product.quantity;

				return `
				<tr>
					<td style="padding: 12px; border-bottom: 1px solid #eee;">
						<strong>${product.name}</strong><br>
						<span style="color: #666; font-size: 12px;">SKU: ${product.sku || "N/A"}</span>
					</td>
					<td style="padding: 12px; border-bottom: 1px solid #eee; text-align: center;">${product.quantity}</td>
					<td style="padding: 12px; border-bottom: 1px solid #eee; text-align: right;">${priceWithTVA.toFixed(2)} RON</td>
					<td style="padding: 12px; border-bottom: 1px solid #eee; text-align: right;"><strong>${totalProduct.toFixed(
						2
					)} RON</strong></td>
				</tr>
			`;
			})
			.join("");

		// Generează HTML pentru adresa de livrare
		let deliveryAddressHTML = "";
		if (orderData.billingType === 0) {
			deliveryAddressHTML = `
				<p><strong>Nume:</strong> ${orderData.pf_prenume} ${orderData.pf_nume_familie}</p>
				<p><strong>Adresă:</strong> ${orderData.pf_adresa}, ${orderData.pf_judet_oras}, ${orderData.pf_tara}</p>
				<p><strong>Telefon:</strong> ${orderData.pf_numar_telefon}</p>
				${orderData.pf_mentiuni ? `<p><strong>Mențiuni:</strong> ${orderData.pf_mentiuni}</p>` : ""}
			`;
		} else {
			deliveryAddressHTML = `
				<p><strong>Firmă:</strong> ${orderData.pj_nume_firma}</p>
				<p><strong>CUI:</strong> ${orderData.pj_cui}</p>
				<p><strong>Nr. Reg. Com.:</strong> ${orderData.pj_nr_reg}</p>
				<p><strong>Adresă facturare:</strong> ${orderData.pj_adresa}, ${orderData.pj_localitate}, ${orderData.pj_judet}</p>
				<p><strong>Adresă livrare:</strong> ${orderData.pj_adresa_livrare}</p>
				<p><strong>Telefon:</strong> ${orderData.pj_numar_telefon}</p>
				<p><strong>Bancă:</strong> ${orderData.pj_banca} - ${orderData.pj_iban}</p>
				${orderData.pj_mentiuni ? `<p><strong>Mențiuni:</strong> ${orderData.pj_mentiuni}</p>` : ""}
			`;
		}

		const emailHTML = `
			<!DOCTYPE html>
			<html>
			<head>
				<meta charset="UTF-8">
				<style>
					body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; }
					.container { max-width: 650px; margin: 0 auto; padding: 20px; background-color: #ffffff; }
					.header { background: linear-gradient(135deg, #007bff 0%, #2da4d0ff 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
					.header h1 { margin: 0; font-size: 28px; }
					.content { padding: 30px; background-color: #f9f9f9; }
					.order-info { background-color: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
					.order-info h2 { color: #007bff; margin-top: 0; border-bottom: 2px solid #007bff; padding-bottom: 10px; }
					table { width: 100%; border-collapse: collapse; background-color: white; margin: 20px 0; }
					th { background-color: #007bff; color: white; padding: 12px; text-align: left; }
					.totals { background-color: white; padding: 20px; border-radius: 8px; margin-top: 20px; }
					.totals-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #eee; }
					.totals-row.final { font-size: 20px; font-weight: bold; color: #007bff; border-bottom: none; margin-top: 10px; }
					.footer { text-align: center; padding: 20px; color: #666; font-size: 14px; }
					.success-badge { background-color: #4caf50; color: white; padding: 10px 20px; border-radius: 20px; display: inline-block; margin: 20px 0; }
				</style>
			</head>
			<body>
				<div class="container">
					<div class="header">
						<h1>✅ Comanda Ta a Fost Plasată!</h1>
						<div class="success-badge">Comandă Confirmată</div>
					</div>
					
					<div class="content">
						<div class="order-info">
							<h2>📦 Detalii Comandă</h2>
							<p><strong>ID Comanda:</strong> ${orderData.id}</p>
							<p><strong>Status:</strong> <span style="color: #ff9800; font-weight: bold;">În așteptare (Pending)</span></p>
							<p><strong>Data:</strong> ${new Date().toLocaleDateString("ro-RO", {
								year: "numeric",
								month: "long",
								day: "numeric",
								hour: "2-digit",
								minute: "2-digit",
							})}</p>
						</div>

						<div class="order-info">
							<h2>📍 Adresă Livrare</h2>
							${deliveryAddressHTML}
						</div>

						<div class="order-info">
							<h2>🛒 Produse Comandate</h2>
							<table>
								<thead>
									<tr>
										<th>Produs</th>
										<th style="text-align: center;">Cantitate</th>
										<th style="text-align: right;">Preț unitar</th>
										<th style="text-align: right;">Total</th>
									</tr>
								</thead>
								<tbody>
									${productsHTML}
									<tr>
										<td style="padding: 12px; border-bottom: 1px solid #eee;">
											<strong>Transport</strong>
										</td>
										<td style="padding: 12px; border-bottom: 1px solid #eee; text-align: center;">1</td>
										<td style="padding: 12px; border-bottom: 1px solid #eee; text-align: right;">${(transport * 1.21).toFixed(2)} RON</td>
										<td style="padding: 12px; border-bottom: 1px solid #eee; text-align: right;"><strong>${(transport * 1.21).toFixed(
											2
										)} RON</strong></td>
									</tr>
								</tbody>
							</table>
						</div>

						<div class="totals">
							<div class="totals-row">
								<span>Subtotal produse:</span>
								<span>${subtotal.toFixed(2)} RON</span>
							</div>
							<div class="totals-row">
								<span>Transport:</span>
								<span>${transport.toFixed(2)} RON</span>
							</div>
							<div class="totals-row">
								<span>Total fără TVA:</span>
								<span>${totalFaraTVA.toFixed(2)} RON</span>
							</div>
							<div class="totals-row">
								<span>TVA (21%):</span>
								<span>${TVA.toFixed(2)} RON</span>
							</div>
							<div class="totals-row final">
								<span>TOTAL DE PLATĂ:</span>
								<span>${totalCuTVA.toFixed(2)} RON</span>
							</div>
						</div>

						<div class="order-info" style="background-color: #e3f2fd; border-left: 4px solid #2196f3;">
							<p style="margin: 0;"><strong>ℹ️ Ce urmează?</strong></p>
							<p style="margin: 10px 0 0 0;">Vei primi un email de confirmare după procesarea plății. Comanda ta va fi pregătită pentru livrare în cel mai scurt timp posibil!</p>
						</div>
					</div>

					<div class="footer">
						<p>Mulțumim pentru comandă!</p>
						<p><strong>emagyl.ro</strong> | contact@emagyl.ro</p>
						<p style="font-size: 12px; color: #999;">Acest email a fost trimis automat. Te rugăm să nu răspunzi la acest mesaj.</p>
					</div>
				</div>
			</body>
			</html>
		`;

		// Trimite emailul
		await transporter.sendMail({
			from: `"emagyl.ro" <noreply@emagyl.ro>`,
			to: orderData.billingType === 0 ? orderData.pf_email : orderData.pj_email,
			subject: `✅ Comandă confirmată - emagyl.ro`,
			html: emailHTML,
		});

		console.log(
			"Email trimis cu succes către:",
			orderData.billingType === 0 ? orderData.pf_email : orderData.pj_email
		);
		return true;
	} catch (error) {
		console.error("Eroare la trimiterea emailului:", error);
		return false;
	}
}

export default async function handler(req, res) {
	if (req.method !== "POST") {
		return res.status(405).json({ error: "Method not allowed" });
	}

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

	try {
		const formData = req.body;
		const userID = formData.userID || 0;

		const lineItems = [
			...formData.cartProducts.map((product) => {
				const price =
					product.priceReduced != null ? parseFloat(product.priceReduced) : parseFloat(product.price);

				return {
					price_data: {
						currency: "ron",
						product_data: {
							name: product.name,
							description: product.desc?.replace(/<\/?[^>]+(>|$)/g, "").slice(0, 200) || "",
							images: product.images ? product.images.split("|") : [],
						},
						unit_amount: Math.round(price * 1.21 * 100),
					},
					quantity: product.quantity,
				};
			}),

			{
				price_data: {
					currency: "ron",
					product_data: {
						name: "Transport",
					},
					unit_amount: Math.round(25 * 1.21 * 100),
				},
				quantity: 1,
			},
		];

		const baseUrl = "http://localhost:3000"; // modify

		const sessionParams = {
			payment_method_types: ["card"],
			line_items: lineItems,
			mode: "payment",
			success_url: `${baseUrl}/placed-order?sessionId={CHECKOUT_SESSION_ID}&userID=${userID}`,
			cancel_url: `${baseUrl}/problem-order`,
			metadata: {
				cartProducts: formData.cartProducts.map((product) => product.id).join(","),
				cartTotal: formData.cartTotal.toString(),
				couponCode: "",
			},
			invoice_creation: {
				enabled: true,
				invoice_data: {
					description: "Prețurile afișate includ TVA (21%)",
				},
			},
		};

		const session = await stripe.checkout.sessions.create(sessionParams);

		const dbItems = formData.cartProducts.map((product) => ({
			id: product.id,
			name: product.name,
			price: product.priceReduced != null ? parseFloat(product.priceReduced) : parseFloat(product.price),
			quantity: product.quantity,
			url: product.url,
			supplier: product.supplier,
			sku: product.sku,
			ean: product.ean,
		}));

		let orderData;
		let createdOrder; 

		if (formData.billingType == 0) {
			orderData = {
				pf_prenume: formData["first-name"],
				pf_nume_familie: formData["last-name"],
				pf_tara: formData["country"],
				pf_judet_oras: formData["city"],
				pf_adresa: formData["address"],
				pf_numar_telefon: formData["phone"],
				pf_email: formData["email"],
				pf_mentiuni: formData["note"],
				userID: userID,
				sessionID: session.id,
				status: "pending",
				items: dbItems,
				billingType: 0,
			};
			createdOrder = await db.Orders.create(orderData); 
			orderData.id = createdOrder.id; 
		} else {
			orderData = {
				pj_nume_firma: formData["nume-firma"],
				pj_cui: formData["cui"],
				pj_nr_reg: formData["nr-inregistrare"],
				pj_banca: formData["banca"],
				pj_iban: formData["iban"],
				pj_judet: formData["judet"],
				pj_localitate: formData["localitate"],
				pj_adresa: formData["adresa_firma"],
				pj_adresa_livrare: formData["adresa_livrare"],
				pj_email: formData["email"],
				pj_numar_telefon: formData["phone"],
				pj_mentiuni: formData["note"],
				userID: userID,
				sessionID: session.id,
				status: "pending",
				billingType: 1,
				items: dbItems,
			};
			createdOrder = await db.Orders.create(orderData); 
			orderData.id = createdOrder.id; 
		}

		await sendOrderConfirmationEmail(orderData, formData.cartProducts);

		res.json({ sessionId: session.id, url: session.url });
	} catch (error) {
		console.error("Checkout error:", error);
		return res.status(500).json({ error: "Eroare server la checkout." });
	}
}
