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

const fmtEur = v => v == null ? '—' : `€${Number(v).toLocaleString('nl-NL',{minimumFractionDigits:2,maximumFractionDigits:2})}`;
const fmtPct = v => `${(Number(v)*100).toFixed(1)}%`;

function CheckItem({ ok, label, sub }) {
  const color = ok ? 'var(--signal)' : 'var(--ember)';
  return (
    <div style={{display:'flex',alignItems:'flex-start',gap:10,padding:'10px 0',borderBottom:'1px solid var(--border)'}}>
      <span style={{fontSize:16,color,flexShrink:0,marginTop:1}}>{ok ? '✓' : '!'}</span>
      <div>
        <div style={{fontSize:13,color: ok?'var(--fg)':'var(--ember)'}}>{label}</div>
        {sub && <div style={{fontSize:11,fontFamily:'var(--font-mono)',color:'var(--fg-subtle)',marginTop:2}}>{sub}</div>}
      </div>
    </div>
  );
}

function TaxRow({ label, value, deduct, bold, indent }) {
  return (
    <div style={{
      display:'flex', justifyContent:'space-between', alignItems:'center',
      padding:'8px 0', borderBottom:'1px solid var(--border)',
      paddingLeft: indent ? 24 : 0,
      fontWeight: bold ? 600 : 400,
    }}>
      <span style={{fontSize:13, color: deduct?'var(--fg-subtle)':'var(--fg)'}}>{deduct?'— ':''}{label}</span>
      <span style={{fontFamily:'var(--font-mono)', fontSize:13, color: deduct?'var(--fg-subtle)':'var(--fg)'}}>{fmtEur(value)}</span>
    </div>
  );
}

