/* global React, API, useApp */
const { useState, useEffect, useCallback } = React;
const fmtEur = v => `€${Math.abs(Number(v)).toLocaleString('nl-NL',{minimumFractionDigits:2,maximumFractionDigits:2})}`;

function CreditNotes() {
  const [notes, setNotes]   = useState([]);
  const [detail, setDetail] = useState(null);
  const { toast } = useApp();

  const load = useCallback(() => { API.get('/credit-notes').then(setNotes).catch(()=>{}); }, []);
  useEffect(() => { load(); }, [load]);

  async function send(cn) {
    if (!confirm(`Send credit note ${cn.credit_number} to customer?\nThis will also generate a PDF and attach it.`)) return;
    await API.post(`/credit-notes/${cn.id}/send`, {}).catch(e => toast(e.error||'Error','error'));
    toast('Credit note sent'); load();
    if (detail?.id === cn.id) setDetail(d => ({ ...d, status:'sent' }));
  }

  async function del(cn) {
    if (!confirm(`Delete draft credit note ${cn.credit_number}?`)) return;
    await API.del(`/credit-notes/${cn.id}`).catch(e=>toast(e.error||'Error','error'));
    toast('Deleted'); load(); if (detail?.id===cn.id) setDetail(null);
  }

  async function openDetail(cn) {
    const d = await API.get(`/credit-notes/${cn.id}`).catch(()=>null);
    setDetail(d);
  }

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Credit notes</h1>
          <div className="page-subtitle">Invoice reversals and dispute resolutions</div>
        </div>
      </div>

      <div style={{display:'grid',gridTemplateColumns:detail?'1fr 380px':'1fr',gap:16}}>
        <div className="card" style={{margin:0}}>
          <div className="table-wrap">
            <table className="data-table" style={{padding:'0 20px'}}>
              <thead><tr><th>Credit note</th><th>Original invoice</th><th>Customer</th><th>Date</th><th style={{textAlign:'right'}}>Total</th><th>Status</th><th></th></tr></thead>
              <tbody>
                {notes.length===0 && <tr><td colSpan={7}><div className="empty-state">No credit notes yet</div></td></tr>}
                {notes.map(cn=>(
                  <tr key={cn.id} style={{cursor:'pointer'}} onClick={()=>openDetail(cn)}>
                    <td className="mono" style={{fontWeight:500}}>{cn.credit_number}</td>
                    <td className="mono" style={{fontSize:11,color:'var(--fg-muted)'}}>{cn.original_invoice_number||'—'}</td>
                    <td>{cn.company_name}</td>
                    <td className="mono" style={{fontSize:11}}>{cn.issued_date}</td>
                    <td className="mono" style={{textAlign:'right',color:'var(--danger)'}}>−{fmtEur(cn.total)}</td>
                    <td><span className={`status ${cn.status==='sent'?'status--sent':'status--draft'}`}>{cn.status}</span></td>
                    <td><div className="row-actions" onClick={e=>e.stopPropagation()}>
                      {cn.status==='draft' && <button className="btn btn--primary btn--sm" onClick={()=>send(cn)}>Send</button>}
                      {cn.status==='draft' && <button className="btn btn--danger btn--sm" onClick={()=>del(cn)}>Del</button>}
                      {cn.pdf_r2_key && <a href={`/api/credit-notes/${cn.id}/pdf`} className="btn btn--ghost btn--sm" target="_blank" rel="noreferrer">PDF</a>}
                    </div></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {detail && (
          <div className="card" style={{margin:0}}>
            <div className="card-head">
              <span className="card-title">{detail.credit_number}</span>
              <button className="btn btn--ghost btn--sm" onClick={()=>setDetail(null)}>×</button>
            </div>
            <div style={{padding:'12px 20px'}}>
              <table style={{fontSize:12,borderCollapse:'collapse',width:'100%',marginBottom:12}}>
                <tbody>
                  <tr><td style={{color:'var(--fg-subtle)',paddingRight:16,paddingBottom:4}}>Customer</td><td>{detail.company_name}</td></tr>
                  <tr><td style={{color:'var(--fg-subtle)',paddingBottom:4}}>Original invoice</td><td className="mono">{detail.original_invoice_number||'—'}</td></tr>
                  <tr><td style={{color:'var(--fg-subtle)',paddingBottom:4}}>Issued</td><td className="mono">{detail.issued_date}</td></tr>
                  <tr><td style={{color:'var(--fg-subtle)',paddingBottom:4}}>Status</td><td><span className={`status ${detail.status==='sent'?'status--sent':'status--draft'}`}>{detail.status}</span></td></tr>
                </tbody>
              </table>
              {detail.notes && <div style={{fontSize:12,color:'var(--fg-muted)',marginBottom:12,padding:8,background:'var(--bg-raised)',borderRadius:4}}>{detail.notes}</div>}
              <div style={{fontSize:10,fontFamily:'var(--font-mono)',textTransform:'uppercase',letterSpacing:'0.08em',color:'var(--fg-subtle)',marginBottom:6}}>Lines (negated)</div>
              {(detail.lines||[]).map((l,i)=>(
                <div key={i} style={{display:'flex',justifyContent:'space-between',fontSize:12,padding:'5px 0',borderBottom:'1px solid var(--border)'}}>
                  <span style={{color:'var(--fg-muted)'}}>{l.description}</span>
                  <span className="mono" style={{color:'var(--danger)'}}>−{fmtEur(l.subtotal)}</span>
                </div>
              ))}
              <div style={{textAlign:'right',marginTop:12}}>
                <div style={{fontSize:11,color:'var(--fg-subtle)'}}>Subtotal: −{fmtEur(detail.subtotal)}</div>
                <div style={{fontSize:11,color:'var(--fg-subtle)'}}>BTW: −{fmtEur(detail.vat_amount)}</div>
                <div style={{fontSize:16,fontWeight:700,fontFamily:'var(--font-mono)',color:'var(--danger)',marginTop:4}}>−{fmtEur(detail.total)}</div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
window.CreditNotes = CreditNotes;
