import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../../environments/environment';

@Injectable({ providedIn: 'root' })
export class PosReceiptService {
  private http = inject(HttpClient);
  private base = `${environment.apiUrl}/sales`;

  generateReceipt(invoice: any, payments: any[], session: any, settings?: any): string {
    const storeName = settings?.receipt_header || 'Moon ERP';
    const storeAddress = settings?.store_address || '';
    const storePhone = settings?.store_phone || '';
    const footer = settings?.receipt_footer || '\u0634\u0643\u0631\u0627\u064B \u0644\u0632\u064A\u0627\u0631\u062A\u0643\u0645';

    const invoiceNumber = invoice?.invoice_number || invoice?.number || '';
    const invoiceDate = invoice?.date || invoice?.created_at || '';
    const cashier = session?.user?.name || '';
    const customerName = invoice?.partner?.name || invoice?.customer_name || '';

    const items: any[] = invoice?.items || invoice?.lines || [];
    const subtotal = parseFloat(invoice?.subtotal || '0');
    const discountAmount = parseFloat(invoice?.discount_amount || '0');
    const taxAmount = parseFloat(invoice?.tax_amount || '0');
    const total = parseFloat(invoice?.total || '0');

    const totalPaid = payments.reduce((sum: number, p: any) => sum + parseFloat(p.amount || '0'), 0);
    const change = Math.max(0, totalPaid - total);

    const now = new Date();
    const printedAt = now.toLocaleString('ar-EG', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
    });

    const itemsHtml = items
      .map((item: any) => {
        const name = item.product?.name || item.product_name || item.name || '';
        const qty = parseFloat(item.quantity || item.qty || '0');
        const unitPrice = parseFloat(item.unit_price || item.price || '0');
        const lineTotal = parseFloat(item.line_total || item.total || '0') || qty * unitPrice;
        return `
          <tr>
            <td style="text-align:right;padding:2px 0;">${name}</td>
            <td style="text-align:center;padding:2px 4px;">${qty}</td>
            <td style="text-align:left;padding:2px 4px;">${unitPrice.toFixed(2)}</td>
            <td style="text-align:left;padding:2px 0;">${lineTotal.toFixed(2)}</td>
          </tr>`;
      })
      .join('');

    const paymentsHtml = payments
      .map((p: any) => {
        const method = p.method || p.payment_method || '';
        const amount = parseFloat(p.amount || '0');
        return `<div style="display:flex;justify-content:space-between;padding:1px 0;">
          <span>${method}</span><span>${amount.toFixed(2)}</span>
        </div>`;
      })
      .join('');

