// ═══════════════════════════════════════════════════════════════
// inventory-lens-forms.jsx — vendor lens return forms (Inventory Step 7)
// ═══════════════════════════════════════════════════════════════
//
// WHAT THIS IS (in plain English):
// When a lens goes back to the manufacturer — expired, or opened and not
// used — the vendor wants their own certificate of destruction, and they
// each want a different one. None of them is a fillable PDF: they send
// static paper. So, exactly as Heather's app does, we redraw each vendor's
// sheet and print the values onto it.
//
// The wording, the fax numbers, the email addresses and the row limits are
// the vendors' own and are reproduced here character for character — a form
// that doesn't look like theirs is a form that gets bounced. The row limits
// are real: Rayner takes 15 lenses per sheet, Bausch + Lomb's opened-not-
// used sheet only 5.
//
// Drawn with jsPDF, which the app already loads for the operative note, in
// points (612 × 792 = US Letter) so the vendor layouts keep their spacing.
// ═══════════════════════════════════════════════════════════════

const LENS_FORM_GREY = [230, 230, 230];

// Heather's iolDrawTable: grey header band, every cell bordered, no wrapping
// (a long description overruns — the vendors' own sheets are no better).
function lensFormTable(doc, { x, y, colWidths, headers, rows, rowH = 22, headerH = 18 }) {
  const totalW = colWidths.reduce((a, b) => a + b, 0);
  doc.setDrawColor(0, 0, 0); doc.setLineWidth(1);
  doc.setFillColor(...LENS_FORM_GREY);
  doc.rect(x, y, totalW, headerH, 'FD');
  doc.setFont('helvetica', 'bold'); doc.setFontSize(8); doc.setTextColor(0, 0, 0);
  let cx = x;
  headers.forEach((h, i) => { doc.text(String(h), cx + 4, y + headerH - 5); cx += colWidths[i]; });
  let ry = y + headerH;
  doc.setFont('helvetica', 'normal');
  for (const row of rows) {
    doc.rect(x, ry, totalW, rowH);
    let cxx = x;
    row.forEach((cell, i) => { if (cell !== '' && cell != null) doc.text(String(cell), cxx + 4, ry + rowH - 7); cxx += colWidths[i]; });
    ry += rowH;
  }
  // column separators run the full height of the table
  let sx = x;
  for (let i = 0; i < colWidths.length; i++) { if (i > 0) doc.line(sx, y, sx, ry); sx += colWidths[i]; }
  doc.line(x + totalW, y, x + totalW, ry);
  return ry;
}
const lensFormPad = (rows, n) => { const out = rows.slice(0, n); while (out.length < n) out.push([]); return out; };
const lensFormCell = (row, key) => (row && row[key] != null ? String(row[key]) : '');

// ─── The five vendor sheets ──────────────────────────────────────
function lensFormDrawJJ(doc, data) {
  const L = data.practice || {}, lenses = data.lenses || [];
  doc.setFont('helvetica', 'bold'); doc.setFontSize(16); doc.setTextColor(178, 0, 0);
  doc.text('Johnson & Johnson Vision', 50, 42);
  doc.setFontSize(13); doc.setTextColor(0, 0, 0);
  doc.text('Expired IOL Certificate of Destruction', 300, 42);
  doc.setFont('helvetica', 'normal'); doc.setFontSize(9);
  doc.text('TOLL FREE FAX NO. (800)752-7006', 300, 57);

  const boxY = 72;
  doc.setDrawColor(0, 0, 0); doc.setLineWidth(1);
  doc.rect(50, boxY, 512, 20);
  doc.line(180, boxY, 180, boxY + 20); doc.line(400, boxY, 400, boxY + 20);
  doc.setFont('helvetica', 'bold'); doc.setFontSize(8);
  doc.text('ACCOUNT #:', 55, boxY + 13);
  doc.text('ACCOUNT NAME:', 185, boxY + 13);
  doc.text('PO NUMBER:', 405, boxY + 13);
  doc.setFont('helvetica', 'normal'); doc.setFontSize(9);
  doc.text(String(L.account_number || ''), 110, boxY + 13);
  doc.text(String(L.account_name || ''), 260, boxY + 13);
  doc.text(String(L.po_number || ''), 460, boxY + 13);

  doc.setFontSize(8); doc.setTextColor(51, 51, 153);
  doc.text('Instructions: Complete Account info, list expired IOL info below, complete signature fields, return via email or fax.', 50, 112);
  doc.setTextColor(0, 0, 0);

  // Ten 250×55 boxes — a real sticker from each lens box goes in the empty ones.
  const gridY = 127, boxW = 250, boxH = 55, gap = 12;
  for (let i = 0; i < 10; i++) {
    const col = i % 2, row = Math.floor(i / 2);
    const bx = 50 + col * (boxW + gap), by = gridY + row * (boxH + gap);
    doc.rect(bx, by, boxW, boxH);
    const lens = lenses[i];
    doc.setFontSize(8);
    if (lens) {
      doc.setTextColor(0, 0, 0);
      doc.text('Model: ' + lensFormCell(lens, 'model'), bx + 6, by + 15);
      doc.text('Power: ' + lensFormCell(lens, 'power'), bx + 6, by + 27);
      doc.text('Serial: ' + lensFormCell(lens, 'serial'), bx + 6, by + 39);
      doc.text('Lot: ' + lensFormCell(lens, 'lot'), bx + 6, by + 51);
    } else {
      doc.setTextColor(153, 153, 153);
      doc.text('(IOL STICKER)', bx + boxW / 2, by + boxH / 2 + 3, { align: 'center' });
      doc.setTextColor(0, 0, 0);
    }
  }

  let y = gridY + 5 * (boxH + gap) + 14;
  doc.setFontSize(8);
  doc.text("I certify each of the above IOLs are expired and will be destroyed per J&J Vision's IOL Destruction Policy.", 50, y);
  y += 12;
  doc.rect(50, y, 512, 60);
  doc.line(50, y + 20, 562, y + 20); doc.line(50, y + 40, 562, y + 40);
  doc.line(326, y, 326, y + 60);
  doc.setFont('helvetica', 'bold'); doc.setFontSize(8);
  doc.text('eMail:', 55, y + 14); doc.text('Phone #:', 55, y + 34); doc.text('Date:', 55, y + 54);
  doc.text('Signature:', 331, y + 14); doc.text('Name:', 331, y + 34); doc.text('Title:', 331, y + 54);
  doc.setFont('helvetica', 'normal'); doc.setFontSize(9);
  doc.text(String(L.email || ''), 100, y + 14);
  doc.text(String(L.phone || ''), 100, y + 34);
  doc.text(String(data.date || ''), 100, y + 54);
  doc.text(String(L.name || ''), 385, y + 34);
  doc.text(String(L.title || ''), 385, y + 54);
}

