/* global React, PORTAL */
const { useState, useEffect } = React;

const STATUS_META = {
  sent:     { label: 'Awaiting your response', color: '#60a5fa', bg: 'rgba(37,99,235,0.10)' },
  accepted: { label: 'Accepted',               color: 'var(--ok)', bg: 'rgba(5,150,105,0.10)' },
  rejected: { label: 'Rejected',               color: 'var(--danger)', bg: 'rgba(220,38,38,0.08)' },
  expired:  { label: 'Expired',                color: 'var(--fg-subtle)', bg: 'var(--night-elev-1)' },
};

function fmtEur(v) { return `€ ${Number(v||0).toLocaleString('nl-NL',{minimumFractionDigits:2,maximumFractionDigits:2})}`; }
function fmtDate(d) { return d ? new Date(d).toLocaleString('nl-NL',{day:'2-digit',month:'long',year:'numeric',hour:'2-digit',minute:'2-digit'}) : '—'; }

function StatusBadge({ status }) {
  const m = STATUS_META[status] || STATUS_META.expired;
  return <span style={{ padding: '3px 10px', borderRadius: 3, fontSize: 11, fontWeight: 600, fontFamily: 'var(--font-mono)', color: m.color, background: m.bg }}>{m.label}</span>;
}

function printProposal(p, session) {
  const lines = typeof p.lines === 'string' ? JSON.parse(p.lines) : (p.lines || []);
  const subtotal   = lines.reduce((s,l) => s + (Number(l.subtotal)||0), 0);
  const vat_amount = subtotal * 0.21;
  const total      = subtotal + vat_amount;
  const fmtN = v => Number(v||0).toLocaleString('nl-NL',{minimumFractionDigits:2,maximumFractionDigits:2});

  const linesHtml = lines.map(l => `<tr>
    <td style="padding:8px 0;border-bottom:1px solid #e8eaf0;font-size:9pt;">${l.description}</td>
    <td style="padding:8px 0;border-bottom:1px solid #e8eaf0;text-align:right;font-family:monospace;font-size:9pt;">${l.quantity}</td>
    <td style="padding:8px 0;border-bottom:1px solid #e8eaf0;text-align:right;font-family:monospace;font-size:9pt;">€ ${fmtN(l.unit_price)}</td>
    <td style="padding:8px 0;border-bottom:1px solid #e8eaf0;text-align:right;font-family:monospace;font-size:9pt;">€ ${fmtN(l.subtotal)}</td>
  </tr>`).join('');

  const accBlock = p.status === 'accepted' ? `
  <div style="margin-top:20px;padding:14px;background:#f0faf7;border:1pt solid #2d7a6a;border-radius:3px">
    <div style="font-size:9pt;font-weight:700;color:#0B1117;margin-bottom:8px">✓ Digitaal geaccepteerd</div>
    <div style="font-size:8pt;color:#444;line-height:1.7">
      Door: <strong>${session?.contact||'—'}</strong><br>
      Namens: <strong>${session?.company||'—'}</strong><br>
      Op: ${fmtDate(p.accepted_at)}<br>
      Rechtsgeldig onder Nederlands recht (eIDAS Art. 25)
    </div>
  </div>` : '';

  const w = window.open('', '_blank');
  w.document.write(`<!DOCTYPE html><html lang="nl"><head><meta charset="utf-8">
<title>Offerte ${p.proposal_number} — Lake-Project</title>
<style>@page{size:A4;margin:20mm 22mm 18mm 22mm}*{box-sizing:border-box}body{font-family:system-ui,-apple-system,sans-serif;font-size:9pt;color:#1a1a1a;margin:0;-webkit-print-color-adjust:exact;print-color-adjust:exact}
.dh{border-bottom:2pt solid #0B1117;padding-bottom:10px;margin-bottom:16px;display:flex;justify-content:space-between;align-items:flex-end}h1{font-size:14pt;margin:0;color:#0B1117}.sub{font-size:7pt;color:#555;font-family:monospace}.meta{font-size:7pt;font-family:monospace;color:#777;text-align:right;line-height:1.7}
h2{font-size:10pt;font-weight:700;margin:14px 0 6px}p{font-size:8.5pt;color:#444;line-height:1.65;margin:0 0 8px}
table{width:100%;border-collapse:collapse}th{text-align:left;font-size:7pt;font-family:monospace;letter-spacing:.1em;text-transform:uppercase;color:#777;padding:6px 0;border-bottom:1px solid #ccc}
.tr{text-align:right}.ft{margin-top:14px;font-size:6.5pt;color:#aaa;font-family:monospace;text-align:center;border-top:1px solid #eee;padding-top:8px}
.pb{display:block;margin-bottom:14px;padding:8px 18px;background:#0B1117;color:#6FE3D1;border:1px solid #6FE3D1;border-radius:3px;cursor:pointer}@media print{.pb{display:none}}</style>
</head><body>
<button class="pb" onclick="window.print()">Print / Opslaan als PDF (A4)</button>
<div class="dh">
<div><div class="sub">Lake Project · KvK 29816688 · BTW NL001170142B85 · Rotterdam</div><h1>Offerte ${p.proposal_number}</h1></div>
<div class="meta"><div>${p.proposal_number}</div><div>Aangemaakt: ${p.created_at?.slice(0,10)||''}</div>${p.valid_until?`<div>Geldig tot: ${p.valid_until}</div>`:''}</div>
</div>
<h2>${p.title}</h2>
${p.intro?`<p>${p.intro}</p>`:''}
<table style="margin:16px 0">
  <thead><tr><th>Omschrijving</th><th class="tr">Aantal</th><th class="tr">Prijs</th><th class="tr">Bedrag</th></tr></thead>
  <tbody>${linesHtml}</tbody>
</table>
<div style="text-align:right;margin:12px 0">
  <div style="font-size:8.5pt;color:#555;margin-bottom:3px">Subtotaal: € ${fmtN(subtotal)}</div>
  <div style="font-size:8.5pt;color:#555;margin-bottom:5px">BTW 21%: € ${fmtN(vat_amount)}</div>
  <div style="font-size:12pt;font-weight:700;color:#0B1117">Totaal: € ${fmtN(total)}</div>
</div>
${p.notes?`<p style="color:#777;font-size:8pt">${p.notes}</p>`:''}
${accBlock}
<div class="ft">Lake-Project · KvK 29816688 · BTW NL001170142B85 · hello@lake-project.com · lake-project.com/algemene-voorwaarden</div>
</body></html>`);
  w.document.close();
}

