import { fmtDate } from "./dates";
import { fmtMoney } from "./format";

export interface ContractData {
  code: string;
  version: number;
  businessName: string;
  businessAddress: string;
  businessPhone: string;
  businessEmail: string;
  customerName: string;
  customerIdType: string | null;
  customerIdNumber: string | null;
  customerPhone: string;
  customerNationality: string | null;
  customerAddress: string | null;
  apartmentName: string;
  apartmentCode: string;
  apartmentAddress: string;
  checkIn: Date;
  checkOut: Date;
  checkInTime: string;
  checkOutTime: string;
  nights: number;
  nightlyPrice: number;
  total: number;
  deposit: number;
  guests: number;
  reservationCode: string;
  terms: string;
  generatedAt: Date;
  currency?: string;
}

function esc(s: string | null | undefined) {
  return (s ?? "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

/** Render a self-contained printable contract (HTML snapshot). */
export function renderContractHtml(d: ContractData): string {
  const cur = d.currency ?? "MAD";
  const terms = d.terms
    .replace(/\{\{checkInTime\}\}/g, d.checkInTime)
    .replace(/\{\{checkOutTime\}\}/g, d.checkOutTime)
    .replace(/\{\{deposit\}\}/g, fmtMoney(d.deposit, cur));
  const termList = terms
    .split(/\n+/)
    .filter(Boolean)
    .map((t) => `<li>${esc(t.replace(/^\d+\.\s*/, ""))}</li>`)
    .join("");

  return `<!doctype html>
<html><head><meta charset="utf-8"><title>${esc(d.code)} — Rental contract</title>
<style>
  *{box-sizing:border-box} body{font-family:Georgia,'Times New Roman',serif;color:#1c1917;margin:0;padding:48px 56px;line-height:1.5;font-size:13px;background:#fff}
  h1{font-size:22px;letter-spacing:.02em;margin:0 0 4px;font-weight:600}
  .muted{color:#78716c;font-size:11px}
  .head{display:flex;justify-content:space-between;align-items:flex-start;border-bottom:2px solid #1c1917;padding-bottom:16px;margin-bottom:24px}
  .brand{font-size:16px;font-weight:700;letter-spacing:.08em;text-transform:uppercase}
  .grid{display:grid;grid-template-columns:1fr 1fr;gap:24px;margin-bottom:24px}
  .box{border:1px solid #d6d3d1;padding:14px 16px;border-radius:4px}
  .box h3{margin:0 0 8px;font-size:11px;text-transform:uppercase;letter-spacing:.1em;color:#78716c}
  table{width:100%;border-collapse:collapse;margin:8px 0 24px}
  td,th{padding:8px 10px;border-bottom:1px solid #e7e5e4;text-align:left;font-size:13px}
  th{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:#78716c;font-weight:600}
  .total td{font-weight:700;font-size:14px;border-top:2px solid #1c1917;border-bottom:none}
  ol{padding-left:18px;margin:0} li{margin-bottom:6px}
  .sign{display:grid;grid-template-columns:1fr 1fr;gap:48px;margin-top:48px}
  .sig{border-top:1px solid #1c1917;padding-top:8px;font-size:11px;color:#78716c;height:80px}
  @media print{body{padding:24px 32px}}
</style></head><body>
<div class="head">
  <div><div class="brand">${esc(d.businessName)}</div><div class="muted">${esc(d.businessAddress)}<br>${esc(d.businessPhone)} · ${esc(d.businessEmail)}</div></div>
  <div style="text-align:right"><h1>Short-term rental contract</h1><div class="muted">Contract ${esc(d.code)} · v${d.version}<br>Reservation ${esc(d.reservationCode)}<br>Issued ${fmtDate(d.generatedAt, { style: "long" })}</div></div>
</div>
<div class="grid">
  <div class="box"><h3>Tenant</h3><strong>${esc(d.customerName)}</strong><br>${esc(d.customerIdType ?? "ID")}: ${esc(d.customerIdNumber ?? "—")}<br>Phone: ${esc(d.customerPhone)}<br>${d.customerNationality ? "Nationality: " + esc(d.customerNationality) + "<br>" : ""}${d.customerAddress ? esc(d.customerAddress) : ""}</div>
  <div class="box"><h3>Property</h3><strong>${esc(d.apartmentName)}</strong> <span class="muted">(${esc(d.apartmentCode)})</span><br>${esc(d.apartmentAddress)}<br>Maximum occupants: ${d.guests}</div>
</div>
<table>
  <tr><th>Check-in</th><th>Check-out</th><th>Nights</th><th>Nightly rate</th><th style="text-align:right">Amount</th></tr>
  <tr><td>${fmtDate(d.checkIn, { style: "long" })} from ${esc(d.checkInTime)}</td><td>${fmtDate(d.checkOut, { style: "long" })} before ${esc(d.checkOutTime)}</td><td>${d.nights}</td><td>${fmtMoney(d.nightlyPrice, cur)}</td><td style="text-align:right">${fmtMoney(d.total, cur)}</td></tr>
  <tr><td colspan="4">Security deposit (refundable)</td><td style="text-align:right">${fmtMoney(d.deposit, cur)}</td></tr>
  <tr class="total"><td colspan="4">Total rental amount</td><td style="text-align:right">${fmtMoney(d.total, cur)}</td></tr>
</table>
<h3 style="font-size:11px;text-transform:uppercase;letter-spacing:.1em;color:#78716c;margin:0 0 8px">Terms and conditions</h3>
<ol>${termList}</ol>
<div class="sign">
  <div class="sig">Tenant signature<br><span style="font-size:10px">${esc(d.customerName)} · read and approved</span></div>
  <div class="sig">For ${esc(d.businessName)}</div>
</div>
</body></html>`;
}