function lensFormDrawRxSight(doc, data) {
  const L = data.practice || {}, lenses = data.lenses || [];
  doc.setFont('helvetica', 'bold'); doc.setFontSize(12); doc.setTextColor(0, 0, 0);
  doc.text('Light Adjustable Lens', 50, 42);
  doc.setFontSize(15);
  doc.text('Certification of Destruction', 50, 62);
  doc.setFont('helvetica', 'normal'); doc.setFontSize(9);
  doc.text('Please return this sheet to: customerexperience@rxsight.com', 50, 82);

  const rows = lensFormPad(lenses.map((l) => [lensFormCell(l, 'model'), lensFormCell(l, 'serial'), lensFormCell(l, 'expiry')]), 6);
  let y = lensFormTable(doc, { x: 50, y: 112, colWidths: [220, 180, 112], headers: ['Item/Model', 'Serial Number', 'Expiry Date'], rows });

  y += 40;
  doc.setFontSize(10);
  doc.text('I hereby certify that the above lenses were destroyed in our facility.', 50, y);
  y += 40;
  doc.setLineWidth(1);
  doc.line(50, y, 290, y); doc.line(400, y, 562, y);
  doc.setFontSize(9);
  doc.text(String(L.name_title || ''), 52, y - 4);
  doc.text(String(L.date || data.date || ''), 402, y - 4);
  doc.setFontSize(8);
  doc.text('Name and Title', 50, y + 10); doc.text('Date', 400, y + 10);
  y += 35;
  doc.line(50, y, 290, y); doc.line(400, y, 562, y);
  doc.setFontSize(9);
  doc.text(String(L.phone || ''), 402, y - 4);
  doc.setFontSize(8);
  doc.text('Signature', 50, y + 10); doc.text('Phone', 400, y + 10);
}

