import PDFDocument from 'pdfkit';

const formatCurrency = (amount) =>
  `Rs. ${Number(amount || 0).toLocaleString('en-IN', { maximumFractionDigits: 0 })}`;

const formatDate = (dateStr) => {
  if (!dateStr) return '';
  return new Date(dateStr).toLocaleString('en-IN', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
};

export const generateInvoicePDF = (sale, settings, res) => {
  const doc = new PDFDocument({ size: 'A4', margin: 40 });

  doc.pipe(res);

  doc.rect(40, 40, doc.page.width - 80, 90).fill('#F8FAFC');

  doc.fillColor('#1E3A8A').fontSize(20).font('Helvetica-Bold').text(
    settings?.storeName || 'My Store',
    55,
    55,
    { align: 'left' }
  );

  doc.fontSize(9).font('Helvetica').fillColor('#64748B');
  if (settings?.storeAddress) {
    doc.text(settings.storeAddress, 55, 82);
  }
  if (settings?.contactDetails) {
    doc.text(settings.contactDetails, 55, 94);
  }

  doc.fontSize(14).font('Helvetica-Bold').fillColor('#0F172A').text(
    'INVOICE',
    55,
    55,
    { align: 'right' }
  );
  doc.fontSize(10).font('Helvetica').fillColor('#334155').text(
    `Bill No: ${sale.billNumber}`,
    55,
    78,
    { align: 'right' }
  );
  doc.text(`Date: ${formatDate(sale.createdAt)}`, 55, 92, { align: 'right' });

  doc.y = 150;

  const startX = 40;
  const startY = doc.y;
  const tableWidth = doc.page.width - 80;
  const columns = [36, 250, 60, 80, 70, 96];
  const headers = ['#', 'Product', 'Qty', 'Price', 'Disc', 'Total'];

  let x = startX;
  doc.rect(startX, startY, tableWidth, 24).fill('#1E3A8A');
  doc.fillColor('#FFFFFF').fontSize(9).font('Helvetica-Bold');
  headers.forEach((header, i) => {
    doc.text(header, x + 6, startY + 8, {
      width: columns[i] - 12,
      align: i > 1 ? 'right' : 'left',
    });
    x += columns[i];
  });

  doc.y = startY + 24;
  const items = sale.items || [];

  items.forEach((item, idx) => {
    const rowY = startY + 24 + idx * 26;
    if (idx % 2 === 0) {
      doc.rect(startX, rowY, tableWidth, 26).fill('#F8FAFC');
    }
    const productLabel = `${item.productName || item.name || '-'}${item.variantLabel ? ` (${item.variantLabel})` : ''}${!item.variantLabel && item.size ? ` (${item.size})` : ''}`;
    const cells = [
      String(idx + 1),
      productLabel,
      String(item.quantity),
      formatCurrency(item.price),
      item.discount ? `- ${formatCurrency(item.discount)}` : '-',
      formatCurrency(item.total ?? item.price * item.quantity),
    ];
    doc.fillColor('#334155').fontSize(9).font('Helvetica');
    let cx = startX;
    cells.forEach((cell, i) => {
      doc.text(cell, cx + 6, rowY + 8, {
        width: columns[i] - 12,
        align: i > 1 ? 'right' : 'left',
      });
      cx += columns[i];
    });
    doc.y = rowY + 26;
  });

  doc.y = startY + 24 + items.length * 26 + 14;

  const summaryY = doc.y;
  doc.rect(startX, summaryY, tableWidth, 80).fill('#FFFFFF');
  doc.fontSize(10);
  doc.fillColor('#334155').font('Helvetica').text('Subtotal', startX + 6, summaryY + 8, { align: 'left' });
  doc.text(formatCurrency(sale.subtotal), startX + 6, summaryY + 8, { align: 'right' });

  doc.text('Discount', startX + 6, summaryY + 28, { align: 'left' });
  doc.fillColor('#DC2626').text(`-${formatCurrency(sale.discount || 0)}`, startX + 6, summaryY + 28, { align: 'right' });

  doc.fillColor('#1E3A8A').font('Helvetica-Bold').fontSize(12).text('Grand Total', startX + 6, summaryY + 52, { align: 'left' });
  doc.text(formatCurrency(sale.grandTotal ?? sale.total), startX + 6, summaryY + 52, { align: 'right' });

  let footerY = summaryY + 80;
  if (sale.paymentMethod) {
    doc.fillColor('#334155').font('Helvetica').fontSize(10);
    doc.text('Payment Method', startX + 6, footerY, { align: 'left' });
    doc.text(sale.paymentMethod, startX + 6, footerY, { align: 'right' });
    footerY += 18;
    if (sale.paymentMethod === 'CASH' && sale.amountReceived != null) {
      doc.text('Amount Received', startX + 6, footerY, { align: 'left' });
      doc.text(formatCurrency(sale.amountReceived), startX + 6, footerY, { align: 'right' });
      footerY += 16;
      doc.text('Change Due', startX + 6, footerY, { align: 'left' });
      doc.text(formatCurrency(sale.changeDue || 0), startX + 6, footerY, { align: 'right' });
      footerY += 16;
    }
  }
  if (sale.customerName) {
    doc.fillColor('#334155').font('Helvetica').fontSize(10);
    doc.text(`Customer: ${sale.customerName}${sale.customerPhone ? ` · ${sale.customerPhone}` : ''}`, startX + 6, footerY, { align: 'left' });
  }

  doc.fillColor('#94A3B8').font('Helvetica').fontSize(9).text(
    'Thank you for your purchase!',
    40,
    doc.page.height - 70,
    { align: 'center' }
  );

  doc.end();
};