import PDFDocument from 'pdfkit';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { NotFoundError } from '../../lib/errors';
import { getTenantFileBytes } from '../uploads/uploads.service';
import type { Deduction } from './moveouts.service';

/**
 * The settlement statement: what the hostel held, what it kept and why,
 * and what it owes the student by when. Same house layout as the receipt,
 * so a parent who has seen one has seen the other.
 */

const NAVY = '#1a3a5c';
const NAVY2 = '#0f2540';
const LGRAY = '#f8fafc';
const DGRAY = '#1e293b';
const MGRAY = '#64748b';
const SGRAY = '#94a3b8';
const BORDER = '#e2e8f0';
const GREEN = '#16a34a';
const AMBER = '#d97706';
const RED = '#dc2626';
const WHITE = '#ffffff';
const GOLD = '#f59e0b';

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

export const settlementNumber = (id: string, lastDay: Date) => `SET-${lastDay.toISOString().slice(0, 7).replace('-', '')}-${id.slice(0, 6).toUpperCase()}`;

export async function buildSettlementPdf(moveOutId: string, opts: { userId?: string } = {}): Promise<{ buffer: Buffer; filename: string }> {
  const m = await db.moveOut.findFirst({
    where: { id: moveOutId },
    include: {
      settlement: true,
      student: { include: { user: { select: { name: true, email: true, phone: true } }, bed: { select: { label: true, room: { select: { number: true, floor: true } } } } } },
      property: { select: { name: true, address: true, city: true, state: true } },
    },
  });
  if (!m || !m.settlement) throw new NotFoundError('Settlement not found');
  if (opts.userId && m.student.userId !== opts.userId) throw new NotFoundError('Settlement not found');
  const s = m.settlement;
  const settings = await db.tenantSettings.findFirst({ select: { billingFirmName: true, billingGstin: true, billingAddress: true, billingPhone: true, billingEmail: true, billingLogoUrl: true } });
  const logo = settings?.billingLogoUrl ? await getTenantFileBytes(getTenantIdOrThrow(), settings.billingLogoUrl) : null;
  const firm = settings?.billingFirmName?.trim() || m.property.name || 'HostelCare';
  const firmAddress = settings?.billingAddress?.trim() || [m.property.address, m.property.city, m.property.state].filter(Boolean).join(', ') || '';
  const contactLine = [settings?.billingPhone && `Tel: ${settings.billingPhone}`, settings?.billingEmail].filter(Boolean).join('   |   ');
  const number = settlementNumber(m.id, m.lastDay);
  const deductions = s.deductions as unknown as Deduction[];
  const netDues = Math.max(0, s.duesBalance - s.prorataCredit);
  const refunded = !!s.refundedAt;

  const doc = new PDFDocument({ size: 'A4', margin: 0, compress: true, info: { Title: `${firm} ${number}`, Author: firm } });
  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
  const LOGO = 54;
  const textLeft = logo ? M + LOGO + 12 : M;
  const textW = CW * 0.6 - (logo ? LOGO + 12 : 0);
  doc.font('Helvetica').fontSize(8.5);
  const addrH = firmAddress ? doc.heightOfString(firmAddress, { width: textW }) : 0;
  const HDR_H = Math.max(118, 47 + addrH + (contactLine ? 13 : 0) + 14);
  doc.rect(0, 0, PW, HDR_H).fill(NAVY);
  doc.rect(0, HDR_H - 4, PW, 4).fill(GOLD);
  if (logo) {
    try {
      doc.save();
      doc.roundedRect(M, 18, LOGO, LOGO, 6).fill(WHITE);
      doc.image(logo, M + 3, 21, { fit: [LOGO - 6, LOGO - 6], align: 'center', valign: 'center' });
      doc.restore();
    } catch {
      /* unreadable logo: the name carries the header */
    }
  }
  doc.fillColor(WHITE).font('Helvetica-Bold').fontSize(20).text(firm, textLeft, 20, { width: textW, lineBreak: false, ellipsis: true });
  let hy = 47;
  doc.font('Helvetica').fontSize(8.5).fillColor(SGRAY);
  if (firmAddress) {
    doc.text(firmAddress, textLeft, hy, { width: textW });
    hy += addrH + 3;
  }
  if (contactLine) doc.text(contactLine, textLeft, hy, { width: textW });
  doc.fillColor(WHITE).font('Helvetica-Bold').fontSize(17).text('SETTLEMENT', M, 18, { width: CW, align: 'right' });
  doc.fillColor(SGRAY).font('Helvetica').fontSize(8.5);
  doc.text(`Statement No:  ${number}`, M, 47, { width: CW, align: 'right' });
  doc.text(`Shared:  ${dayLabel(s.sharedAt)}`, M, 61, { width: CW, align: 'right' });
  doc.text(`Last day:  ${dayLabel(m.lastDay)}`, M, 75, { width: CW, align: 'right' });

  // Student | Refund
  let y = HDR_H + 22;
  const COL2 = M + CW * 0.55;
  doc.fillColor(NAVY).font('Helvetica-Bold').fontSize(7.5).text('STUDENT', M, y);
  doc.text('REFUND', COL2, y);
  y += 11;
  doc.fillColor(DGRAY).font('Helvetica-Bold').fontSize(12.5).text(m.student.user.name, M, y, { width: CW * 0.5 });
  let ly = y + 20;
  const rows: [string, string | null | undefined][] = [
    ['Room', m.student.bed ? `Room ${m.student.bed.room.number}, Bed ${m.student.bed.label}` : null],
    ['Property', m.property.name],
    ['Notice given', dayLabel(m.noticeDate)],
    ['Email', m.student.user.email],
  ];
  doc.font('Helvetica').fontSize(9);
  for (const [label, value] of rows) {
    if (!value) continue;
    doc.fillColor(MGRAY).text(label, M, ly, { width: 70 });
    doc.fillColor(DGRAY).text(value, M + 70, ly, { width: CW * 0.5 - 78 });
    ly += 15;
  }
  // Refund block
  const RW = CW * 0.45;
  doc.rect(COL2, y, RW, 58).fill(NAVY2);
  doc.fillColor(WHITE).font('Helvetica-Bold').fontSize(9).text(refunded ? 'REFUNDED' : s.shortfall > 0 ? 'AMOUNT DUE FROM STUDENT' : 'REFUND DUE TO STUDENT', COL2 + 10, y + 10, { width: RW - 20 });
  doc.fillColor(GOLD).font('Helvetica-Bold').fontSize(18).text(money(refunded ? (s.refundAmount ?? s.refundDue) : s.shortfall > 0 ? s.shortfall : s.refundDue), COL2 + 10, y + 26, { width: RW - 20 });
  let ry = y + 66;
  doc.font('Helvetica').fontSize(8.5).fillColor(MGRAY).text(refunded ? `Paid on ${dayLabel(s.refundedAt)} by ${s.refundMethod ?? '-'}${s.refundReference ? ` · ref ${s.refundReference}` : ''}` : s.shortfall > 0 ? `Payable by ${dayLabel(m.lastDay)}` : `Promised by ${dayLabel(s.promisedDate)}`, COL2, ry, { width: RW });
  ry += 14;
  const chip = refunded ? { text: 'REFUNDED', fill: GREEN, w: 70 } : s.disputeRequestId ? { text: 'DISPUTED', fill: RED, w: 64 } : { text: 'SHARED', fill: AMBER, w: 56 };
  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' });

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

  // Table: the arithmetic
  const TH = 26;
  const TR = 24;
  const C0 = 30;
  const C3 = 120;
  const C1 = CW - C0 - C3;
  const line = (n: number, title: string, sub: string | null, amount: number, credit = false, bold = false) => {
    doc.rect(M, y, CW, TR).fill(n % 2 ? LGRAY : WHITE);
    doc.fillColor(DGRAY).font('Helvetica').fontSize(9).text(String(n), M, y + 7, { width: C0, align: 'center' });
    doc.font(bold ? 'Helvetica-Bold' : 'Helvetica').fontSize(9.5).fillColor(DGRAY).text(title, M + C0 + 8, y + (sub ? 4 : 7), { width: C1 - 16, lineBreak: false, ellipsis: true });
    if (sub) doc.font('Helvetica').fontSize(7.5).fillColor(MGRAY).text(sub, M + C0 + 8, y + 14, { width: C1 - 16, lineBreak: false, ellipsis: true });
    doc.font('Helvetica-Bold').fontSize(9.5).fillColor(credit ? GREEN : DGRAY).text(credit ? `+ ${money(amount)}` : `- ${money(amount)}`, M + C0 + C1 + 4, y + 7, { width: C3 - 12, align: 'right' });
    y += TR;
  };
  doc.rect(M, y, CW, TH).fill(NAVY);
  doc.fillColor(WHITE).font('Helvetica-Bold').fontSize(8.5);
  doc.text('#', M, y + 9, { width: C0, align: 'center' });
  doc.text('ITEM', M + C0 + 8, y + 9, { width: C1 - 16 });
  doc.text('AMOUNT', M + C0 + C1 + 4, y + 9, { width: C3 - 12, align: 'right' });
  y += TH;
  const top = y;
  let n = 0;
  line(++n, 'Security deposit held', 'Received at move-in, less any earlier refund', s.depositHeld, true, true);
  if (s.duesBalance > 0) line(++n, 'Unpaid invoices at move-out', 'Rent, mess and charges still open', s.duesBalance);
  if (s.prorataCredit > 0) line(++n, 'Final-month credit', `Days after ${dayLabel(m.lastDay)} not stayed`, s.prorataCredit, true);
  for (const d of deductions) line(++n, d.label, d.note ?? (d.fromCheck ? 'From the room checklist' : null), d.amount);
  doc.rect(M, top - TH, CW, TH + (y - top)).strokeColor(BORDER).lineWidth(0.75).stroke();
  y += 16;

  // Summary
  const SW = 250;
  const SX = PW - M - SW;
  const SLW = 150;
  const sum: [string, string][] = [
    ['Deposit held', money(s.depositHeld)],
    ['Less unpaid dues (net of credit)', netDues > 0 ? `- ${money(netDues)}` : money(0)],
    ['Less deductions', s.deductionsTotal > 0 ? `- ${money(s.deductionsTotal)}` : money(0)],
  ];
  for (const [label, value] of sum) {
    doc.font('Helvetica').fontSize(9).fillColor(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;
  doc.rect(SX, y, SW, 32).fill(NAVY2);
  doc.font('Helvetica-Bold').fontSize(9.5).fillColor(WHITE).text(s.shortfall > 0 ? 'DUE FROM STUDENT' : 'REFUND DUE', SX + 10, y + 11, { width: SLW });
  doc.font('Helvetica-Bold').fontSize(13).fillColor(GOLD).text(money(s.shortfall > 0 ? s.shortfall : s.refundDue), SX + 10, y + 9, { width: SW - 20, align: 'right' });
  y += 46;

  if (s.shortfall > 0) {
    doc.font('Helvetica').fontSize(8.5).fillColor(MGRAY).text('The deposit did not cover the dues and deductions. The difference has been raised as a final invoice, payable by the last day.', M, y, { width: CW });
    y += 24;
  }
  if (s.notes) {
    doc.font('Helvetica-Bold').fontSize(7.5).fillColor(NAVY).text('NOTES', M, y);
    y += 11;
    doc.font('Helvetica').fontSize(8.5).fillColor(DGRAY).text(s.notes, M, y, { width: CW });
  }

  // Footer
  const FOOT_H = 70;
  doc.rect(0, PH - FOOT_H, PW, 4).fill(GOLD);
  doc.rect(0, PH - FOOT_H + 4, PW, FOOT_H - 4).fill(LGRAY);
  doc.font('Helvetica-Bold').fontSize(10).fillColor(NAVY).text(`Thank you for staying with ${firm}.`, M, PH - FOOT_H + 14, { width: CW, align: 'center' });
  doc.font('Helvetica').fontSize(7.5).fillColor(MGRAY).text('This is a computer-generated statement and is valid without a physical signature. Questions about a deduction can be raised from the HostelCare app within 7 days.', M, PH - FOOT_H + 30, { width: CW, align: 'center' });
  doc.font('Helvetica').fontSize(7).fillColor(SGRAY).text(`${firm}   |   Generated on ${dayLabel(new Date())}`, M, PH - 18, { width: CW, align: 'center' });

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