function lensFormDrawBL(doc, data, openedNotUsed) {
  const L = data.practice || {}, lenses = data.lenses || [];
  doc.setFont('helvetica', 'bold'); doc.setFontSize(18); doc.setTextColor(0, 140, 140);
  doc.text('BAUSCH + LOMB', 190, 42);
  doc.setTextColor(0, 0, 0); doc.setFontSize(13);
  doc.text(openedNotUsed ? 'Opened Not Used' : 'Expired Lens', 250, 72);
  doc.text('Certificate of Destruction', 220, 88);

  doc.setFont('helvetica', 'normal'); doc.setFontSize(10);
  let y = 128;
  doc.text('Date: ' + String(L.date || data.date || ''), 50, y); y += 18;
  doc.text('Customer#: ' + String(L.customer_number || ''), 50, y); y += 18;
  doc.text('Facility Name: ' + String(L.facility_name || ''), 50, y); y += 18;
  const yes = /^y/i.test(String(L.replace_yn || '')) ? 'X' : '_';
  const no = /^n/i.test(String(L.replace_yn || '')) ? 'X' : '_';
  doc.text('Replace lenses   Yes ___' + yes + '___   No ___' + no + '___     PO#: ' + String(L.po_number || ''), 50, y);
  y += 24;

  const rows = lensFormPad(lenses.map((l) => [lensFormCell(l, 'model'), lensFormCell(l, 'diopter'), lensFormCell(l, 'serial')]), openedNotUsed ? 5 : 6);
  y = lensFormTable(doc, { x: 50, y, colWidths: [212, 150, 150], headers: ['TYPE OF LENS/MODEL', 'DIOPTER', 'SERIAL NUMBER'], rows });

  y += 30;
  doc.setFontSize(9);
  doc.text('I hereby certify that the above lenses were destroyed in our facility.' + (openedNotUsed ? ' There was no patient contact.' : ''), 50, y);
  y += 44;
  doc.setLineWidth(1);
  doc.line(50, y, 250, y); doc.line(270, y, 420, y); doc.line(440, y, 562, y);
  doc.text(String(L.date || data.date || ''), 442, y - 4);
  doc.setFontSize(8);
  doc.text('Name and Title', 50, y + 10); doc.text('Signature', 270, y + 10); doc.text('Date', 440, y + 10);
  y += 34;
  doc.setFontSize(9);
  doc.text('Phone: ' + String(L.phone || ''), 50, y);
  y += 26;
  doc.setFontSize(8);
  doc.text('Please return this form via fax number 800-822-8918 Attention: ' + (openedNotUsed
    ? 'Consignment Team or via e-mail at SU.Consign@bausch.com'
    : 'Expired Team or via e-mail at BLexpired@bausch.com'), 50, y);
}

function lensFormDrawRayner(doc, data) {
  const L = data.practice || {}, lenses = data.lenses || [];
  doc.setFont('helvetica', 'bold'); doc.setFontSize(16); doc.setTextColor(0, 0, 0);
  doc.text('Rayner', 50, 37);
  doc.setFontSize(13);
  doc.text('CUSTOMER CERTIFICATE OF DESTRUCTION FORM', 130, 62);

  const pairs = [
    ['Date:', L.date || data.date || '', 'Company Name:', L.company_name || ''],
    ['CUSTOMER #:', L.customer_number || '', '', ''],
    ['Telephone No.', L.phone || '', 'Fax No.', L.fax || ''],
    ['', '', 'Email:', L.email || ''],
  ];
  let y = 92;
  for (const [l1, v1, l2, v2] of pairs) {
    doc.setFont('helvetica', 'bold'); doc.setFontSize(9);
    if (l1) doc.text(l1, 50, y);
    if (l2) doc.text(l2, 320, y);
    doc.setFont('helvetica', 'normal');
    if (v1) doc.text(String(v1), 150, y);
    if (v2) doc.text(String(v2), 410, y);
    y += 16;
  }
  y += 10;
  doc.setFontSize(7); doc.setTextColor(128, 0, 77);
  doc.text('PLACE LABELS BELOW OR COMPLETE ITEM DETAILS — FULL 11 DIGIT LOT/SERIAL NUMBER, MODEL NUMBER, AND DIOPTER POWER SIZE', 50, y);
  doc.setTextColor(0, 0, 0);
  y += 12;

  const rows = lensFormPad(lenses.map((l) => [lensFormCell(l, 'lot_serial'), lensFormCell(l, 'model_diopter'), lensFormCell(l, 'reason'), lensFormCell(l, 'qty')]), 15);
  y = lensFormTable(doc, { x: 50, y, colWidths: [140, 180, 110, 82], headers: ['Device Lot/Serial No.', 'Model with Diopter', 'Reason for Disposal', 'QTY Needed'], rows, rowH: 15, headerH: 22 });

  y += 15;
  doc.setFont('helvetica', 'bold'); doc.setFontSize(10);
  doc.text('Total Lenses: ' + lenses.length, 50, y);
  y += 20;
  doc.setFont('helvetica', 'normal'); doc.setFontSize(7);
  doc.text('This form acknowledges the IOLs did not come in physical contact with the patient, or no adverse event occurred.', 50, y);
  y += 12;
  doc.setTextColor(178, 0, 0);
  doc.text('Send completed form to Customer Service at CustomerServiceUSA@Rayner.com or fax (844)-729-6372', 50, y);
  doc.setTextColor(0, 0, 0);
}

