// Printable Vendor Statement — A4 layout, opened from the settlement list. Uses print CSS to
// hide the rest of the app and print only the statement content.
const { useMemo: vpMemo } = React;

function VendorStatementPrint({ settlement, onClose }) {
  const s = settlement;
  const vendor = Store.byId('vendors', s.vendorId);
  const rows = s.purchaseRows || [];
  const t = vpMemo(function () { return window.vsCalcTotals(rows, { total: s.dieselDeduction || 0 }, s.deductions || []); }, [rows, s]);
  const royalty = (s.deductions || []).filter(function (d) { return d.type === 'Royalty Recovery'; }).reduce(function (a, d) { return a + (parseFloat(d.amount) || 0); }, 0);
  const advance = (s.deductions || []).filter(function (d) { return d.type === 'Advance'; }).reduce(function (a, d) { return a + (parseFloat(d.amount) || 0); }, 0);
  const adjustment = (s.deductions || []).filter(function (d) { return d.type === 'Adjustment'; }).reduce(function (a, d) { return a + (parseFloat(d.amount) || 0); }, 0);
  const otherDeds = (s.deductions || []).filter(function (d) { return !['Royalty Recovery', 'Advance', 'Adjustment'].includes(d.type); }).reduce(function (a, d) { return a + (parseFloat(d.amount) || 0); }, 0);

  function doPrint() { window.print(); }

  return (
    <div className="vs-print-overlay">
      <style>{`
        .vs-print-overlay { position:fixed; inset:0; background:#5B5B5B; z-index:20000; overflow:auto; padding:24px; }
        .vs-print-toolbar { max-width:800px; margin:0 auto 12px; display:flex; justify-content:flex-end; gap:8px; }
        .vs-print-area { max-width:800px; margin:0 auto; background:#fff; padding:40px; font-family:var(--font-b, Arial, sans-serif); color:#111; }
        .vs-hdr { display:none; }
        .vs-table { width:100%; border-collapse:collapse; font-size:11.5px; margin-bottom:16px; }
        .vs-table th { background:#F9FAFB; text-align:left; padding:6px 8px; font-size:10px; text-transform:uppercase; border:1px solid #E5E7EB; }
        .vs-table td { padding:6px 8px; border:1px solid #E5E7EB; }
        .vs-totals div { display:flex; justify-content:space-between; padding:4px 0; border-bottom:1px dashed #E5E7EB; font-size:12.5px; }
        @media print {
          body * { visibility:hidden; }
          .vs-print-area, .vs-print-area * { visibility:visible; }
          .vs-print-area { position:absolute; top:0; left:0; width:100%; padding:0; }
          .vs-print-toolbar { display:none; }
          .vs-print-overlay { position:static; background:#fff; padding:0; }
        }
      `}</style>
      <div className="vs-print-toolbar">
        <button className="btn btn-wh" onClick={onClose}>Close</button>
        <button className="btn btn-or" onClick={doPrint}>Print / Save PDF</button>
      </div>
      <div className="vs-print-area">
        <window.DocHeader
          companyId={s.paidThroughCompanyId || s.companyId}
          docTitle="Vendor Statement"
          docMeta={[
            ['Period', window.fmtDate(s.periodFrom) + ' – ' + window.fmtDate(s.periodTo)],
            ['Ref', (s.id || '').slice(0, 8).toUpperCase()],
            ['Status', s.status || '—'],
          ]}
        />

        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 18, fontSize: 12 }}>
          <div>
            <div style={{ fontWeight: 700, marginBottom: 3 }}>{vendor?.name || s.vendorName}</div>
            {vendor?.gst && <div>GST: {vendor.gst}</div>}
            {vendor?.address && <div style={{ maxWidth: 260 }}>{vendor.address}</div>}
            {vendor?.mobile && <div>Phone: {vendor.mobile}</div>}
          </div>
          <div style={{ textAlign: 'right' }}>
            <div>Status: <strong>{s.status}</strong></div>
            <div>Settlement Date: {s.settlementDate ? window.fmtDate(s.settlementDate) : '—'}</div>
          </div>
        </div>

        <table className="vs-table">
          <thead><tr><th>Date</th><th>Challan</th><th>Vehicle</th><th>Material</th><th style={{ textAlign: 'right' }}>Qty</th><th style={{ textAlign: 'right' }}>Rate</th><th style={{ textAlign: 'right' }}>Amount</th><th style={{ textAlign: 'right' }}>GST</th><th style={{ textAlign: 'right' }}>Total</th></tr></thead>
          <tbody>
            {rows.map(function (r, i) {
              return (
                <tr key={i}>
                  <td>{window.fmtDate(r.date)}</td>
                  <td>{r.challanNumber}</td>
                  <td>{r.vehicleFull}</td>
                  <td>{r.material}</td>
                  <td style={{ textAlign: 'right' }}>{window.formatQuantity(r.quantity)}</td>
                  <td style={{ textAlign: 'right' }}>{window.fmtCur(r.rate)}</td>
                  <td style={{ textAlign: 'right' }}>{window.fmtCur(r.amount)}</td>
                  <td style={{ textAlign: 'right' }}>{window.fmtCur(r.gstAmount)}</td>
                  <td style={{ textAlign: 'right', fontWeight: 600 }}>{window.fmtCur(r.amountWithGst)}</td>
                </tr>);

            })}
          </tbody>
        </table>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
          <div className="vs-totals">
            <div><span>Purchase Total</span><strong>{window.fmtCur(t.gross)}</strong></div>
            <div><span>Diesel Deduction{s.dieselCompanyName ? ' (' + s.dieselCompanyName + ')' : ''}</span><strong>{window.fmtCur(t.dsl)}</strong></div>
            <div><span>Royalty</span><strong>{window.fmtCur(royalty)}</strong></div>
            <div><span>Advance</span><strong>{window.fmtCur(advance)}</strong></div>
            <div><span>Adjustment</span><strong>{window.fmtCur(adjustment)}</strong></div>
            <div><span>Other Deductions</span><strong>{window.fmtCur(otherDeds)}</strong></div>
            <div style={{ borderTop: '2px solid #111', marginTop: 4, paddingTop: 6, fontWeight: 800, fontSize: 14 }}><span>Net Payable</span><span>{window.fmtCur(t.net)}</span></div>
          </div>
          <div className="vs-totals">
            <div style={{ fontWeight: 700, borderBottom: 'none', marginBottom: 2 }}><span>Payment Details</span><span></span></div>
            {(s.payments || []).length === 0 ? <div style={{ color: '#777', fontStyle: 'italic' }}>No payments recorded</div> : (s.payments || []).map(function (p, i) {
              return <div key={i}><span>{window.fmtDate(p.date)} · {p.mode}{p.reference ? ' · ' + p.reference : ''}</span><strong>{window.fmtCur(p.amount)}</strong></div>;
            })}
            <div style={{ borderTop: '1px solid #999', marginTop: 4, paddingTop: 6 }}><span>Amount Paid</span><strong>{window.fmtCur(s.amountPaid || 0)}</strong></div>
            <div style={{ fontWeight: 800 }}><span>Running Balance</span><span style={{ color: (s.outstandingBalance || 0) > 0 ? '#DC2626' : '#166534' }}>{window.fmtCur(s.outstandingBalance || 0)}</span></div>
            <div style={{ borderTop: '2px solid #111', marginTop: 4, paddingTop: 6, fontWeight: 800, fontSize: 14 }}><span>Grand Total</span><span>{window.fmtCur(t.gross)}</span></div>
          </div>
        </div>

        {(s.notes) && <div style={{ marginTop: 20, fontSize: 11, color: '#555' }}><strong>Notes:</strong> {s.notes}</div>}
        <div style={{ marginTop: 30, fontSize: 10, color: '#999', textAlign: 'center' }}>Generated {new Date().toLocaleDateString()} · OM Group ERP · This is a system-generated statement.</div>
      </div>
    </div>);

}

window.VendorStatementPrint = VendorStatementPrint;