function IBPrep() {
  const currentYear = new Date().getFullYear();
  const [year, setYear] = useState(currentYear.toString());
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const { toast } = useApp();

  useEffect(() => {
    setLoading(true);
    API.get(`/ibprep?year=${year}`)
      .then(setData)
      .catch(() => toast('Could not load IB data', 'error'))
      .finally(() => setLoading(false));
  }, [year]);

  const years = Array.from({length:4}, (_,i) => (currentYear - i).toString());

  if (!data && loading) return (
    <div className="page"><div className="page-header"><div><h1 className="page-title">IB Preparation</h1></div></div>
      <div className="empty-state" style={{marginTop:48}}>Loading…</div></div>
  );

  if (!data) return null;

  const { revenue, costs, net_profit, hours_worked, urencriterium, zelfstandigenaftrek,
          mkb_winstvrijstelling, taxable_income, ib_estimate, checklist } = data;

  const allClear = checklist.open_outbound_invoices === 0 &&
                   checklist.pending_inbound_invoices === 0 &&
                   checklist.unreconciled_transactions === 0;

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">IB Preparation</h1>
          <div className="page-subtitle">Inkomstenbelasting · annual tax overview · {year}</div>
        </div>
        <div className="page-actions">
          <select className="field-select" style={{fontSize:12,padding:'4px 8px'}} value={year} onChange={e => setYear(e.target.value)}>
            {years.map(y => <option key={y} value={y}>{y}</option>)}
          </select>
        </div>
      </div>

      {/* Year-end checklist */}
      <div className="card" style={{marginBottom:24}}>
        <div className="card-head">
          <span className="card-title">Year-end checklist</span>
          {allClear && <span style={{fontSize:11,fontFamily:'var(--font-mono)',color:'var(--signal)'}}>All clear — ready for submission</span>}
        </div>
        <div style={{padding:'0 20px 8px'}}>
          <CheckItem
            ok={checklist.open_outbound_invoices === 0}
            label="All outbound invoices collected"
            sub={checklist.open_outbound_invoices > 0 ? `${checklist.open_outbound_invoices} invoice(s) still open/overdue` : `No open invoices`}
          />
          <CheckItem
            ok={checklist.pending_inbound_invoices === 0}
            label="All inbound invoices reviewed and approved"
            sub={checklist.pending_inbound_invoices > 0 ? `${checklist.pending_inbound_invoices} invoice(s) still pending review` : `All approved or paid`}
          />
          <CheckItem
            ok={checklist.unreconciled_transactions === 0}
            label="Bank reconciliation complete"
            sub={checklist.unreconciled_transactions > 0 ? `${checklist.unreconciled_transactions} unmatched bank transaction(s)` : `All transactions matched`}
          />
          <CheckItem
            ok={urencriterium.met}
            label={`Urencriterium — ${Math.round(hours_worked)} hours worked`}
            sub={urencriterium.met
              ? `≥ ${urencriterium.threshold} hours met — zelfstandigenaftrek applies`
              : `${urencriterium.threshold - Math.round(hours_worked)} hours short — zelfstandigenaftrek NOT applicable`}
          />
          <CheckItem
            ok={true}
            label="BTW aangiften filed quarterly"
            sub="Verify in the Belastingdienst portal for all quarters"
          />
        </div>
      </div>

      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16}}>

        {/* Tax calculation */}
        <div className="card">
          <div className="card-head"><span className="card-title">Fiscale berekening {year}</span></div>
          <div style={{padding:'0 20px 16px'}}>
            <TaxRow label="Revenue (omzet)" value={revenue} bold />
            <TaxRow label="Total costs (aftrekbare kosten)" value={costs} deduct />
            <TaxRow label="Net profit (winst)" value={net_profit} bold />
            {zelfstandigenaftrek > 0 && <TaxRow label="Zelfstandigenaftrek" value={zelfstandigenaftrek} deduct indent />}
            {mkb_winstvrijstelling > 0 && <TaxRow label="MKB-winstvrijstelling (14%)" value={mkb_winstvrijstelling} deduct indent />}
            <TaxRow label="Belastbaar inkomen" value={taxable_income} bold />
            <TaxRow label="Geschatte IB (indicatief)" value={ib_estimate} bold />
          </div>
        </div>

        {/* Urencriterium + notes */}
        <div className="card">
          <div className="card-head"><span className="card-title">Ondernemersaftrek {year}</span></div>
          <div style={{padding:'0 20px 16px'}}>
            <div style={{padding:'10px 0',borderBottom:'1px solid var(--border)'}}>
              <div style={{display:'flex',justifyContent:'space-between',fontSize:13,marginBottom:4}}>
                <span>Hours worked</span>
                <span style={{fontFamily:'var(--font-mono)',fontWeight:600}}>{Math.round(hours_worked)} h</span>
              </div>
              <div style={{height:6,background:'var(--border)',borderRadius:3}}>
                <div style={{
                  height:'100%',
                  width:`${Math.min(100, hours_worked / urencriterium.threshold * 100)}%`,
                  background: urencriterium.met ? 'var(--signal)' : 'var(--ember)',
                  borderRadius:3,
                  transition:'width 0.4s',
                }} />
              </div>
              <div style={{fontSize:11,fontFamily:'var(--font-mono)',color:'var(--fg-subtle)',marginTop:4}}>
                {urencriterium.met ? '✓ ' : ''}
                {Math.round(hours_worked)} / {urencriterium.threshold} h urencriterium
              </div>
            </div>
            <div style={{padding:'12px 0',fontSize:12,color:'var(--fg-subtle)'}}>
              <p style={{marginBottom:8}}>
                <strong style={{color:'var(--fg)'}}>Zelfstandigenaftrek</strong> — {fmtEur(zelfstandigenaftrek)}<br/>
                Fixed deduction for entrepreneurs meeting the urencriterium. Phased down annually.
              </p>
              <p style={{marginBottom:8}}>
                <strong style={{color:'var(--fg)'}}>MKB-winstvrijstelling</strong> — 14%<br/>
                Applied on profit after zelfstandigenaftrek. No urencriterium required.
              </p>
              <p style={{fontSize:11,color:'var(--fg-subtle)',fontStyle:'italic'}}>
                ⚠ Estimates only — consult your tax advisor before filing.
                IB rates and deductions change annually.
              </p>
            </div>
          </div>
        </div>

      </div>
    </div>
  );
}
window.IBPrep = IBPrep;