// ─── The five, and what each one needs typed in ──────────────────
const LENS_RETURN_FORMS = {
  jnj_expired: {
    label: 'Johnson & Johnson Vision — Expired IOL',
    lensCols: [['model', 'Model'], ['power', 'Power'], ['serial', 'Serial #'], ['lot', 'Lot #']],
    practiceFields: [['account_number', 'Account #'], ['account_name', 'Account Name'], ['po_number', 'PO Number'], ['email', 'Email'], ['phone', 'Phone'], ['name', 'Name'], ['title', 'Title']],
    maxRows: 10, draw: lensFormDrawJJ,
  },
  rxsight: {
    label: 'RxSight / Light Adjustable Lens',
    lensCols: [['model', 'Item/Model'], ['serial', 'Serial #'], ['expiry', 'Expiry Date']],
    practiceFields: [['name_title', 'Name and Title'], ['date', 'Date'], ['phone', 'Phone']],
    maxRows: 6, draw: lensFormDrawRxSight,
  },
  bl_expired: {
    label: 'Bausch + Lomb — Expired',
    lensCols: [['model', 'Model'], ['diopter', 'Diopter'], ['serial', 'Serial #']],
    practiceFields: [['date', 'Date'], ['customer_number', 'Customer #'], ['facility_name', 'Facility Name'], ['replace_yn', 'Replace lenses (Yes/No)'], ['po_number', 'PO #'], ['phone', 'Phone']],
    maxRows: 6, draw: (doc, data) => lensFormDrawBL(doc, data, false),
  },
  bl_opened: {
    label: 'Bausch + Lomb — Opened Not Used',
    lensCols: [['model', 'Model'], ['diopter', 'Diopter'], ['serial', 'Serial #']],
    practiceFields: [['date', 'Date'], ['customer_number', 'Customer #'], ['facility_name', 'Facility Name'], ['replace_yn', 'Replace lenses (Yes/No)'], ['po_number', 'PO #'], ['phone', 'Phone']],
    maxRows: 5, draw: (doc, data) => lensFormDrawBL(doc, data, true),
  },
  rayner: {
    label: 'Rayner',
    lensCols: [['lot_serial', 'Lot/Serial (11 digit)'], ['model_diopter', 'Model + Diopter'], ['reason', 'Reason'], ['qty', 'Qty Needed']],
    practiceFields: [['date', 'Date'], ['company_name', 'Company Name'], ['customer_number', 'Customer #'], ['phone', 'Phone'], ['fax', 'Fax'], ['email', 'Email']],
    maxRows: 15, draw: lensFormDrawRayner,
  },
};

// ─── Whose lens is this? ─────────────────────────────────────────
// A certificate of destruction only covers that vendor's own lenses — an
// Alcon lens on a Johnson & Johnson form gets the whole sheet sent back. The
// catalog records the maker of every lens, so the form can tell.
const LENS_FORM_VENDOR_PATTERNS = {
  jnj_expired: /j\s*&\s*j|johnson|jnj|\bamo\b|abbott/i,
  rxsight: /rxsight/i,
  bl_expired: /b\s*&\s*l|bausch/i,
  bl_opened: /b\s*&\s*l|bausch/i,
  rayner: /rayner/i,
};
// true — this lens is that vendor's; false — it is somebody else's;
// null — the catalog doesn't say who made it, so don't get in the way.
function lensFormVendorMatch(vendorKey, product) {
  const re = LENS_FORM_VENDOR_PATTERNS[vendorKey];
  const maker = String((product && product.manufacturer) || '').trim();
  if (!re || !maker) return null;
  return re.test(maker);
}

// A lens on the shelf → a row in whichever vendor's columns. The catalog
// already splits a lens into model and power, so nothing has to be guessed
// out of the description text.
function lensFormRowFromStock(vendorKey, product, lot) {
  const model = product.iolModel || product.description || '';
  const power = product.iolPower || '';
  const serial = (lot && lot.serial) || '';
  switch (vendorKey) {
    case 'jnj_expired': return { model, power, serial, lot: (lot && lot.lot) || '' };
    case 'rxsight': return { model: product.description || model, serial, expiry: (lot && lot.expiry) || '' };
    case 'bl_expired':
    case 'bl_opened': return { model, diopter: power, serial };
    case 'rayner': return { lot_serial: serial || (lot && lot.lot) || '', model_diopter: `${model} ${power}`.trim(), reason: '', qty: '1' };
    default: return { model, power, serial };
  }
}

function lensFormGenerate(vendorKey, data) {
  const cfg = LENS_RETURN_FORMS[vendorKey];
  if (!cfg) throw new Error('Unknown return form: ' + vendorKey);
  const { jsPDF } = window.jspdf;
  const doc = new jsPDF({ orientation: 'portrait', unit: 'pt', format: 'letter' });
  cfg.draw(doc, data);
  doc.save(`${vendorKey}_return_form_${(data.date || new Date().toISOString().slice(0, 10))}.pdf`);
}

window.SurgSuiteLensForms = { LENS_RETURN_FORMS, lensFormGenerate, lensFormRowFromStock, lensFormVendorMatch };
