import QRCode from 'qrcode';

export async function printReceipt(order: any, type: 'CUSTOMER' | 'KITCHEN', settings: any) {
  const isKitchen = type === 'KITCHEN';
  const formatPrice = (p: number) => p ? p.toLocaleString('fa-IR') : '۰';
  const dateStr = new Date(order.createdAt || Date.now()).toLocaleString('fa-IR', { timeZone: 'Asia/Tehran' });

  // In Electron the app is loaded via http://localhost:{port} so window.location is correct.
  // Fallback for edge cases where origin might be unexpected.
  const isElectron = typeof window !== 'undefined' && !!(window as any).require;
  const origin = (typeof window !== 'undefined' && window.location.origin && !window.location.origin.startsWith('file'))
    ? window.location.origin
    : 'http://localhost:3000';
  const fontSrc = `${origin}/fonts/IRANYekanXVF.ttf`;


  const firstStationLogo = order.items?.[0]?.menuItem?.station?.logoUrl;
  let safeLogoUrl = '';
  if (firstStationLogo) {
    safeLogoUrl = firstStationLogo;
  } else if (settings?.logoLightUrl) {
    safeLogoUrl = settings.logoLightUrl;
  } else if (settings?.logoUrl) {
    safeLogoUrl = settings.logoUrl;
  }
  if (safeLogoUrl && !safeLogoUrl.startsWith('http') && !safeLogoUrl.startsWith('data:')) {
    if (!safeLogoUrl.startsWith('/')) safeLogoUrl = '/' + safeLogoUrl;
    safeLogoUrl = origin + safeLogoUrl;
  }

  let base64LogoUrl = safeLogoUrl;
  if (safeLogoUrl && !safeLogoUrl.startsWith('data:')) {
    try {
      if (typeof window !== 'undefined') {
        base64LogoUrl = await new Promise((resolve) => {
          const img = new Image();
          img.crossOrigin = 'Anonymous';
          img.onload = () => {
            const canvas = document.createElement('canvas');
            canvas.width = img.naturalWidth;
            canvas.height = img.naturalHeight;
            canvas.getContext('2d')?.drawImage(img, 0, 0);
            resolve(canvas.toDataURL('image/png'));
          };
          img.onerror = () => {
            console.error('Failed to load image for print logo:', safeLogoUrl);
            resolve(''); // fallback to empty
          };
          img.src = safeLogoUrl;
        });
      }
    } catch (e) {
      console.error('Failed to encode logo to base64 for printing:', e);
      base64LogoUrl = '';
    }
  }

  const PAGE_MM = 56; // Configured down for 58mm printer
  const CONTENT_MM = 54;

  const suffix = order.orderNumber || '---';
  const typeFa = order.orderType === 'DINE_IN' ? 'سالن' : order.orderType === 'TAKEAWAY' ? 'بیرون‌بر' : 'پیک';
  const customer = order.customer ? `${order.customer.firstName} ${order.customer.lastName || ''}`.trim() : 'مهمان';
  const isDineIn = order.orderType === 'DINE_IN';

  let placeInfo = typeFa;
  if (isDineIn && order.table) placeInfo = `${typeFa}، میز ${order.table.name}`;

  const headCols = isKitchen
    ? `<th class="txt">آیتم</th><th class="num text-center" style="width: 40px; text-align: center;">تعداد</th>`
    : `<th class="txt">آیتم</th><th class="num">قیمت</th><th class="num">جمع</th>`;

  const rows = order.items.map((it: any) => {
    const qty = it.quantity;
    const unit = it.menuItem?.sellingPrice || it.unitPrice || 0;
    const line = qty * unit;
    const name = it.menuItem?.name || it.name;

    let res = isKitchen
      ? `<tr><td class="txt font-bold text-lg">${name}</td><td class="num font-black text-xl text-center" style="text-align: center;">${qty}</td></tr>`
      : `<tr><td class="txt">${qty} × ${name}</td><td class="num">${formatPrice(unit)}</td><td class="num">${formatPrice(line)}</td></tr>`;

    if (it.notes) {
      res += `<tr><td colspan="${isKitchen ? 2 : 3}" class="txt notes">- ${it.notes}</td></tr>`;
    }
    return res;
  }).join("");

  const subtotal = order.totalAmount || order.items.reduce((acc: any, x: any) => acc + (x.quantity * (x.menuItem?.sellingPrice || x.unitPrice)), 0);
  const discount = order.discountAmount || 0;
  const tax = order.taxAmount || 0;
  const deliveryFee = order.deliveryFee || 0;
  const finalP = order.finalAmount || (subtotal - discount + tax + deliveryFee);

  const totalsBlock = !isKitchen ? `
    <table><tbody>
      <tr><td class="txt" colspan="2">جمع جزء</td><td class="num">${formatPrice(subtotal)}</td></tr>
      ${discount > 0 ? `<tr><td class="txt" colspan="2">تخفیف</td><td class="num">-${formatPrice(discount)}</td></tr>` : ''}
      ${deliveryFee > 0 ? `<tr><td class="txt" colspan="2">هزینه ارسال</td><td class="num">${formatPrice(deliveryFee)}</td></tr>` : ''}
      ${tax > 0 ? `<tr><td class="txt" colspan="2">مالیات / سرویس</td><td class="num">${formatPrice(tax)}</td></tr>` : ''}
      <tr class="sum"><td class="txt text-center" colspan="2" style="font-size: 14px;">قابل پرداخت</td><td class="num" style="font-size: 14px;">${formatPrice(finalP)}</td></tr>
    </tbody></table>
  ` : '';

  const deliveryInfo = (!isDineIn && order.customer) ? `
    <div style="margin-bottom: 10px; border-bottom: 1px dashed #000; padding-bottom: 8px; text-align: right;">
       <div style="font-weight: bold; font-size: 12px; margin-bottom: 4px;">اطلاعات ارسال (${typeFa}):</div>
       <div style="margin-bottom: 3px; font-weight: bold;">گیرنده: ${customer}</div>
       ${order.customer.phone ? `<div style="margin-bottom: 3px; font-weight: bold;">تلفن: <span dir="ltr">${order.customer.phone}</span></div>` : ''}
       ${order.customer.address ? `<div style="margin-bottom: 3px; line-height: 1.4;">آدرس: ${order.customer.address}</div>` : ''}
    </div>
  ` : '';

  let qrCodeDataUrl = '';
  if (!isKitchen && settings?.onlineServerUrl) {
    try {
      let qrUrl = settings.onlineServerUrl.trim();
      if (!/^https?:\/\//i.test(qrUrl)) qrUrl = `https://${qrUrl}`;
      qrCodeDataUrl = await QRCode.toDataURL(qrUrl, { width: 100, margin: 0 });

    } catch (e) {
      console.error('QR Generate Error', e);
    }
  }

  const qrCodeBlock = (!isKitchen && qrCodeDataUrl) ? `
    <div style="margin-top: 12px; text-align: center;">
       <div style="font-weight: bold; font-size: 10px; margin-bottom: 4px;">کد تخفیف و سفارش آنلاین</div>
       <img src="${qrCodeDataUrl}" style="width: 80px; height: 80px; display: inline-block; padding: 2px; border: 1px solid #ddd; border-radius: 4px;" />
    </div>
  ` : '';

  const noteBlock = order.notes ? `
    <div class="box warn mt-2">
      <div class="box-title text-sm">یادداشت کل:</div>
      <div class="font-bold text-sm">${order.notes}</div>
    </div>
  ` : '';

  const brandBlock = safeLogoUrl && !isKitchen ? `<div class="brand"><img src="${safeLogoUrl}" alt="لوگو" onerror="this.style.display='none'"/></div>` : '';

  const footerContact = !isKitchen ? `
    <div class="footer text-center" style="margin-top: 10px;">
      ${settings?.phone ? `<div>تلفن: ${settings.phone}</div>` : ''}
      ${settings?.address ? `<div>${settings.address}</div>` : ''}
      <div style="margin-top:5px; font-weight:bold;">${settings?.siteName || 'فروشگاه توکان'}</div>
      <div style="margin-top:2px; font-size:9px; color:#555; direction:ltr;">Tukan ERP System</div>
    </div>
  ` : '';

  const titleBlock = isKitchen
    ? `<div class="orderno text-9xl">#${suffix}</div><div class="title">فیش آشپزخانه — ${typeFa}</div>`
    : `<div class="title">فیش سفارش #${suffix}</div>`;

  const html = `
    <html>
      <head>
        <meta charset="utf-8" />
        <style>
          @page { margin: 0; }
          * { box-sizing: border-box; }
          body { 
            font-family: 'IRANYekanXVF', 'IRANYekan', 'Vazirmatn', Tahoma, sans-serif; 
            font-size: 11px; 
            margin: 0; 
            padding: 0; 
            width: 100%; 
            direction: ltr; /* Force rendering to the left physical edge of the virtual A4 page */
          }
          .receipt-wrapper {
            width: 275px; /* Expanded by 5px */
            padding: 2px 4px; /* Added slight padding */
            direction: rtl; /* Real RTL content inside the safe width */
            margin-right: auto; /* Align to left properly */
          }
          table { width: 100%; table-layout: fixed; border-collapse: collapse; margin-top: 2px; }
          td, th { padding: 2px 1px; text-align: right; border-bottom: 1px dashed #000; word-wrap: break-word; font-size: 11px; }
          td:first-child, th:first-child { width: 40%; font-weight: bold; }
          ${!isKitchen ? `
          td:nth-child(2), th:nth-child(2) { width: 15%; text-align: center; white-space: nowrap; }
          td:nth-child(3), th:nth-child(3) { width: 20%; white-space: nowrap; }
          td:nth-child(4), th:nth-child(4) { width: 25%; white-space: nowrap; }
          ` : `
          td:nth-child(2), th:nth-child(2) { width: 60%; text-align: center; white-space: nowrap; }
          `}
          .text-center { text-align: center; }
          .font-bold { font-weight: bold; }
          .mb-1 { margin-bottom: 4px; }
          .logo { text-align: center; margin-bottom: 8px; }
          .logo img { max-width: 140px; max-height: 50px; }
          .header-block { border-bottom: 1px solid #000; padding-bottom: 6px; margin-bottom: 6px; }
        </style>
      </head>
      <body>
        <div class="receipt-wrapper">
          ${base64LogoUrl ? `<div class="logo"><img src="${base64LogoUrl}" /></div>` : ''}
          <div class="text-center header-block">
            <div class="font-bold mb-1" style="font-size: 13px;">
              ${isKitchen ? 'فیش سفارش آشپزخانه' : (settings?.siteName || 'فروشگاه توکان')}
            </div>
            <div class="mb-1">سفارش شماره: <span class="font-bold">${suffix}</span></div>
            <div class="mb-1">تاریخ: ${dateStr}</div>
            <div class="mb-1 font-bold">نوع: ${placeInfo}</div>
            ${customer !== 'مهمان' ? `<div class="mb-1">مشتری: ${customer}</div>` : ''}
          </div>

          ${deliveryInfo}

          <table>
            <thead>
              <tr>
                ${isKitchen
      ? '<th>آیتم</th><th class="text-center">تعداد</th>'
      : '<th>آیتم</th><th>تعداد</th><th>قیمت</th><th>جمع</th>'
    }
              </tr>
            </thead>
            <tbody>
              ${order.items.map((it: any) => `
                <tr>
                  <td>${it.menuItem?.name || it.name} ${it.notes ? `<br/><small>-${it.notes}</small>` : ''}</td>
                  <td class="text-center font-bold">${it.quantity}</td>
                  ${!isKitchen ? `
                    <td>${formatPrice(it.unitPrice || it.menuItem?.sellingPrice || 0)}</td>
                    <td>${formatPrice(it.quantity * (it.unitPrice || it.menuItem?.sellingPrice || 0))}</td>
                  ` : ''}
                </tr>
              `).join('')}
            </tbody>
          </table>

          ${!isKitchen ? `
            <div style="margin-top: 10px; text-align: center;">
              <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
                <span>جمع کل:</span><span class="font-bold">${formatPrice(subtotal)} تومان</span>
              </div>
              ${discount > 0 ? `
                <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
                  <span>تخفیف:</span><span>${formatPrice(discount)} تومان</span>
                </div>
              ` : ''}
              ${tax > 0 ? `
                <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
                  <span>مالیات و عوارض:</span><span>${formatPrice(tax)} تومان</span>
                </div>
              ` : ''}
               ${deliveryFee > 0 ? `
                <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
                  <span>هزینه ارسال:</span><span>${formatPrice(deliveryFee)} تومان</span>
                </div>
              ` : ''}
              <div style="display: flex; justify-content: space-between; margin-top: 8px; border-top: 2px solid #000; padding-top: 8px;">
                <span class="font-bold text-center w-full">مبلغ نهایی: ${formatPrice(finalP)} تومان</span>
              </div>
            </div>
            <div class="text-center" style="margin-top: 15px; font-size: 10px; border-top: 1px dashed #000; padding-top: 10px;">
              ${settings?.address ? `<div style="margin-bottom: 4px;">آدرس: ${settings.address}</div>` : ''}
              ${settings?.phone ? `<div style="margin-bottom: 4px;">تلفن: <span dir="ltr" style="display: inline-block;">${settings.phone}</span></div>` : ''}
              <div>${settings?.receiptFooter || 'سپاس از انتخاب شما!'}</div>
            </div>
            ${qrCodeBlock}
            <div style="text-align:center; margin-top:12px; font-size:10px; color:#000; font-weight:bold; border-top:1px dashed #000; padding-top:8px;">
              قدرت گرفته از سیستم مدیریت توکان
            </div>
          ` : `
          `}
        </div>
      </body>
    </html>
  `;

  // Detect Electron reliably via ipcRenderer
  const isElectronEnv = typeof window !== 'undefined' && !!(window as any).require;
  const electron = isElectronEnv ? (window as any).require('electron') : null;

  let parsedPrinters: any = {};
  if (settings?.printers) {
    try { parsedPrinters = JSON.parse(settings.printers); } catch (e) { }
  }
  const pCashier = settings?.cashierPrinter || parsedPrinters?.cashierPrinter;
  const pKitchen = settings?.kitchenPrinter || parsedPrinters?.kitchenPrinter;
  const printerName = isKitchen ? pKitchen : pCashier;

  if (isElectronEnv && electron?.ipcRenderer && printerName) {
    // Pass html and the font path; main.js will embed font as base64
    electron.ipcRenderer.invoke('print-silent', { html, deviceName: printerName }).catch(console.error);
    return;
  }

  // BROWSER FALLBACK
  const iframe = document.createElement('iframe');
  iframe.style.position = 'fixed';
  iframe.style.right = '0';
  iframe.style.bottom = '0';
  iframe.style.width = '0';
  iframe.style.height = '0';
  iframe.style.border = '0';
  document.body.appendChild(iframe);

  const w = iframe.contentWindow!;
  const doc = w.document;
  doc.open();
  doc.write(html);
  doc.close();

  let printed = false;
  const cleanup = () => setTimeout(() => iframe.remove(), 300);
  const tryPrint = () => {
    if (printed) return;
    printed = true;
    w.focus();
    w.print();
    if ("onafterprint" in w) (w as any).onafterprint = cleanup;
    else cleanup();
  };

  const waitFonts: Promise<any> = (doc as any).fonts?.ready ?? Promise.resolve();
  const waitImages = Promise.all(
    Array.from(doc.images).map((img) =>
      img.complete
        ? Promise.resolve()
        : new Promise<void>((res) => {
          img.onload = () => res();
          img.onerror = () => res();
        })
    )
  );

  Promise.all([waitFonts, waitImages]).then(() => setTimeout(tryPrint, 200));
  setTimeout(tryPrint, 2000); // 2 second absolute fallback fallback
}
