import { receipt, receipt_items, Receipts } from "@shared/schema";
import { format } from "date-fns";

// Utility function for formatting currency
function formatCurrency(value: number): string {
	return value.toFixed(2);
}

interface ReceiptWithUser extends Receipts{
	username: string;
}

interface ReceiptDetails {
	receipt: ReceiptWithUser;
}

/**
	* Generates a receipt as HTML with proper formatting for printing
	*/
export function generateReceipt({ receipt }: ReceiptDetails): string {

	const formattedDate = format(
		new Date(receipt.created_at),
		"yyyy-MM-dd HH:mm"
	);

	const ITEM_WIDTH = 15;

	const itemsHtml = receipt.items
			.map((item) => {
					const name = item.name;
					const qty = item.quantity.toString().padStart(3, " ");

					// Split name into chunks of ITEM_WIDTH
					const lines: string[] = [];
					for (let i = 0; i < name.length; i += ITEM_WIDTH) {
							lines.push(name.substring(i, i + ITEM_WIDTH));
					}

					// First line includes the quantity
					return lines.map((line, index) => {
							if (index === 0) {
									return line.padEnd(ITEM_WIDTH, " ") + " " + qty;
							} else {
									return line; // wrapped lines just show the name
							}
					}).join("\n");
			})
			.join("\n");



	return `
<div class="receipt">
  <div style="text-align:center;margin-bottom:8px;">
    <p style="font-weight:bold;">STOCK</p>
    <p>Atalou MicroSystem Stock</p>
    <p>==============================</p>
  </div>

  <div>
    <p>Date: ${formattedDate}</p>
    <p>Receipt No: ${receipt.receipt_code}</p>
    <p>Created by: ${receipt.username}</p>
    <p>==============================</p>

    <p>Handled By: ${receipt.responsible_name}</p>
    <p>Recipient: ${receipt.for_name}</p>

    ${receipt.description ? `<p>Note: ${receipt.description}</p>` : ""}
    <p>----------------------------------------</p>

<pre>
ITEM         QTY
<p>----------------------------------------</p>
${itemsHtml}
<p>----------------------------------------</p>
</pre>
  </div>

  <div style="text-align:center;">
    <p>==============================</p>
    <p style="font-weight:bold;">ATALOUMS STOCK</p>
  </div>
</div>
`;
}


/**
	* Helper function to print the receipt to the thermal printer
	* This opens a window with the formatted receipt for printing
	*/
export function printReceipt(
	receiptContent: string,
	receipt?: Receipts,
): void {
	// Open a new window for printing
	const printWindow = window.open("", "_blank");
	if (printWindow) {

	let logoUrl = '/logo.jpg';

		// Generate QR code placeholder ID

		// Write the HTML content to the new window
		printWindow.document.write(`
      <html>
        <head>
          <title>Print Receipt</title>
          <style>
            @page {
              size: 80mm 297mm; /* Standard 80mm thermal receipt width */
              margin: 0mm;
            }
            body {
              font-family: 'Roboto Mono', monospace;
              font-size: 12px;
              line-height: 1.2;
              padding: 0;
              margin: 0;
              width: 76mm; /* 80mm minus margins */
              background-color: white;
            }
            .receipt-container {
              display: flex;
              flex-direction: column;
              align-items: center;
              width: 100%;
              padding: 3mm;
              box-sizing: border-box;
            }
            .logo-container {
              text-align: center;
              margin-bottom: 5px;
              width: 100%;
            }
            .logo {
              max-width: 60mm;
              max-height: 60mm;
              margin: 0 auto;
            }
            p {
              margin: 2px 0;
            }
            .print-button {
              position: fixed;
              top: 5mm;
              right: 5mm;
              padding: 2mm 4mm;
              background: #007bff;
              color: white;
              border: none;
              border-radius: 1mm;
              cursor: pointer;
              font-size: 12px;
            }
            .qr-code-container {
              margin-top: 5mm;
              text-align: center;
              width: 100%;
            }
            .qr-code {
              width: 30mm;
              height: 30mm;
              margin: 0 auto;
            }
            @media print {
              .print-button {
                display: none;
              }
              body {
                padding: 0;
                margin: 0;
                width: 76mm;
              }
              @page {
                size: 80mm auto; /* Width fixed at 80mm, height auto */
                margin: 0;
              }
            }
          </style>
        </head>
        <body>
          <div class="receipt-container">

              <div class="logo-container">
                <img src="${logoUrl}" alt="Company Logo" class="logo" />
              </div>

            ${receiptContent}

          </div>
          <button class="print-button" onclick="window.print(); window.close();">Print Receipt</button>
        </body>
      </html>
    `);

		// Focus on the new window
		printWindow.focus();
	}
}