function ProposalCard({ p, session, onAccept, busy }) {
  const [expanded, setExpanded] = useState(false);
  const [confirmed, setConfirmed] = useState(false);
  const now = new Date().toISOString().slice(0,10);
  const status = (p.status === 'sent' && p.valid_until && p.valid_until < now) ? 'expired' : p.status;
  const lines = typeof p.lines === 'string' ? JSON.parse(p.lines||'[]') : (p.lines||[]);

  return (
    <div className="card" style={{ margin: '0 0 12px', maxWidth: 640 }}>
      <div style={{ padding: '14px 20px', display: 'flex', alignItems: 'flex-start', gap: 14, borderBottom: expanded ? '1px solid var(--border)' : 'none', cursor: 'pointer' }} onClick={() => setExpanded(e => !e)}>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4, flexWrap: 'wrap' }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--signal)' }}>{p.proposal_number}</span>
            <StatusBadge status={status} />
          </div>
          <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg)', marginBottom: 2 }}>{p.title}</div>
          <div style={{ fontSize: 12, color: 'var(--fg-subtle)', fontFamily: 'var(--font-mono)' }}>
            {fmtEur(p.total)} {p.valid_until ? `· geldig tot ${p.valid_until}` : ''}
          </div>
        </div>
        <span style={{ fontSize: 11, color: 'var(--fg-subtle)', paddingTop: 2 }}>{expanded ? '▾' : '▸'}</span>
      </div>

      {expanded && (
        <div style={{ padding: '16px 20px' }}>
          {p.intro && <p style={{ fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.7, marginBottom: 16 }}>{p.intro}</p>}

          {/* Line items */}
          <div style={{ marginBottom: 16 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 60px 90px 90px', gap: '4px 12px', marginBottom: 6 }}>
              {['Description','Qty','Unit price','Amount'].map(h => (
                <span key={h} style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--fg-subtle)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>{h}</span>
              ))}
            </div>
            {lines.map((l, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 60px 90px 90px', gap: '4px 12px', padding: '6px 0', borderBottom: '1px solid var(--border-hairline)' }}>
                <span style={{ fontSize: 13, color: 'var(--fg)' }}>{l.description}</span>
                <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--fg-muted)', textAlign: 'right' }}>{l.quantity}</span>
                <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--fg-muted)', textAlign: 'right' }}>{fmtEur(l.unit_price)}</span>
                <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--fg-muted)', textAlign: 'right' }}>{fmtEur(l.subtotal)}</span>
              </div>
            ))}
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 3, marginTop: 10 }}>
              <span style={{ fontSize: 12, color: 'var(--fg-subtle)' }}>Subtotaal <span style={{ fontFamily: 'var(--font-mono)', marginLeft: 12 }}>{fmtEur(p.subtotal)}</span></span>
              <span style={{ fontSize: 12, color: 'var(--fg-subtle)' }}>BTW 21% <span style={{ fontFamily: 'var(--font-mono)', marginLeft: 12 }}>{fmtEur(p.vat_amount)}</span></span>
              <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--signal)', fontFamily: 'var(--font-mono)' }}>{fmtEur(p.total)}</span>
            </div>
          </div>

          {/* Accepted state */}
          {status === 'accepted' && (
            <div style={{ padding: '12px 14px', background: 'rgba(5,150,105,0.08)', border: '1px solid rgba(5,150,105,0.25)', borderRadius: 4, marginBottom: 12 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ok)', marginBottom: 4 }}>✓ Accepted</div>
              <div style={{ fontSize: 12, color: 'var(--fg-muted)', fontFamily: 'var(--font-mono)' }}>{fmtDate(p.accepted_at)}</div>
            </div>
          )}

          {/* Accept flow */}
          {status === 'sent' && (
            <div style={{ borderTop: '1px solid var(--border)', paddingTop: 14, marginTop: 4 }}>
              {!confirmed ? (
                <button className="btn btn--primary" onClick={() => setConfirmed(true)}>
                  Accept this proposal
                </button>
              ) : (
                <div style={{ padding: 14, background: 'var(--abyss)', border: '1px solid var(--border)', borderRadius: 4 }}>
                  <div style={{ fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.65, marginBottom: 12 }}>
                    By accepting, you confirm that <strong style={{ color: 'var(--fg)' }}>{session?.company}</strong> agrees to this proposal and the attached Algemene Voorwaarden. Your acceptance is recorded with a timestamp.
                  </div>
                  <div style={{ display: 'flex', gap: 8 }}>
                    <button className="btn btn--ghost" onClick={() => setConfirmed(false)}>Cancel</button>
                    <button className="btn btn--primary" disabled={busy} onClick={() => onAccept(p.id)}>
                      {busy ? 'Processing…' : 'Confirm acceptance'}
                    </button>
                  </div>
                </div>
              )}
            </div>
          )}

          <div style={{ display: 'flex', gap: 8, marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--border-hairline)' }}>
            <button className="btn btn--ghost" onClick={() => printProposal(p, session)}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ marginRight: 4 }}>
                <polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/>
              </svg>
              Print / Save PDF
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function Proposals() {
  const [proposals, setProposals] = useState(undefined);
  const [session, setSession]     = useState({ company: '', contact: '' });
  const [busy, setBusy]           = useState(false);
  const [error, setError]         = useState('');

  useEffect(() => {
    PORTAL.get('/proposals').then(setProposals).catch(() => setProposals([]));
    Promise.all([
      PORTAL.get('/company').catch(() => ({})),
      PORTAL.get('/profile').catch(() => ({})),
    ]).then(([co, ct]) => setSession({ company: co?.name||'', contact: ct?.name||'' }));
  }, []);

  async function handleAccept(id) {
    setBusy(true); setError('');
    try {
      const updated = await PORTAL.post(`/proposals/${id}/accept`, {});
      setProposals(prev => prev.map(p => p.id === id ? { ...p, ...updated } : p));
    } catch(ex) {
      setError(ex?.error || 'Something went wrong. Please try again.');
    } finally { setBusy(false); }
  }

  if (proposals === undefined) {
    return <div style={{ padding: 24, color: 'var(--fg-subtle)', fontSize: 13 }}>Loading…</div>;
  }

  const now = new Date().toISOString().slice(0,10);
  const pending = proposals.filter(p => p.status === 'sent' && !(p.valid_until && p.valid_until < now));
  const others  = proposals.filter(p => !(p.status === 'sent' && !(p.valid_until && p.valid_until < now)));

  return (
    <div>
      <h1 className="page-title">Proposals</h1>
      <div className="page-subtitle">Offertes from Lake-Project</div>

      {error && (
        <div style={{ marginTop: 12, padding: '10px 14px', background: 'rgba(220,38,38,0.08)', border: '1px solid rgba(220,38,38,0.3)', borderRadius: 4, fontSize: 12, color: 'var(--danger)', maxWidth: 580 }}>
          {error}
        </div>
      )}

      {proposals.length === 0 ? (
        <div className="card" style={{ maxWidth: 480, marginTop: 20 }}>
          <div style={{ padding: 28, textAlign: 'center' }}>
            <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--fg)', marginBottom: 8 }}>No proposals yet</div>
            <div style={{ fontSize: 12, color: 'var(--fg-muted)', lineHeight: 1.65 }}>
              When Lake-Project sends you a proposal, it will appear here for your review and acceptance.
            </div>
          </div>
        </div>
      ) : (
        <div style={{ marginTop: 20 }}>
          {pending.length > 0 && (
            <div style={{ marginBottom: 24 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: '#60a5fa', flexShrink: 0 }}>Awaiting response</span>
                <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
              </div>
              {pending.map(p => <ProposalCard key={p.id} p={p} session={session} onAccept={handleAccept} busy={busy} />)}
            </div>
          )}

          {others.length > 0 && (
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--fg-subtle)', flexShrink: 0 }}>History</span>
                <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
              </div>
              {others.map(p => <ProposalCard key={p.id} p={p} session={session} onAccept={handleAccept} busy={busy} />)}
            </div>
          )}
        </div>
      )}

      <div style={{ fontSize: 11, color: 'var(--fg-faint)', fontFamily: 'var(--font-mono)', marginTop: 20, lineHeight: 1.6 }}>
        Questions? <a href="mailto:hello@lake-project.com" style={{ color: 'var(--signal)' }}>hello@lake-project.com</a>
      </div>
    </div>
  );
}
window.Proposals = Proposals;