    return `<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
  <meta charset="UTF-8">
  <title>Receipt - ${invoiceNumber}</title>
</head>
<body style="margin:0;padding:0;font-family:'Courier New',monospace;font-size:12px;color:#000;background:#fff;max-width:80mm;width:80mm;">
  <div style="padding:8px;max-width:80mm;">
    <!-- Header -->
    <div style="text-align:center;margin-bottom:8px;">
      <div style="font-size:16px;font-weight:bold;">${storeName}</div>
      ${storeAddress ? `<div style="font-size:10px;margin-top:2px;">${storeAddress}</div>` : ''}
      ${storePhone ? `<div style="font-size:10px;">${storePhone}</div>` : ''}
    </div>

    <div style="border-top:1px dashed #000;margin:4px 0;"></div>

    <!-- Invoice Info -->
    <div style="font-size:11px;">
      <div style="display:flex;justify-content:space-between;">
        <span>\u0631\u0642\u0645 \u0627\u0644\u0641\u0627\u062A\u0648\u0631\u0629:</span>
        <span>${invoiceNumber}</span>
      </div>
      <div style="display:flex;justify-content:space-between;">
        <span>\u0627\u0644\u062A\u0627\u0631\u064A\u062E:</span>
        <span>${invoiceDate}</span>
      </div>
      <div style="display:flex;justify-content:space-between;">
        <span>\u0627\u0644\u0643\u0627\u0634\u064A\u0631:</span>
        <span>${cashier}</span>
      </div>
      ${
        customerName
          ? `<div style="display:flex;justify-content:space-between;">
              <span>\u0627\u0644\u0639\u0645\u064A\u0644:</span>
              <span>${customerName}</span>
            </div>`
          : ''
      }
    </div>

    <div style="border-top:1px dashed #000;margin:4px 0;"></div>

    <!-- Items -->
    <table style="width:100%;border-collapse:collapse;font-size:11px;">
      <thead>
        <tr style="border-bottom:1px solid #000;">
          <th style="text-align:right;padding:2px 0;">\u0627\u0644\u0635\u0646\u0641</th>
          <th style="text-align:center;padding:2px 4px;">\u0627\u0644\u0643\u0645\u064A\u0629</th>
          <th style="text-align:left;padding:2px 4px;">\u0627\u0644\u0633\u0639\u0631</th>
          <th style="text-align:left;padding:2px 0;">\u0627\u0644\u0625\u062C\u0645\u0627\u0644\u064A</th>
        </tr>
      </thead>
      <tbody>
        ${itemsHtml}
      </tbody>
    </table>

    <div style="border-top:1px dashed #000;margin:6px 0;"></div>

    <!-- Totals -->
    <div style="font-size:11px;">
      <div style="display:flex;justify-content:space-between;padding:1px 0;">
        <span>\u0627\u0644\u0645\u062C\u0645\u0648\u0639 \u0627\u0644\u0641\u0631\u0639\u064A:</span>
        <span>${subtotal.toFixed(2)}</span>
      </div>
      ${
        discountAmount > 0
          ? `<div style="display:flex;justify-content:space-between;padding:1px 0;">
              <span>\u0627\u0644\u062E\u0635\u0645:</span>
              <span>-${discountAmount.toFixed(2)}</span>
            </div>`
          : ''
      }
      ${
        taxAmount > 0
          ? `<div style="display:flex;justify-content:space-between;padding:1px 0;">
              <span>\u0627\u0644\u0636\u0631\u064A\u0628\u0629:</span>
              <span>${taxAmount.toFixed(2)}</span>
            </div>`
          : ''
      }
      <div style="display:flex;justify-content:space-between;padding:4px 0;font-size:16px;font-weight:bold;border-top:1px solid #000;border-bottom:1px solid #000;margin:4px 0;">
        <span>\u0627\u0644\u0625\u062C\u0645\u0627\u0644\u064A:</span>
        <span>${total.toFixed(2)}</span>
      </div>
    </div>

    <!-- Payment Info -->
    <div style="font-size:11px;margin-top:4px;">
      ${paymentsHtml}
      <div style="display:flex;justify-content:space-between;padding:1px 0;font-weight:bold;">
        <span>\u0627\u0644\u0645\u062F\u0641\u0648\u0639:</span>
        <span>${totalPaid.toFixed(2)}</span>
      </div>
      ${
        change > 0
          ? `<div style="display:flex;justify-content:space-between;padding:1px 0;font-weight:bold;">
              <span>\u0627\u0644\u0628\u0627\u0642\u064A:</span>
              <span>${change.toFixed(2)}</span>
            </div>`
          : ''
      }
    </div>

    <div style="border-top:1px dashed #000;margin:6px 0;"></div>

    <!-- Footer -->
    <div style="text-align:center;font-size:11px;">
      <div style="margin-bottom:4px;">${footer}</div>
      <div style="font-size:9px;color:#666;">${printedAt}</div>
    </div>
  </div>
</body>
</html>`;
  }

  generateCloseReport(session: any, summary: any): string {
    const sessionId = session?.id || '';
    const terminal = session?.terminal?.name || session?.terminal?.code || '';
    const cashier = session?.user?.name || '';
    const openedAt = session?.opened_at || '';
    const closedAt = session?.closed_at || new Date().toLocaleString('ar-EG');

    const payments: any[] = summary?.payments || [];
    const totalTransactions = summary?.total_transactions || summary?.transactions_count || 0;
    const openingBalance = parseFloat(session?.opening_balance || '0');
    const closingBalance = parseFloat(session?.closing_balance || summary?.closing_balance || '0');

    const paymentsRowsHtml = payments
      .map((p: any) => {
        const method = p.method || '';
        const expected = parseFloat(p.expected_amount || '0');
        const actual = parseFloat(p.actual_amount || '0');
        const diff = actual - expected;
        const diffColor = diff < 0 ? '#c00' : diff > 0 ? '#060' : '#000';
        return `
          <tr>
            <td style="padding:3px 4px;border-bottom:1px solid #ddd;text-align:right;">${method}</td>
            <td style="padding:3px 4px;border-bottom:1px solid #ddd;text-align:left;">${expected.toFixed(2)}</td>
            <td style="padding:3px 4px;border-bottom:1px solid #ddd;text-align:left;">${actual.toFixed(2)}</td>
            <td style="padding:3px 4px;border-bottom:1px solid #ddd;text-align:left;color:${diffColor};">${diff.toFixed(2)}</td>
          </tr>`;
      })
      .join('');

    return `<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
  <meta charset="UTF-8">
  <title>Session Close Report - ${sessionId}</title>
</head>
<body style="margin:0;padding:0;font-family:'Courier New',monospace;font-size:12px;color:#000;background:#fff;max-width:80mm;width:80mm;">
  <div style="padding:8px;max-width:80mm;">
    <!-- Header -->
    <div style="text-align:center;margin-bottom:8px;">
      <div style="font-size:14px;font-weight:bold;">\u062A\u0642\u0631\u064A\u0631 \u0625\u063A\u0644\u0627\u0642 \u0627\u0644\u0648\u0631\u062F\u064A\u0629</div>
    </div>

    <div style="border-top:1px dashed #000;margin:4px 0;"></div>

    <!-- Session Info -->
    <div style="font-size:11px;">
      <div style="display:flex;justify-content:space-between;padding:1px 0;">
        <span>\u0631\u0642\u0645 \u0627\u0644\u0648\u0631\u062F\u064A\u0629:</span>
        <span>${sessionId}</span>
      </div>
      <div style="display:flex;justify-content:space-between;padding:1px 0;">
        <span>\u0627\u0644\u0637\u0631\u0641\u064A\u0629:</span>
        <span>${terminal}</span>
      </div>
      <div style="display:flex;justify-content:space-between;padding:1px 0;">
        <span>\u0627\u0644\u0643\u0627\u0634\u064A\u0631:</span>
        <span>${cashier}</span>
      </div>
      <div style="display:flex;justify-content:space-between;padding:1px 0;">
        <span>\u0648\u0642\u062A \u0627\u0644\u0641\u062A\u062D:</span>
        <span>${openedAt}</span>
      </div>
      <div style="display:flex;justify-content:space-between;padding:1px 0;">
        <span>\u0648\u0642\u062A \u0627\u0644\u0625\u063A\u0644\u0627\u0642:</span>
        <span>${closedAt}</span>
      </div>
    </div>

    <div style="border-top:1px dashed #000;margin:6px 0;"></div>

    <!-- Payment Summary -->
    <div style="font-size:11px;font-weight:bold;text-align:center;margin-bottom:4px;">
      \u0645\u0644\u062E\u0635 \u0627\u0644\u0645\u062F\u0641\u0648\u0639\u0627\u062A
    </div>
    <table style="width:100%;border-collapse:collapse;font-size:10px;">
      <thead>
        <tr style="border-bottom:1px solid #000;">
          <th style="text-align:right;padding:3px 4px;">\u0627\u0644\u0637\u0631\u064A\u0642\u0629</th>
          <th style="text-align:left;padding:3px 4px;">\u0627\u0644\u0645\u062A\u0648\u0642\u0639</th>
          <th style="text-align:left;padding:3px 4px;">\u0627\u0644\u0641\u0639\u0644\u064A</th>
          <th style="text-align:left;padding:3px 4px;">\u0627\u0644\u0641\u0631\u0642</th>
        </tr>
      </thead>
      <tbody>
        ${paymentsRowsHtml}
      </tbody>
    </table>

    <div style="border-top:1px dashed #000;margin:6px 0;"></div>

    <!-- Totals -->
    <div style="font-size:11px;">
      <div style="display:flex;justify-content:space-between;padding:2px 0;">
        <span>\u0639\u062F\u062F \u0627\u0644\u0645\u0639\u0627\u0645\u0644\u0627\u062A:</span>
        <span style="font-weight:bold;">${totalTransactions}</span>
      </div>
      <div style="display:flex;justify-content:space-between;padding:2px 0;">
        <span>\u0631\u0635\u064A\u062F \u0627\u0644\u0627\u0641\u062A\u062A\u0627\u062D:</span>
        <span>${openingBalance.toFixed(2)}</span>
      </div>
      <div style="display:flex;justify-content:space-between;padding:2px 0;font-weight:bold;font-size:13px;">
        <span>\u0631\u0635\u064A\u062F \u0627\u0644\u0625\u063A\u0644\u0627\u0642:</span>
        <span>${closingBalance.toFixed(2)}</span>
      </div>
    </div>

    <div style="border-top:1px dashed #000;margin:6px 0;"></div>

    <div style="text-align:center;font-size:9px;color:#666;">
      ${new Date().toLocaleString('ar-EG')}
    </div>
  </div>
</body>
</html>`;
  }

  printReceipt(html: string): void {
    const printWindow = window.open('', '_blank', 'width=320,height=600');
    if (!printWindow) {
      // Popup blocked — fallback to iframe
      this.printViaIframe(html);
      return;
    }
    printWindow.document.open();
    printWindow.document.write(html);
    printWindow.document.close();
    printWindow.onload = () => {
      printWindow.focus();
      printWindow.print();
      printWindow.onafterprint = () => printWindow.close();
      // Fallback close after 10s if onafterprint not supported
      setTimeout(() => {
        try { printWindow.close(); } catch {}
      }, 10000);
    };
    // Fallback: if onload already fired (some browsers)
    setTimeout(() => {
      try {
        if (!printWindow.closed) {
          printWindow.focus();
          printWindow.print();
          printWindow.onafterprint = () => printWindow.close();
        }
      } catch {}
    }, 500);
  }

  private printViaIframe(html: string): void {
    const iframe = document.createElement('iframe');
    iframe.style.position = 'fixed';
    iframe.style.top = '-10000px';
    iframe.style.left = '-10000px';
    iframe.style.width = '80mm';
    iframe.style.height = '0';
    iframe.style.border = 'none';

    // Set onload BEFORE appending to DOM
    iframe.onload = () => {
      try {
        iframe.contentWindow?.focus();
        iframe.contentWindow?.print();
      } catch {}
      setTimeout(() => {
        try { document.body.removeChild(iframe); } catch {}
      }, 2000);
    };

    iframe.srcdoc = html;
    document.body.appendChild(iframe);
  }

  printFromInvoiceId(invoiceId: number): void {
    this.http.get(`${this.base}/invoices/${invoiceId}`).subscribe({
      next: (res: any) => {
        const invoice = res?.data || res;
        const payments = invoice?.payments || [];
        const session = invoice?.session || { user: { name: '' } };
        const settings = invoice?.terminal?.settings || {};
        const html = this.generateReceipt(invoice, payments, session, settings);
        this.printReceipt(html);
      },
    });
  }
}
