/* global React, API, useApp */
const { useState, useEffect, useCallback, useRef } = React;

const fmtEur    = v => v == null ? '—' : `€${Number(v).toLocaleString('nl-NL', { minimumFractionDigits:2, maximumFractionDigits:2 })}`;
const fmtDate   = v => v ? new Date(v).toLocaleDateString('nl-NL') : '—';
const fmtAmount = (v, cur) => v == null ? '—' : `${cur === 'EUR' ? '€' : ''}${Number(v).toLocaleString('nl-NL', { minimumFractionDigits:2, maximumFractionDigits:2 })}${cur && cur !== 'EUR' ? ' ' + cur : ''}`;

function ReviewModal({ invoice, companies, onSave, onClose }) {
  const [form, setForm] = useState({
    supplier_id:    invoice.supplier_id || '',
    invoice_number: invoice.invoice_number || '',
    invoice_date:   invoice.invoice_date || '',
    due_date:       invoice.due_date || '',
    subtotal:       invoice.subtotal || '',
    vat_rate:       invoice.vat_rate || 0.21,
    vat_amount:     invoice.vat_amount || '',
    total:          invoice.total || '',
    currency:       invoice.currency || 'EUR',
    notes:          invoice.notes || '',
    status:         invoice.status,
    // read-only computed fields (shown, not submitted)
    amount_eur:     invoice.amount_eur,
    vat_eur:        invoice.vat_eur,
    exchange_rate:  invoice.exchange_rate,
    reverse_charge: invoice.reverse_charge,
  });
  const [extracting, setExtracting] = useState(false);
  const [busy, setBusy]             = useState(false);
  const { toast } = useApp();
  const f = k => e => setForm(p => ({ ...p, [k]: e.target.value }));

  async function extract() {
    setExtracting(true);
    try {
      const result = await API.post(`/inbound/extract`, { id: invoice.id });
      setForm(p => ({ ...p, ...result }));
      toast('AI extraction complete' + (result.reverse_charge ? ' — reverse charge detected' : ''));
    } catch (e) { toast(e.error || 'Extraction failed', 'error'); }
    finally { setExtracting(false); }
  }

  async function save(status) {
    setBusy(true);
    try {
      await API.put(`/inbound/${invoice.id}`, { ...form, status: status || form.status });
      toast('Invoice updated'); onSave();
    } catch (e) { toast(e.error || 'Error', 'error'); }
    finally { setBusy(false); }
  }

  return (
    <div className="modal-overlay" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="modal modal--lg">
        <div className="modal-head">
          <span className="modal-title">Review inbound invoice</span>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>
        <div className="modal-body">
          {invoice.file_r2_key && (
            <div style={{marginBottom:16}}>
              <a className="btn btn--ghost btn--sm" href={`/api/upload?key=${encodeURIComponent(invoice.file_r2_key)}`} target="_blank">View PDF ↗</a>
              <button className="btn btn--ghost btn--sm" style={{marginLeft:8}} onClick={extract} disabled={extracting}>
                {extracting ? '⟳ Extracting…' : '✦ AI extract'}
              </button>
              {invoice.ai_extracted ? <span style={{marginLeft:8,fontSize:10,fontFamily:'var(--font-mono)',color:'var(--signal)'}}>AI-filled</span> : null}
            </div>
          )}
          {/* Currency / reverse charge info bar */}
          {form.currency && form.currency !== 'EUR' && (
            <div style={{display:'flex',gap:8,alignItems:'center',padding:'8px 12px',background:'rgba(111,227,209,0.07)',borderRadius:6,marginBottom:16,fontSize:12,fontFamily:'var(--font-mono)'}}>
              <span style={{color:'var(--signal)'}}>
                {form.currency} invoice
                {form.exchange_rate && form.exchange_rate !== 1 ? ` · 1 ${form.currency} = €${Number(form.exchange_rate).toFixed(4)}` : ''}
              </span>
              {form.amount_eur != null && <span style={{color:'var(--fg-subtle)'}}>· subtotal {fmtEur(form.amount_eur)} EUR</span>}
              {form.reverse_charge ? (
                <span style={{marginLeft:'auto',color:'var(--ember)',fontWeight:600}}>BTW VERLEGD · {fmtEur(form.vat_eur)} self-assessed @ 21%</span>
              ) : null}
            </div>
          )}
          <div className="form-grid">
            <div className="field field--full">
              <label className="field-label">Supplier</label>
              <select className="field-select" value={form.supplier_id} onChange={f('supplier_id')}>
                <option value="">— unmatched —</option>
                {companies.filter(c => c.type !== 'customer').map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>
            <div className="field">
              <label className="field-label">Invoice number</label>
              <input className="field-input" value={form.invoice_number} onChange={f('invoice_number')} />
            </div>
            <div className="field">
              <label className="field-label">Currency</label>
              <select className="field-select" value={form.currency} onChange={f('currency')}>
                {['EUR','USD','GBP','CHF','SEK','NOK','DKK'].map(c => <option key={c} value={c}>{c}</option>)}
              </select>
            </div>
            <div className="field">
              <label className="field-label">Invoice date</label>
              <input className="field-input" type="date" value={form.invoice_date} onChange={f('invoice_date')} />
            </div>
            <div className="field">
              <label className="field-label">Due date</label>
              <input className="field-input" type="date" value={form.due_date} onChange={f('due_date')} />
            </div>
            <div className="field">
              <label className="field-label">Subtotal (excl. BTW, orig. currency)</label>
              <input className="field-input" type="number" step="0.01" value={form.subtotal} onChange={f('subtotal')} />
            </div>
            <div className="field">
              <label className="field-label">VAT rate</label>
              <select className="field-select" value={form.vat_rate} onChange={f('vat_rate')}>
                <option value="0.21">21%</option><option value="0.09">9%</option><option value="0.00">0% / reverse charge</option>
              </select>
            </div>
            <div className="field">
              <label className="field-label">VAT amount (orig. currency)</label>
              <input className="field-input" type="number" step="0.01" value={form.vat_amount} onChange={f('vat_amount')} />
            </div>
            <div className="field">
              <label className="field-label">Total (incl. BTW, orig. currency)</label>
              <input className="field-input" type="number" step="0.01" value={form.total} onChange={f('total')} />
            </div>
            <div className="field field--full">
              <label className="field-label">Notes</label>
              <textarea className="field-textarea" rows={2} value={form.notes} onChange={f('notes')} />
            </div>
          </div>
        </div>
        <div className="modal-foot">
          <button type="button" className="btn btn--ghost" onClick={onClose}>Cancel</button>
          <button type="button" className="btn btn--ghost" disabled={busy} onClick={() => save('approved')}>Approve</button>
          <button type="button" className="btn btn--ghost" disabled={busy} onClick={() => save('paid')}>Mark paid</button>
          <button type="button" className="btn btn--primary" disabled={busy} onClick={() => save()}>Save</button>
        </div>
      </div>
    </div>
  );
}

function InboundInvoices() {
  const [invoices, setInvoices]   = useState([]);
  const [companies, setCompanies] = useState([]);
  const [filter, setFilter]       = useState('all');
  const [modal, setModal]         = useState(null);
  const [uploading, setUploading] = useState(false);
  const [drag, setDrag]           = useState(false);
  const dropRef = useRef(null);
  const { toast } = useApp();

  const load = useCallback(() => {
    API.get('/inbound').then(setInvoices).catch(() => {});
  }, []);

  useEffect(() => {
    load();
    API.get('/companies').then(setCompanies).catch(() => {});
  }, [load]);

  async function uploadFile(file) {
    if (!file || !file.type.includes('pdf')) { toast('PDF files only', 'error'); return; }
    setUploading(true);
    try {
      const form = new FormData();
      form.append('file', file);
      form.append('source', 'upload');
      await API.upload('/inbound', form);
      toast('Invoice uploaded — open to review');
      load();
    } catch (e) { toast(e.error || 'Upload failed', 'error'); }
    finally { setUploading(false); }
  }

  function onDrop(e) {
    e.preventDefault(); setDrag(false);
    uploadFile(e.dataTransfer.files[0]);
  }

  async function del(inv) {
    if (!confirm('Delete this invoice?')) return;
    await API.del(`/inbound/${inv.id}`).catch(e => toast(e.error || 'Error', 'error'));
    toast('Invoice deleted'); load();
  }

  const visible = invoices.filter(i => filter === 'all' || i.status === filter);
  const coMap   = Object.fromEntries(companies.map(c => [c.id, c.name]));

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Invoices — inbound</h1>
          <div className="page-subtitle">Supplier invoices · inbox: invoices@lake-project.com</div>
        </div>
      </div>

      <div
        ref={dropRef}
        className={`dropzone ${drag ? 'drag-over' : ''}`}
        style={{marginBottom:24}}
        onClick={() => { const inp = document.createElement('input'); inp.type='file'; inp.accept='.pdf'; inp.onchange = e => uploadFile(e.target.files[0]); inp.click(); }}
        onDragOver={e => { e.preventDefault(); setDrag(true); }}
        onDragLeave={() => setDrag(false)}
        onDrop={onDrop}
      >
        <div className="dropzone-icon">{uploading ? '⟳' : '↑'}</div>
        <div className="dropzone-text">{uploading ? 'Uploading…' : 'Drop a PDF here, or click to upload'}</div>
        <div className="dropzone-hint">Alternatively, forward supplier invoices to invoices@lake-project.com</div>
      </div>

      <div className="tabs">
        {[['all','All'],['pending','Pending'],['approved','Approved'],['paid','Paid']].map(([v,l]) => (
          <button key={v} className={`tab ${filter===v?'is-active':''}`} onClick={() => setFilter(v)}>{l}</button>
        ))}
      </div>

      <div className="card" style={{margin:0}}>
        <div className="table-wrap">
          <table className="data-table" style={{padding:'0 20px'}}>
            <thead><tr><th>Supplier</th><th>Invoice #</th><th>Date</th><th>Amount</th><th>EUR equiv.</th><th>Source</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {visible.length === 0 && <tr><td colSpan={8}><div className="empty-state">No inbound invoices</div></td></tr>}
              {visible.map(inv => (
                <tr key={inv.id} style={{cursor:'pointer'}} onClick={() => setModal(inv)}>
                  <td>{inv.supplier_id ? (coMap[inv.supplier_id] || '—') : <span className="muted">Unmatched</span>}</td>
                  <td className="mono">{inv.invoice_number || <span className="muted">—</span>}</td>
                  <td className="mono">{fmtDate(inv.invoice_date)}</td>
                  <td className="mono">
                    {fmtAmount(inv.total, inv.currency)}
                    {inv.reverse_charge ? <span title="BTW verlegd" style={{marginLeft:4,color:'var(--ember)',fontSize:10,fontFamily:'var(--font-mono)'}}>RC</span> : null}
                  </td>
                  <td className="mono" style={{color:'var(--fg-subtle)'}}>
                    {inv.currency !== 'EUR' && inv.amount_eur ? fmtEur(inv.amount_eur) : '—'}
                  </td>
                  <td><span className="badge">{inv.source}</span></td>
                  <td><span className={`status status--${inv.status}`}>{inv.status}</span></td>
                  <td>
                    <div className="row-actions" onClick={e => e.stopPropagation()}>
                      <button className="btn btn--ghost btn--sm" onClick={() => setModal(inv)}>Review</button>
                      <button className="btn btn--danger btn--sm" onClick={() => del(inv)}>Del</button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {modal && (
        <ReviewModal
          invoice={modal}
          companies={companies}
          onSave={() => { load(); setModal(null); }}
          onClose={() => setModal(null)}
        />
      )}
    </div>
  );
}
window.InboundInvoices = InboundInvoices;
