import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';
import { OrderRecord } from './orderService';

export function generateOrderPDFBlob(order: OrderRecord): Blob {
  const doc = new jsPDF();

  // Header & Brand
  doc.setFillColor(28, 24, 20); // Dark background header
  doc.rect(0, 0, 210, 38, 'F');

  doc.setTextColor(255, 255, 255);
  doc.setFont('helvetica', 'bold');
  doc.setFontSize(20);
  doc.text('TIME N LIFE', 14, 18);

  doc.setFont('helvetica', 'normal');
  doc.setFontSize(9);
  doc.setTextColor(220, 200, 180);
  doc.text('Official Order Invoice & Booking Confirmation', 14, 25);
  doc.text('Website: https://timenlife.com | Email: orders@timenlife.com | Phone: +923313333400', 14, 31);

  // Right-aligned Order ID & Date
  doc.setTextColor(255, 255, 255);
  doc.setFont('helvetica', 'bold');
  doc.setFontSize(12);
  doc.text(`ORDER #${order.id}`, 196, 18, { align: 'right' });
  doc.setFont('helvetica', 'normal');
  doc.setFontSize(9);
  doc.text(`Date: ${new Date(order.createdAt).toLocaleString('en-PK')}`, 196, 25, { align: 'right' });
  doc.text(`Status: ${order.status.toUpperCase()}`, 196, 31, { align: 'right' });

  // Customer Information Block
  doc.setTextColor(40, 40, 40);
  doc.setFontSize(11);
  doc.setFont('helvetica', 'bold');
  doc.text('CUSTOMER & DELIVERY DETAILS', 14, 48);

  doc.setLineWidth(0.5);
  doc.setDrawColor(200, 180, 160);
  doc.line(14, 51, 196, 51);

  doc.setFontSize(9);
  doc.setFont('helvetica', 'normal');
  
  const isBankTransfer = order.paymentMethod === 'Bank Transfer';
  const paymentMethodText = isBankTransfer ? 'Direct Bank Transfer' : 'Cash on Delivery (COD)';

  const customerInfo = [
    `Name: ${order.customer.name}${order.customer.companyName ? ` (${order.customer.companyName})` : ''}`,
    `Email: ${order.customer.email}`,
    `Mobile: ${order.customer.phone}${order.customer.whatsapp ? ` | WhatsApp: ${order.customer.whatsapp}` : ''}`,
    `Address: ${order.customer.address}`,
    `City / Province: ${order.customer.city}, ${order.customer.province || 'Pakistan'} ${order.customer.postalCode ? `(${order.customer.postalCode})` : ''}`,
    `Country: ${order.customer.country || 'Pakistan'}`,
    `Payment Method: ${paymentMethodText}`,
  ];

  if (order.customer.notes) {
    customerInfo.push(`Notes: ${order.customer.notes}`);
  }

  let y = 57;
  customerInfo.forEach((line) => {
    doc.text(line, 14, y);
    y += 5.5;
  });

  // Courier Information if Dispatched
  if (order.courierInfo && order.courierInfo.courierName) {
    y += 2;
    doc.setFont('helvetica', 'bold');
    doc.text(`Courier: ${order.courierInfo.courierName} | Tracking #: ${order.courierInfo.trackingNumber}`, 14, y);
    y += 5.5;
  }

  y += 4;

  // Products Table
  doc.setFont('helvetica', 'bold');
  doc.setFontSize(11);
  doc.text('ORDERED PRODUCTS', 14, y);

  const tableBody = order.items.map((item, index) => [
    index + 1,
    item.productName,
    item.strength || '-',
    item.packing || '-',
    item.quantity,
    `Rs ${item.unitPrice.toLocaleString('en-PK')}`,
    `Rs ${item.totalPrice.toLocaleString('en-PK')}`,
  ]);

  autoTable(doc, {
    startY: y + 3,
    head: [['#', 'Product Name', 'Strength', 'Packing', 'Qty', 'Unit Price', 'Total']],
    body: tableBody,
    theme: 'grid',
    headStyles: {
      fillColor: [200, 30, 61], // #C81E3D brand red
      textColor: [255, 255, 255],
      fontStyle: 'bold',
      fontSize: 9,
    },
    styles: {
      fontSize: 8.5,
      cellPadding: 3,
    },
    columnStyles: {
      0: { cellWidth: 10, halign: 'center' },
      1: { cellWidth: 65 },
      2: { cellWidth: 25 },
      3: { cellWidth: 25 },
      4: { cellWidth: 15, halign: 'center' },
      5: { cellWidth: 25, halign: 'right' },
      6: { cellWidth: 25, halign: 'right' },
    },
  });

  // Summary Totals
  const finalY = (doc as any).lastAutoTable.finalY + 8;

  doc.setFontSize(9);
  doc.setFont('helvetica', 'normal');
  doc.text(`Total Items: ${order.totals.totalItems}`, 14, finalY);

  const rightAlignX = 196;
  let summaryY = finalY;

  doc.text(`Subtotal: Rs ${order.totals.subtotal.toLocaleString('en-PK')}`, rightAlignX, summaryY, { align: 'right' });
  summaryY += 5;
  const shippingLabel = order.totals.shippingCharges === 0
    ? 'Delivery Charges: FREE (Rs 0)'
    : `Delivery Charges: Rs ${order.totals.shippingCharges.toLocaleString('en-PK')}`;
  doc.text(shippingLabel, rightAlignX, summaryY, { align: 'right' });
  summaryY += 5;
  if (order.totals.discount > 0) {
    const couponText = order.totals.couponCode
      ? `Coupon Discount (${order.totals.couponCode}): -Rs ${order.totals.discount.toLocaleString('en-PK')}`
      : `Discount: -Rs ${order.totals.discount.toLocaleString('en-PK')}`;
    doc.text(couponText, rightAlignX, summaryY, { align: 'right' });
    summaryY += 5;
  }

  doc.setFont('helvetica', 'bold');
  doc.setFontSize(11);
  doc.setTextColor(200, 30, 61);
  doc.text(`GRAND TOTAL: Rs ${order.totals.grandTotal.toLocaleString('en-PK')}`, rightAlignX, summaryY + 2, { align: 'right' });

  // Bank Transfer Information Block if applicable
  if (isBankTransfer) {
    const bankBoxY = summaryY + 10;

    const bankLines = order.bankDetailsUsed
      ? order.bankDetailsUsed.split('\n')
      : [
          'Bank Name: Meezan Bank Limited | Account Title: Time N Life',
          'Account Number: 01010103928102 | IBAN: PK89MEZN0001010103928102',
          'Instructions: Please transfer total order amount to the bank account above and send screenshot on WhatsApp (+92 331 3333400) with your Order ID.',
        ];

    // Set font for line length calculations
    doc.setFont('helvetica', 'normal');
    doc.setFontSize(8);

    // Wrap each line to fit within 172mm (box width 182mm - 10mm padding)
    const maxTextWidth = 172;
    const splitLines: string[] = [];
    bankLines.forEach((bLine) => {
      const wrapped = doc.splitTextToSize(bLine, maxTextWidth);
      splitLines.push(...wrapped);
    });

    // Dynamic height calculation for the box
    const boxHeight = 10 + (splitLines.length * 4.5) + 4;

    doc.setFillColor(250, 245, 240);
    doc.setDrawColor(242, 229, 217);
    doc.roundedRect(14, bankBoxY, 182, boxHeight, 3, 3, 'FD');

    doc.setFont('helvetica', 'bold');
    doc.setFontSize(9);
    doc.setTextColor(200, 30, 61);
    doc.text('BANK TRANSFER INSTRUCTIONS & ACCOUNT DETAILS:', 18, bankBoxY + 6);

    doc.setFont('helvetica', 'normal');
    doc.setFontSize(8);
    doc.setTextColor(50, 50, 50);

    let bankLineY = bankBoxY + 12;
    splitLines.forEach((sLine) => {
      doc.text(sLine, 18, bankLineY);
      bankLineY += 4.5;
    });
  }

  // Footer Note
  doc.setFont('helvetica', 'normal');
  doc.setFontSize(8);
  doc.setTextColor(120, 120, 120);
  doc.text('Thank you for shopping with Time N Life! For support or inquiries, contact orders@timenlife.com or call +923313333400.', 105, 285, { align: 'center' });

  return doc.output('blob');
}

export function generateOrderPDFDataUri(order: OrderRecord): string {
  const blob = generateOrderPDFBlob(order);
  return URL.createObjectURL(blob);
}

export function downloadOrderPDF(order: OrderRecord): void {
  const blob = generateOrderPDFBlob(order);
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `Invoice_${order.id}.pdf`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

export function printOrder(order: OrderRecord): void {
  const blob = generateOrderPDFBlob(order);
  const url = URL.createObjectURL(blob);
  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';
  iframe.src = url;
  document.body.appendChild(iframe);
  iframe.onload = () => {
    iframe.contentWindow?.focus();
    iframe.contentWindow?.print();
  };
}
