import PDFDocument from 'pdfkit';
import { SubscriptionStatus } from '@prisma/client';
import { getInvoice, TYPE_LABEL, type Party } from './subscriptions.service';

/**
 * The platform's tax invoice to a hostel, rendered server-side with pdfkit in
 * the same house style as the hostel-to-student invoices (navy header band,
 * gold rule, BILL TO beside INVOICE DETAILS, an itemised table, a total
 * block, notes, a footer).
 *
 * The seller is the super admin's billing profile and the buyer the hostel's
 * billing identity, both as frozen on the invoice when it was raised. Amounts
 * are whole rupees; tax is added on top at the invoice's rate.
 */

const money = (rupees: number) => `Rs. ${rupees.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
const dayLabel = (d: Date | string | null | undefined) =>
  d ? new Date(d).toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric', timeZone: 'UTC' }) : '-';

const STATUS_CHIP: Record<SubscriptionStatus, { text: string; fill: string; w: number }> = {
  DRAFT: { text: 'DRAFT', fill: '#64748b', w: 52 },
  PENDING: { text: 'UNPAID', fill: '#dc2626', w: 58 },
  PARTIAL: { text: 'PARTIALLY PAID', fill: '#d97706', w: 96 },
  PAID: { text: 'PAID', fill: '#16a34a', w: 46 },
  VOID: { text: 'CANCELLED', fill: '#64748b', w: 74 },
};

const NAVY = '#1a3a5c';
const NAVY2 = '#0f2540';
const LGRAY = '#f8fafc';
const DGRAY = '#1e293b';
const MGRAY = '#64748b';
const SGRAY = '#94a3b8';
const BORDER = '#e2e8f0';
const WHITE = '#ffffff';
const GOLD = '#f59e0b';

const cityLine = (p: Party) => [p.city, p.state, p.zip].filter(Boolean).join(', ');

export async function buildSubscriptionInvoicePdf(id: string): Promise<{ buffer: Buffer; filename: string; invoice: Awaited<ReturnType<typeof getInvoice>> }> {
  const inv = await getInvoice(id);
  const seller = inv.seller;
  const buyer = inv.buyer;
  const number = inv.invoiceNumber ?? `INV-${inv.id.slice(0, 8).toUpperCase()}`;

  const doc = new PDFDocument({ size: 'A4', margin: 0, compress: true, info: { Title: `${seller.name} ${number}`, Author: seller.name } });
  const chunks: Buffer[] = [];
  doc.on('data', (c: Buffer) => chunks.push(c));
  const done = new Promise<Buffer>((resolve, reject) => {
    doc.on('end', () => resolve(Buffer.concat(chunks)));
    doc.on('error', reject);
  });

  const PW = doc.page.width;
  const PH = doc.page.height;
  const M = 44;
  const CW = PW - M * 2;

  // ── Header band: the seller ────────────────────────────────────────────
  const textW = CW * 0.6;
  const sellerLines = [seller.address, cityLine(seller), seller.country].filter((x): x is string => !!x && x.trim().length > 0).join('\n');
  const contact = [seller.phone && `Tel: ${seller.phone}`, seller.email].filter(Boolean).join('   |   ');
  const taxIds = [seller.gstin && `GSTIN: ${seller.gstin}`, seller.pan && `PAN: ${seller.pan}`].filter(Boolean).join('   |   ');
  doc.font('Helvetica').fontSize(8.5);
  const addrH = sellerLines ? doc.heightOfString(sellerLines, { width: textW }) : 0;
  const HDR_H = Math.max(120, 47 + addrH + (sellerLines ? 3 : 0) + (contact ? 13 : 0) + (taxIds ? 13 : 0) + 12);

  doc.rect(0, 0, PW, HDR_H).fill(NAVY);
  doc.rect(0, HDR_H - 4, PW, 4).fill(GOLD);
  doc.fillColor(WHITE).font('Helvetica-Bold').fontSize(19).text(seller.name, M, 20, { width: textW, lineBreak: false, ellipsis: true });
  let hy = 47;
  doc.font('Helvetica').fontSize(8.5).fillColor(SGRAY);
  if (sellerLines) {
    doc.text(sellerLines, M, hy, { width: textW });
    hy += addrH + 3;
  }
  if (contact) {
    doc.text(contact, M, hy, { width: textW });
    hy += 13;
  }
  if (taxIds) doc.font('Helvetica-Bold').fillColor('#93c5fd').text(taxIds, M, hy, { width: textW });

  doc.fillColor(WHITE).font('Helvetica-Bold').fontSize(17).text('TAX INVOICE', M, 18, { width: CW, align: 'right' });
  doc.fillColor(SGRAY).font('Helvetica').fontSize(8.5);
  doc.text(`Invoice No:  ${number}`, M, 47, { width: CW, align: 'right' });
  doc.text(`Date:  ${dayLabel(inv.issueDate ?? inv.createdAt)}`, M, 61, { width: CW, align: 'right' });
  doc.text(`Due:  ${dayLabel(inv.dueDate)}`, M, 75, { width: CW, align: 'right' });

  // ── Bill to | Invoice details ──────────────────────────────────────────
  let y = HDR_H + 22;
  const COL2 = M + CW * 0.55;
  const billW = CW * 0.5;
  doc.fillColor(NAVY).font('Helvetica-Bold').fontSize(7.5).text('BILL TO', M, y);
  doc.text('INVOICE DETAILS', COL2, y);
  y += 11;

  const buyerName = buyer.legalName || buyer.name;
  const nameH = doc.font('Helvetica-Bold').fontSize(12.5).heightOfString(buyerName, { width: billW });
  doc.fillColor(DGRAY).text(buyerName, M, y, { width: billW });
  let ly = y + nameH + 5;
  const buyerRows: (string | null | undefined)[] = [
    buyer.legalName && buyer.legalName !== buyer.name ? `(${buyer.name})` : null,
    buyer.address,
    cityLine(buyer),
    buyer.email && `Email: ${buyer.email}`,
    buyer.phone && `Phone: ${buyer.phone}`,
    buyer.gstin && `GSTIN: ${buyer.gstin}`,
  ];
  doc.font('Helvetica').fontSize(9).fillColor(MGRAY);
  for (const row of buyerRows) {
    if (!row) continue;
    const h = doc.heightOfString(row, { width: billW - 8 });
    doc.fillColor(row.startsWith('GSTIN') ? DGRAY : MGRAY).text(row, M, ly, { width: billW - 8 });
    ly += h + 2;
  }

  const RLW = 80;
  const RVX = COL2 + RLW;
  const RVW = CW * 0.45 - RLW - 4;
  let ry = y + 2;
  const period = inv.periodStart || inv.periodEnd ? `${dayLabel(inv.periodStart)} - ${dayLabel(inv.periodEnd)}` : '-';
  const detailRows: [string, string][] = [
    ['Type', TYPE_LABEL[inv.invoiceType]],
    ['Plan', inv.planName],
    ['Period', period],
    ['Issue date', dayLabel(inv.issueDate ?? inv.createdAt)],
    ['Due date', dayLabel(inv.dueDate)],
  ];
  for (const [label, value] of detailRows) {
    doc.font('Helvetica').fontSize(9).fillColor(MGRAY).text(label, COL2, ry, { width: RLW });
    const h = doc.font('Helvetica-Bold').fontSize(9).heightOfString(value, { width: RVW });
    doc.fillColor(DGRAY).text(value, RVX, ry, { width: RVW });
    ry += Math.max(14, h + 2);
  }
  ry += 3;
  const chip = STATUS_CHIP[inv.status];
  doc.roundedRect(COL2, ry, chip.w, 17, 3).fill(chip.fill);
  doc.font('Helvetica-Bold').fontSize(8.5).fillColor(WHITE).text(chip.text, COL2, ry + 4.5, { width: chip.w, align: 'center' });
  ry += 17;

  y = Math.max(ly, ry) + 22;
  doc.moveTo(M, y).lineTo(PW - M, y).strokeColor(BORDER).lineWidth(0.75).stroke();
  y += 18;

  // ── Line table ─────────────────────────────────────────────────────────
  const TH = 27;
  const TR = 36;
  const C0 = 30;
  const C2 = 60;
  const C3 = 120;
  const C1 = CW - C0 - C2 - C3;
  const colX = [C0, C0 + C1, C0 + C1 + C2];
  doc.rect(M, y, CW, TH).fill(NAVY);
  for (const cx of colX) doc.moveTo(M + cx, y).lineTo(M + cx, y + TH).strokeColor('#2e4e70').lineWidth(0.5).stroke();
  const hY = y + 9.5;
  doc.fillColor(WHITE).font('Helvetica-Bold').fontSize(8.5);
  doc.text('#', M, hY, { width: C0, align: 'center' });
  doc.text('DESCRIPTION', M + C0 + 8, hY, { width: C1 - 16 });
  doc.text('QTY', M + C0 + C1, hY, { width: C2, align: 'center' });
  doc.text('AMOUNT', M + C0 + C1 + C2 + 4, hY, { width: C3 - 12, align: 'right' });
  y += TH;
  doc.rect(M, y, CW, TR).fill(LGRAY);
  for (const cx of colX) doc.moveTo(M + cx, y).lineTo(M + cx, y + TR).strokeColor(BORDER).lineWidth(0.5).stroke();
  const qty = inv.months;
  const unit = qty > 1 ? ` (${qty} months × ${money(Math.round(inv.subtotal / qty))})` : '';
  doc.fillColor(DGRAY).font('Helvetica').fontSize(9).text('1', M, y + 12, { width: C0, align: 'center' });
  doc.font('Helvetica-Bold').fontSize(9.5).text(inv.description, M + C0 + 8, y + 7, { width: C1 - 16, lineBreak: false, ellipsis: true });
  doc.font('Helvetica').fontSize(8).fillColor(MGRAY).text(`${inv.tenant.name}${unit}`, M + C0 + 8, y + 20, { width: C1 - 16, lineBreak: false, ellipsis: true });
  doc.font('Helvetica').fontSize(9).fillColor(DGRAY).text(String(qty), M + C0 + C1, y + 12, { width: C2, align: 'center' });
  doc.font('Helvetica-Bold').fontSize(9.5).text(money(inv.subtotal), M + C0 + C1 + C2 + 4, y + 12, { width: C3 - 12, align: 'right' });
  y += TR;
  doc.rect(M, y - TH - TR, CW, TH + TR).strokeColor(BORDER).lineWidth(0.75).stroke();
  y += 18;

  // ── Totals ─────────────────────────────────────────────────────────────
  const SW = 240;
  const SX = PW - M - SW;
  const SLW = 130;
  const rows: [string, string][] = [
    ['Subtotal', money(inv.subtotal)],
    ...(inv.taxRate > 0 ? ([[`Tax (${inv.taxRate}%)`, money(inv.taxAmount)]] as [string, string][]) : []),
    ['Total', money(inv.amount)],
    ...(inv.paid > 0 ? ([['Amount received', `- ${money(inv.paid)}`]] as [string, string][]) : []),
  ];
  for (const [label, value] of rows) {
    doc.font(label === 'Total' ? 'Helvetica-Bold' : 'Helvetica').fontSize(9).fillColor(label === 'Total' ? DGRAY : MGRAY).text(label, SX, y, { width: SLW });
    doc.fillColor(DGRAY).text(value, SX + SLW, y, { width: SW - SLW, align: 'right' });
    y += 15;
  }
  doc.moveTo(SX, y + 2).lineTo(SX + SW, y + 2).strokeColor(BORDER).lineWidth(0.75).stroke();
  y += 10;
  const settled = inv.status === SubscriptionStatus.PAID;
  doc.rect(SX, y, SW, 32).fill(NAVY2);
  doc.font('Helvetica-Bold').fontSize(9.5).fillColor(WHITE).text(settled ? 'TOTAL PAID' : 'TOTAL DUE', SX + 10, y + 11, { width: SLW });
  doc.font('Helvetica-Bold').fontSize(13).fillColor(GOLD).text(money(settled ? inv.amount : inv.balance), SX + 10, y + 9, { width: SW - 20, align: 'right' });
  y += 50;

  // ── Notes ──────────────────────────────────────────────────────────────
  if (inv.note?.trim()) {
    const noteH = doc.font('Helvetica').fontSize(9).heightOfString(inv.note, { width: CW - 20 });
    doc.rect(M, y, CW, noteH + 30).fill(LGRAY);
    doc.fillColor(NAVY).font('Helvetica-Bold').fontSize(7.5).text('NOTES', M + 10, y + 9);
    doc.fillColor(DGRAY).font('Helvetica').fontSize(9).text(inv.note, M + 10, y + 21, { width: CW - 20 });
    y += noteH + 42;
  }
  if (!settled && inv.status !== SubscriptionStatus.VOID) {
    doc.font('Helvetica').fontSize(8.5).fillColor(MGRAY).text(
      `Please pay ${money(inv.balance)}${inv.dueDate ? ` by ${dayLabel(inv.dueDate)}` : ''} and quote ${number} as the reference.`,
      M,
      y,
      { width: CW },
    );
  }

  // ── Footer ─────────────────────────────────────────────────────────────
  const FY = PH - 70;
  doc.moveTo(M, FY).lineTo(PW - M, FY).strokeColor(BORDER).lineWidth(0.75).stroke();
  doc.font('Helvetica-Bold').fontSize(9).fillColor(NAVY).text(`Thank you for choosing ${seller.name}!`, M, FY + 10, { width: CW, align: 'center' });
  doc.font('Helvetica').fontSize(8).fillColor(MGRAY).text([seller.phone, seller.email, seller.website].filter(Boolean).join('   |   '), M, FY + 24, { width: CW, align: 'center' });
  doc.fontSize(7.5).fillColor(SGRAY).text('This is a computer-generated document and is valid without a physical signature.', M, FY + 38, { width: CW, align: 'center' });

  doc.end();
  return { buffer: await done, filename: `${number}.pdf`, invoice: inv };
}
