import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import PDFDocument from 'pdfkit';
import { PrismaService } from '../../prisma/prisma.service';
import { RequestTenantContext, TenantQueryHelper } from '../../common/tenancy/tenant-query.helper';
import { type CrmActor } from '../../common/crm/crm-record.helper';
import { CreateInvoiceDto, CreateInvoiceItemDto } from './dto/create-invoice.dto';
import { CreateFromQuoteDto } from './dto/create-from-quote.dto';
import { CreateFromTimesheetsDto } from './dto/create-from-timesheets.dto';
import { RecordPaymentDto } from './dto/record-payment.dto';
import { UpdateInvoiceDto } from './dto/update-invoice.dto';
import { GetInvoicesQuery } from './dto/get-invoices.query';

import { NumberingService } from '../numbering/numbering.service';
import { AuditService } from '../audit/audit.service';

@Injectable()
export class InvoicesService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly tenant: TenantQueryHelper,
    private readonly numbering: NumberingService,
    private readonly audit: AuditService,
  ) {}

  // Helper to compute line item amounts and totals
  private computeTotals(items: CreateInvoiceItemDto[]) {
    let subtotal = 0;
    let discountTotal = 0;
    let taxTotal = 0;

    const computedItems = items.map((it, idx) => {
      const qty = Math.max(0.01, it.quantity ?? 1);
      const rate = Math.max(0, it.unitPrice ?? 0);
      const discPct = Math.min(100, Math.max(0, it.discountPercent ?? 0));
      const gstRate = Math.min(100, Math.max(0, it.gstRate ?? 18.0));

      const lineGross = qty * rate;
      const lineDisc = lineGross * (discPct / 100);
      const lineTaxable = lineGross - lineDisc;
      const lineTax = lineTaxable * (gstRate / 100);
      const lineTotal = lineTaxable + lineTax;

      subtotal += lineGross;
      discountTotal += lineDisc;
      taxTotal += lineTax;

      return {
        productId: it.productId || null,
        name: it.name.trim(),
        description: it.description?.trim() || null,
        quantity: qty,
        unitPrice: rate,
        discountPercent: discPct,
        gstRate,
        lineTotal,
        orderIndex: idx,
      };
    });

    const totalAmount = subtotal - discountTotal + taxTotal;

    return {
      items: computedItems,
      subtotal,
      discountTotal,
      taxTotal,
      totalAmount,
    };
  }

  // Generates unique sequence invoice number via NumberingService
  private async generateInvoiceNumber(tenantId: string): Promise<string> {
    return this.numbering.getNextNumber(tenantId, 'INVOICE');
  }

  // Returns list of invoices with statistics KPIs
  async list(ctx: RequestTenantContext, q: GetInvoicesQuery) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const page = Math.max(1, q.page || 1);
    const limit = Math.min(100, Math.max(1, q.limit || 25));
    const skip = (page - 1) * limit;

    const where: Prisma.InvoiceWhereInput = {
      tenantId,
    };

    if (q.status) {
      where.status = q.status;
    }

    if (q.accountId) {
      where.accountId = q.accountId;
    }

    if (q.dealId) {
      where.dealId = q.dealId;
    }

    if (q.projectId) {
      where.projectId = q.projectId;
    }

    if (q.search?.trim()) {
      const term = q.search.trim();
      where.OR = [{ invoiceNumber: { contains: term } }, { account: { name: { contains: term } } }, { project: { name: { contains: term } } }];
    }

    const now = new Date();
    const ninetyDaysAgo = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000);

    const [total, data, allInvoices, payments90d] = await Promise.all([
      this.prisma.invoice.count({ where }),
      this.prisma.invoice.findMany({
        where,
        skip,
        take: limit,
        orderBy: [{ createdAt: 'desc' }],
        include: {
          account: { select: { id: true, name: true } },
          deal: { select: { id: true, title: true } },
          project: { select: { id: true, name: true, projectNumber: true } },
          contact: { select: { id: true, name: true, email: true } },
          owner: { select: { id: true, name: true } },
          _count: { select: { items: true, payments: true, timeEntries: true } },
        },
      }),
      this.prisma.invoice.findMany({
        where: { tenantId },
        select: {
          status: true,
          dueDate: true,
          issueDate: true,
          totalAmount: true,
          paidAmount: true,
          updatedAt: true,
        },
      }),
      this.prisma.payment.findMany({
        where: {
          tenantId,
          status: 'CAPTURED',
          paidAt: { gte: ninetyDaysAgo },
        },
        select: { amount: true },
      }),
    ]);

    let outstanding = 0;
    let overdue = 0;
    let paidInvoicesCount = 0;
    let totalDaysToPay = 0;

    allInvoices.forEach((inv) => {
      const balance = Math.max(0, Number(inv.totalAmount) - Number(inv.paidAmount));
      if (['SENT', 'OVERDUE', 'PARTIALLY_PAID'].includes(inv.status)) {
        outstanding += balance;
      }
      if (inv.status === 'OVERDUE' || (balance > 0 && inv.dueDate < now && inv.status !== 'VOID')) {
        overdue += balance;
      }
      if (inv.status === 'PAID') {
        paidInvoicesCount += 1;
        const days = Math.max(0, Math.round((inv.updatedAt.getTime() - inv.issueDate.getTime()) / (24 * 3600 * 1000)));
        totalDaysToPay += days;
      }
    });

    const collected90d = payments90d.reduce((sum, p) => sum + Number(p.amount), 0);
    const avgDaysToPay = paidInvoicesCount > 0 ? Number((totalDaysToPay / paidInvoicesCount).toFixed(1)) : 0;

    return {
      data,
      stats: {
        outstanding,
        overdue,
        collected90d,
        avgDaysToPay,
        totalInvoices: allInvoices.length,
      },
      meta: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit) || 1,
      },
    };
  }

  // Returns full invoice details with items and payment logs
  async get(ctx: RequestTenantContext, id: string) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const invoice = await this.prisma.invoice.findFirst({
      where: { id, tenantId },
      include: {
        account: { select: { id: true, name: true, phone: true, website: true, city: true } },
        quote: { select: { id: true, quoteNumber: true, version: true } },
        deal: { select: { id: true, title: true, dealNumber: true } },
        project: { select: { id: true, name: true, projectNumber: true } },
        contact: { select: { id: true, name: true, email: true, phone: true } },
        owner: { select: { id: true, name: true, email: true } },
        items: {
          orderBy: { orderIndex: 'asc' },
          include: {
            product: { select: { id: true, name: true, sku: true, unit: true, hsnSac: true } },
          },
        },
        payments: {
          orderBy: { paidAt: 'desc' },
        },
        timeEntries: {
          select: { id: true, hours: true, date: true, note: true },
        },
      },
    });

    if (!invoice) {
      throw new NotFoundException('Invoice not found');
    }

    return invoice;
  }

  // Returns aggregated financial KPIs for invoice dashboard
  async getStats(ctx: RequestTenantContext) {
    const listRes = await this.list(ctx, { page: 1, limit: 1 });
    return listRes.stats;
  }

  // Creates a standalone invoice
  async create(ctx: RequestTenantContext, dto: CreateInvoiceDto, actor?: CrmActor) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);

    const account = await this.prisma.customer.findFirst({
      where: { id: dto.accountId, tenantId },
    });
    if (!account) {
      throw new NotFoundException('Account not found in your organization');
    }

    if (dto.projectId) {
      const project = await this.prisma.project.findFirst({
        where: { id: dto.projectId, tenantId },
      });
      if (!project) {
        throw new NotFoundException('Project not found in your organization');
      }
    }

    const invoiceNumber = dto.invoiceNumber?.trim() || (await this.generateInvoiceNumber(tenantId));

    const existing = await this.prisma.invoice.findUnique({
      where: {
        tenantId_invoiceNumber: {
          tenantId,
          invoiceNumber,
        },
      },
    });

    if (existing) {
      throw new ConflictException(`Invoice number "${invoiceNumber}" already exists`);
    }

    const computed = this.computeTotals(dto.items || []);

    return this.prisma.$transaction(async (tx) => {
      const invoice = await tx.invoice.create({
        data: {
          tenantId,
          invoiceNumber,
          status: 'DRAFT',
          accountId: dto.accountId,
          quoteId: dto.quoteId || null,
          dealId: dto.dealId || null,
          projectId: dto.projectId || null,
          contactId: dto.contactId || null,
          ownerId: dto.ownerId || actor?.id || null,
          issueDate: dto.issueDate ? new Date(dto.issueDate) : new Date(),
          dueDate: new Date(dto.dueDate),
          subtotal: computed.subtotal,
          discountTotal: computed.discountTotal,
          taxTotal: computed.taxTotal,
          totalAmount: computed.totalAmount,
          paidAmount: 0,
          notes: dto.notes?.trim() || null,
          terms: dto.terms?.trim() || null,
          items: {
            create: computed.items.map((it) => ({
              productId: it.productId,
              name: it.name,
              description: it.description,
              quantity: it.quantity,
              unitPrice: it.unitPrice,
              discountPercent: it.discountPercent,
              gstRate: it.gstRate,
              lineTotal: it.lineTotal,
              orderIndex: it.orderIndex,
            })),
          },
        },
        include: {
          account: { select: { id: true, name: true } },
          items: true,
        },
      });

      if (dto.timeEntryIds && dto.timeEntryIds.length > 0) {
        await tx.timeEntry.updateMany({
          where: {
            id: { in: dto.timeEntryIds },
            tenantId,
          },
          data: {
            invoiceId: invoice.id,
          },
        });
      }

      return invoice;
    });
  }

  // Generates an invoice directly from an accepted quote
  async createFromQuote(ctx: RequestTenantContext, quoteId: string, dto: CreateFromQuoteDto, actor?: CrmActor) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const quote = await this.prisma.quote.findFirst({
      where: { id: quoteId, tenantId },
      include: {
        items: true,
      },
    });

    if (!quote) {
      throw new NotFoundException('Quote not found');
    }

    const invoiceNumber = await this.generateInvoiceNumber(tenantId);

    return this.prisma.invoice.create({
      data: {
        tenantId,
        invoiceNumber,
        status: 'DRAFT',
        serviceName: quote.serviceName,
        quoteId: quote.id,
        accountId: quote.accountId,
        dealId: quote.dealId,
        contactId: quote.contactId,
        ownerId: quote.ownerId || actor?.id || null,
        issueDate: new Date(),
        dueDate: new Date(dto.dueDate),
        subtotal: quote.subtotal,
        discountTotal: quote.discountTotal,
        taxTotal: quote.taxTotal,
        totalAmount: quote.totalAmount,
        paidAmount: 0,
        notes: dto.notes?.trim() || quote.notes,
        terms: dto.terms?.trim() || quote.terms,
        items: {
          create: quote.items.map((it) => ({
            productId: it.productId,
            name: it.name,
            description: it.description,
            quantity: it.quantity,
            unitPrice: it.unitPrice,
            discountPercent: it.discountPercent,
            gstRate: it.gstRate,
            lineTotal: it.lineTotal,
            orderIndex: it.orderIndex,
          })),
        },
      },
      include: {
        account: { select: { id: true, name: true } },
        items: true,
      },
    });
  }

  // Generates invoice directly from billable project delivery timesheets
  async createFromTimesheets(ctx: RequestTenantContext, dto: CreateFromTimesheetsDto, actor?: CrmActor) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const project = await this.prisma.project.findFirst({
      where: { id: dto.projectId, tenantId },
      include: { account: true },
    });

    if (!project) {
      throw new NotFoundException('Project not found');
    }

    const timeEntries = await this.prisma.timeEntry.findMany({
      where: {
        id: { in: dto.timeEntryIds },
        tenantId,
        projectId: dto.projectId,
        isBillable: true,
        invoiceId: null,
      },
      include: {
        task: { select: { title: true } },
        user: { select: { name: true } },
      },
    });

    if (timeEntries.length === 0) {
      throw new BadRequestException('No un-invoiced billable time entries found matching selection');
    }

    const rate = dto.hourlyRate ?? 2500; // Default ₹2,500/hour
    const invoiceItems: CreateInvoiceItemDto[] = timeEntries.map((te) => ({
      name: `${te.task?.title || 'Engineering Work'} - ${te.user.name}`,
      description: te.note || `${te.hours} hours logged on ${te.date.toISOString().slice(0, 10)}`,
      quantity: Number(te.hours),
      unitPrice: rate,
      discountPercent: 0,
      gstRate: 18.0,
    }));

    const invoiceNumber = await this.generateInvoiceNumber(tenantId);
    const computed = this.computeTotals(invoiceItems);

    return this.prisma.$transaction(async (tx) => {
      const invoice = await tx.invoice.create({
        data: {
          tenantId,
          invoiceNumber,
          status: 'DRAFT',
          projectId: project.id,
          accountId: project.accountId,
          dealId: project.dealId,
          ownerId: actor?.id || null,
          issueDate: new Date(),
          dueDate: new Date(dto.dueDate),
          subtotal: computed.subtotal,
          discountTotal: computed.discountTotal,
          taxTotal: computed.taxTotal,
          totalAmount: computed.totalAmount,
          paidAmount: 0,
          notes: dto.notes?.trim() || `Invoiced ${timeEntries.length} billable timesheets for ${project.name}`,
          terms: dto.terms?.trim() || 'Payment due within 15 days of invoice date',
          items: {
            create: computed.items.map((it) => ({
              productId: it.productId,
              name: it.name,
              description: it.description,
              quantity: it.quantity,
              unitPrice: it.unitPrice,
              discountPercent: it.discountPercent,
              gstRate: it.gstRate,
              lineTotal: it.lineTotal,
              orderIndex: it.orderIndex,
            })),
          },
        },
        include: {
          account: { select: { id: true, name: true } },
          items: true,
        },
      });

      await tx.timeEntry.updateMany({
        where: { id: { in: timeEntries.map((te) => te.id) } },
        data: { invoiceId: invoice.id },
      });

      return invoice;
    });
  }

  // Records a payment against invoice and updates balance / status
  async recordPayment(ctx: RequestTenantContext, id: string, dto: RecordPaymentDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const invoice = await this.get(ctx, id);

    if (invoice.status === 'VOID') {
      throw new BadRequestException('Cannot record payments on a voided invoice');
    }
    if (invoice.status === 'DRAFT') {
      throw new BadRequestException('Send the invoice before recording a payment');
    }

    const amount = Number(dto.amount);
    const balanceDue = Math.round((Number(invoice.totalAmount) - Number(invoice.paidAmount)) * 100) / 100;
    if (balanceDue <= 0) {
      throw new BadRequestException('This invoice is already fully paid');
    }
    if (amount > balanceDue) {
      throw new BadRequestException(`Payment of ₹${amount} is more than the balance due of ₹${balanceDue}`);
    }

    await this.prisma.$transaction(async (tx) => {
      const updated = await tx.invoice.update({
        where: { id },
        data: { paidAmount: { increment: amount } },
        select: { paidAmount: true, totalAmount: true },
      });
      const remaining = Math.round((Number(updated.totalAmount) - Number(updated.paidAmount)) * 100) / 100;
      if (remaining < 0) {
        throw new BadRequestException(`Payment of ₹${amount} is more than the balance due`);
      }

      await tx.payment.create({
        data: {
          tenantId,
          invoiceId: id,
          amount,
          paymentMethod: dto.paymentMethod || 'BANK_TRANSFER',
          transactionRef: dto.transactionRef?.trim() || null,
          paidAt: dto.paidAt ? new Date(dto.paidAt) : new Date(),
          notes: dto.notes?.trim() || null,
          status: 'CAPTURED',
        },
      });

      await tx.invoice.update({ where: { id }, data: { status: remaining === 0 ? 'PAID' : 'PARTIALLY_PAID' } });
    });

    await this.audit.record({
      tenantId,
      entityType: 'INVOICE',
      entityId: id,
      customerId: invoice.accountId,
      action: 'PAYMENT_RECORDED',
      summary: `Payment of ₹${amount} recorded on invoice ${invoice.invoiceNumber}`,
      details: { amount, method: dto.paymentMethod, transactionRef: dto.transactionRef },
    });

    return this.get(ctx, id);
  }

  // Rejects status changes that would bypass the payment records: only DRAFT to SENT or VOID, and unpaid SENT or OVERDUE to VOID.
  private assertStatusChange(current: { status: string; paidAmount: unknown }, next: string) {
    const fromDraft = current.status === 'DRAFT' && (next === 'SENT' || next === 'VOID');
    const voidUnpaid = (current.status === 'SENT' || current.status === 'OVERDUE') && next === 'VOID' && Number(current.paidAmount) === 0;
    if (!fromDraft && !voidUnpaid) {
      throw new BadRequestException(`An invoice cannot move from ${current.status} to ${next}. Record a payment, or void an unpaid invoice.`);
    }
  }

  // Updates invoice status or metadata
  async update(ctx: RequestTenantContext, id: string, dto: UpdateInvoiceDto) {
    const current = await this.get(ctx, id);
    if (dto.status && dto.status !== current.status) {
      this.assertStatusChange(current, dto.status);
    }

    await this.prisma.invoice.update({
      where: { id },
      data: {
        status: dto.status,
        dueDate: dto.dueDate ? new Date(dto.dueDate) : undefined,
        contactId: dto.contactId !== undefined ? dto.contactId : undefined,
        ownerId: dto.ownerId !== undefined ? dto.ownerId : undefined,
        notes: dto.notes !== undefined ? dto.notes?.trim() || null : undefined,
        terms: dto.terms !== undefined ? dto.terms?.trim() || null : undefined,
      },
    });

    return this.get(ctx, id);
  }

  // Deletes a draft invoice; an issued invoice must be voided instead so invoice numbers stay unbroken.
  async delete(ctx: RequestTenantContext, id: string) {
    const invoice = await this.get(ctx, id);

    if (invoice.status !== 'DRAFT') {
      throw new BadRequestException('Only draft invoices can be deleted. Void an issued invoice instead.');
    }

    await this.prisma.$transaction(async (tx) => {
      await tx.timeEntry.updateMany({
        where: { invoiceId: id },
        data: { invoiceId: null },
      });

      await tx.invoice.delete({
        where: { id },
      });
    });

    return { success: true, message: `Invoice "${invoice.invoiceNumber}" deleted successfully` };
  }

  // Generates a professional branded PDF for the invoice
  async generatePdf(ctx: RequestTenantContext, id: string): Promise<{ buffer: Buffer; filename: string }> {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const [invoice, org] = await Promise.all([
      this.prisma.invoice.findFirst({
        where: { id, tenantId },
        include: {
          account: { select: { id: true, name: true, phone: true, website: true, city: true } },
          quote: { select: { id: true, quoteNumber: true } },
          deal: { select: { id: true, title: true, dealNumber: true } },
          project: { select: { id: true, name: true, projectNumber: true } },
          contact: { select: { id: true, name: true, email: true, phone: true } },
          owner: { select: { id: true, name: true, email: true } },
          items: {
            orderBy: { orderIndex: 'asc' },
          },
        },
      }),
      this.prisma.organization.findUnique({
        where: { id: tenantId },
        select: {
          name: true,
          legalName: true,
          addressLine1: true,
          addressLine2: true,
          city: true,
          postalCode: true,
          country: true,
          gstin: true,
          pan: true,
          bankName: true,
          bankAccountNumber: true,
          bankIfsc: true,
          bankBranch: true,
          defaultTerms: true,
        },
      }),
    ]);

    if (!invoice) {
      throw new NotFoundException('Invoice not found');
    }

    const doc = new PDFDocument({ size: 'A4', margin: 40, bufferPages: true });
    const buffers: Buffer[] = [];
    doc.on('data', (chunk) => buffers.push(chunk));

    const orgName = org?.legalName || org?.name || 'TechCMantix CRM';
    const totalAmount = Number(invoice.totalAmount);
    const paidAmount = Number(invoice.paidAmount);
    const balanceDue = Math.max(0, totalAmount - paidAmount);

    const formatINR = (val: number | string | Prisma.Decimal) => `Rs. ${Number(val || 0).toLocaleString('en-IN', { maximumFractionDigits: 2 })}`;
    const formatDate = (d: Date | string) => new Date(d).toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });

    // Header banner
    doc.save();
    doc.rect(40, 40, 515, 65).fill('#0f172a');
    doc.fillColor('#ffffff').fontSize(16).font('Helvetica-Bold').text(orgName.toUpperCase(), 55, 52);

    const orgMeta = [org?.city, org?.gstin ? `GSTIN: ${org.gstin}` : null, org?.pan ? `PAN: ${org.pan}` : null].filter(Boolean).join('  |  ');
    doc
      .fontSize(8)
      .font('Helvetica')
      .fillColor('#94a3b8')
      .text(orgMeta || 'Official Tax Invoice', 55, 74);

    doc.fontSize(16).font('Helvetica-Bold').fillColor('#38bdf8').text('TAX INVOICE', 350, 52, { align: 'right', width: 190 });
    doc.fontSize(9).font('Helvetica-Bold').fillColor('#ffffff').text(invoice.invoiceNumber, 350, 72, { align: 'right', width: 190 });
    doc.fontSize(8).font('Helvetica').fillColor('#cbd5e1').text(`Status: ${invoice.status}`, 350, 86, { align: 'right', width: 190 });
    doc.restore();

    let y = 120;

    // Billed To & Metadata Boxes
    doc.save();
    doc.roundedRect(40, y, 250, 85, 4).fillAndStroke('#f8fafc', '#e2e8f0');
    doc
      .fillColor('#64748b')
      .fontSize(7.5)
      .font('Helvetica-Bold')
      .text('BILLED TO', 52, y + 10);
    doc
      .fillColor('#0f172a')
      .fontSize(11)
      .font('Helvetica-Bold')
      .text(invoice.account?.name || 'Customer', 52, y + 24, { width: 226 });

    const contactLines: string[] = [];
    if (invoice.contact?.name) contactLines.push(`Attn: ${invoice.contact.name}`);
    if (invoice.contact?.email) contactLines.push(invoice.contact.email);
    if (invoice.account?.city) contactLines.push(invoice.account.city);
    doc
      .fillColor('#475569')
      .fontSize(8.5)
      .font('Helvetica')
      .text(contactLines.join('  ·  ') || 'Valued Client', 52, y + 44, { width: 226 });

    doc.roundedRect(305, y, 250, 85, 4).fillAndStroke('#f8fafc', '#e2e8f0');
    doc
      .fillColor('#64748b')
      .fontSize(7.5)
      .font('Helvetica-Bold')
      .text('INVOICE DETAILS', 317, y + 10);

    const metaRows: [string, string][] = [
      ['Issue Date:', formatDate(invoice.issueDate)],
      ['Due Date:', formatDate(invoice.dueDate)],
    ];
    if (invoice.project?.name) {
      metaRows.push(['Project:', invoice.project.name]);
    } else if (invoice.deal?.title) {
      metaRows.push(['Deal:', invoice.deal.title]);
    }

    let metaY = y + 24;
    metaRows.forEach(([lbl, val]) => {
      doc.fillColor('#64748b').fontSize(8.5).font('Helvetica').text(lbl, 317, metaY);
      doc.fillColor('#0f172a').fontSize(8.5).font('Helvetica-Bold').text(val, 390, metaY, { width: 155, align: 'right' });
      metaY += 16;
    });
    doc.restore();

    y = 220;

    // Table Header
    const cols = [
      { label: '#', x: 40, width: 25, align: 'center' },
      { label: 'ITEM / SERVICE DESCRIPTION', x: 65, width: 240, align: 'left' },
      { label: 'QTY', x: 305, width: 45, align: 'right' },
      { label: 'RATE', x: 350, width: 65, align: 'right' },
      { label: 'GST', x: 415, width: 45, align: 'right' },
      { label: 'AMOUNT', x: 460, width: 95, align: 'right' },
    ];

    doc.save();
    doc.rect(40, y, 515, 22).fill('#1e293b');
    cols.forEach((col) => {
      doc
        .fillColor('#ffffff')
        .fontSize(8)
        .font('Helvetica-Bold')
        .text(col.label, col.x + 3, y + 7, {
          width: col.width - 6,
          align: col.align as any,
        });
    });
    doc.restore();

    y += 22;

    // Table Rows
    invoice.items.forEach((item, idx) => {
      const isEven = idx % 2 === 0;
      const rowHeight = item.description ? 34 : 24;

      doc.save();
      if (!isEven) {
        doc.rect(40, y, 515, rowHeight).fill('#f8fafc');
      }
      doc.strokeColor('#e2e8f0').lineWidth(0.5).rect(40, y, 515, rowHeight).stroke();

      doc
        .fillColor('#64748b')
        .fontSize(8.5)
        .font('Helvetica')
        .text(String(idx + 1), cols[0].x + 3, y + 7, {
          width: cols[0].width - 6,
          align: 'center',
        });

      doc
        .fillColor('#0f172a')
        .fontSize(8.5)
        .font('Helvetica-Bold')
        .text(item.name, cols[1].x + 3, y + 6, {
          width: cols[1].width - 6,
          align: 'left',
        });
      if (item.description) {
        doc
          .fillColor('#64748b')
          .fontSize(7.5)
          .font('Helvetica')
          .text(item.description, cols[1].x + 3, y + 18, {
            width: cols[1].width - 6,
            align: 'left',
          });
      }

      doc
        .fillColor('#334155')
        .fontSize(8.5)
        .font('Helvetica')
        .text(String(Number(item.quantity)), cols[2].x + 3, y + 7, {
          width: cols[2].width - 6,
          align: 'right',
        });

      doc
        .fillColor('#334155')
        .fontSize(8.5)
        .font('Helvetica')
        .text(formatINR(item.unitPrice), cols[3].x + 3, y + 7, {
          width: cols[3].width - 6,
          align: 'right',
        });

      doc
        .fillColor('#334155')
        .fontSize(8.5)
        .font('Helvetica')
        .text(`${Number(item.gstRate)}%`, cols[4].x + 3, y + 7, {
          width: cols[4].width - 6,
          align: 'right',
        });

      doc
        .fillColor('#0f172a')
        .fontSize(8.5)
        .font('Helvetica-Bold')
        .text(formatINR(item.lineTotal), cols[5].x + 3, y + 7, {
          width: cols[5].width - 6,
          align: 'right',
        });

      doc.restore();
      y += rowHeight;
    });

    y += 15;

    // Totals Box on Right
    const totalsBoxY = y;
    const totalsWidth = 220;
    const totalsX = 555 - totalsWidth;

    doc.save();
    doc.roundedRect(totalsX, totalsBoxY, totalsWidth, 140, 4).fillAndStroke('#f8fafc', '#e2e8f0');

    const totRows: [string, string][] = [['Subtotal:', formatINR(invoice.subtotal)], ...(Number(invoice.discountTotal) > 0 ? ([['Discount:', `- ${formatINR(invoice.discountTotal)}`]] as [string, string][]) : []), ['GST Tax:', formatINR(invoice.taxTotal)], ['Total Amount:', formatINR(invoice.totalAmount)], ['Amount Paid:', formatINR(invoice.paidAmount)], ['Balance Due:', formatINR(balanceDue)]];

    let tY = totalsBoxY + 10;
    totRows.forEach(([lbl, val]) => {
      const isGrand = lbl === 'Total Amount:';
      const isBal = lbl === 'Balance Due:';

      if (isGrand || isBal) {
        doc
          .strokeColor('#cbd5e1')
          .lineWidth(0.5)
          .moveTo(totalsX + 10, tY - 3)
          .lineTo(totalsX + totalsWidth - 10, tY - 3)
          .stroke();
      }

      const font = isGrand || isBal ? 'Helvetica-Bold' : 'Helvetica';
      const size = isGrand ? 10 : 8.5;
      const color = isBal ? (balanceDue > 0 ? '#dc2626' : '#16a34a') : isGrand ? '#0f172a' : '#475569';

      doc
        .fillColor('#475569')
        .fontSize(size)
        .font(font)
        .text(lbl, totalsX + 12, tY);
      doc
        .fillColor(color)
        .fontSize(size)
        .font('Helvetica-Bold')
        .text(val, totalsX + 90, tY, {
          width: totalsWidth - 102,
          align: 'right',
        });

      tY += isGrand ? 22 : 18;
    });
    doc.restore();

    // Bank Details & Notes on Left
    doc.save();
    const bankBoxWidth = totalsX - 55;
    let bankY = totalsBoxY;

    if (org?.bankName || org?.bankAccountNumber) {
      doc.fillColor('#0f172a').fontSize(8.5).font('Helvetica-Bold').text('BANK & PAYMENT DETAILS', 40, bankY);
      bankY += 14;
      const bankInfo = [org.bankName ? `Bank: ${org.bankName}` : null, org.bankAccountNumber ? `A/C: ${org.bankAccountNumber}` : null, org.bankIfsc ? `IFSC: ${org.bankIfsc}` : null, org.bankBranch ? `Branch: ${org.bankBranch}` : null].filter(Boolean).join('  |  ');
      doc.fillColor('#475569').fontSize(8).font('Helvetica').text(bankInfo, 40, bankY, { width: bankBoxWidth });
      bankY += 20;
    }

    if (invoice.notes || org?.defaultTerms || invoice.terms) {
      const notesText = invoice.notes || invoice.terms || org?.defaultTerms;
      doc.fillColor('#0f172a').fontSize(8.5).font('Helvetica-Bold').text('NOTES & TERMS', 40, bankY);
      bankY += 14;
      doc.fillColor('#64748b').fontSize(8).font('Helvetica').text(notesText!, 40, bankY, { width: bankBoxWidth });
    }
    doc.restore();

    // Footer on all pages cleanly without page overflow
    const range = doc.bufferedPageRange();
    for (let i = range.start; i < range.start + range.count; i++) {
      doc.switchToPage(i);
      doc.save();
      doc.page.margins.bottom = 0;
      doc.rect(40, 770, 515, 0.5).fill('#cbd5e1');
      doc.fillColor('#94a3b8').fontSize(7.5).font('Helvetica').text('Thank you for your business!  ·  TechCMantix CRM  ·  Official Billing Document', 40, 778, {
        align: 'center',
        width: 515,
        lineBreak: false,
      });
      doc.restore();
    }

    doc.end();

    return new Promise((resolve, reject) => {
      doc.on('end', () => {
        resolve({
          buffer: Buffer.concat(buffers),
          filename: `invoice-${invoice.invoiceNumber}.pdf`,
        });
      });
      doc.on('error', reject);
    });
  }
}
