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

const newLine = () => ({ _key: Math.random(), description:'', quantity:1, unit_price:0, vat_rate:0.21 });

function TemplateModal({ tpl, companies, onSave, onClose }) {
  const isNew = !tpl?.id;
  const [form, setForm] = useState({ customer_id:'', description:'', frequency:'monthly', day_of_month:1, auto_send:0, ...(tpl||{}) });
  const [lines, setLines] = useState(tpl?.lines_json ? JSON.parse(tpl.lines_json) : [newLine()]);
  const [busy, setBusy]   = useState(false);
  const { toast } = useApp();
  const f = k => e => setForm(p => ({ ...p, [k]: e.target.type==='checkbox' ? (e.target.checked?1:0) : e.target.value }));

  async function save(e) {
    e.preventDefault(); setBusy(true);
    try {
      const body = { ...form, lines_json: JSON.stringify(lines) };
      isNew ? await API.post('/recurring', body) : await API.put(`/recurring/${tpl.id}`, body);
      toast(isNew ? 'Template created' : 'Template 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">{isNew ? 'New recurring template' : 'Edit template'}</span><button className="modal-close" onClick={onClose}>×</button></div>
        <form onSubmit={save}>
          <div className="modal-body">
            <div className="form-grid" style={{marginBottom:16}}>
              <div className="field field--full">
                <label className="field-label">Customer *</label>
                <select className="field-select" required value={form.customer_id} onChange={f('customer_id')}>
                  <option value="">— select —</option>
                  {companies.filter(c => c.type !== 'supplier').map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
              </div>
              <div className="field field--full">
                <label className="field-label">Template name</label>
                <input className="field-input" required value={form.description} onChange={f('description')} placeholder="e.g. Monthly retainer" />
              </div>
              <div className="field">
                <label className="field-label">Frequency</label>
                <select className="field-select" value={form.frequency} onChange={f('frequency')}>
                  <option value="monthly">Monthly</option>
                  <option value="quarterly">Quarterly</option>
                </select>
              </div>
              <div className="field">
                <label className="field-label">Day of month</label>
                <input className="field-input" type="number" min={1} max={28} value={form.day_of_month} onChange={f('day_of_month')} />
              </div>
              <div className="field field--full">
                <label style={{display:'flex',alignItems:'center',gap:8,cursor:'pointer'}}>
                  <input type="checkbox" checked={!!form.auto_send} onChange={f('auto_send')} />
                  <span className="field-label" style={{margin:0}}>Auto-send (no review)</span>
                </label>
              </div>
            </div>

            <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8}}>
              <span className="field-label">Line items</span>
              <button type="button" className="btn btn--ghost btn--sm" onClick={() => setLines(l => [...l, newLine()])}>+ Line</button>
            </div>
            <div className="line-items">
              <div className="line-item line-item-head">
                <div className="li-cell">Description</div><div className="li-cell">Qty</div>
                <div className="li-cell">Unit price</div><div className="li-cell">VAT</div><div className="li-cell"></div>
              </div>
              {lines.map((l, idx) => (
                <div key={l._key||idx} className="line-item">
                  <div className="li-cell"><input className="li-input" value={l.description} onChange={e => setLines(ls => ls.map((x,i) => i===idx?{...x,description:e.target.value}:x))} /></div>
                  <div className="li-cell"><input className="li-input mono" type="number" step="0.01" value={l.quantity} onChange={e => setLines(ls => ls.map((x,i) => i===idx?{...x,quantity:e.target.value}:x))} /></div>
                  <div className="li-cell"><input className="li-input mono" type="number" step="0.01" value={l.unit_price} onChange={e => setLines(ls => ls.map((x,i) => i===idx?{...x,unit_price:e.target.value}:x))} /></div>
                  <div className="li-cell">
                    <select className="li-input mono" value={l.vat_rate} onChange={e => setLines(ls => ls.map((x,i) => i===idx?{...x,vat_rate:e.target.value}:x))}>
                      <option value="0.21">21%</option><option value="0.09">9%</option><option value="0.00">0%</option>
                    </select>
                  </div>
                  <div className="li-cell"><span className="li-del" onClick={() => setLines(ls => ls.filter((_,i) => i!==idx))}>×</span></div>
                </div>
              ))}
            </div>
          </div>
          <div className="modal-foot">
            <button type="button" className="btn btn--ghost" onClick={onClose}>Cancel</button>
            <button type="submit" className="btn btn--primary" disabled={busy}>{busy?'Saving…':'Save template'}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function RecurringInvoices() {
  const [templates, setTemplates] = useState([]);
  const [companies, setCompanies] = useState([]);
  const [modal, setModal]         = useState(null);
  const { toast } = useApp();

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

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

  async function toggle(tpl) {
    await API.put(`/recurring/${tpl.id}`, { active: tpl.active ? 0 : 1 }).catch(e => toast(e.error || 'Error', 'error'));
    load();
  }

  async function del(tpl) {
    if (!confirm(`Delete template "${tpl.description}"?`)) return;
    await API.del(`/recurring/${tpl.id}`).catch(e => toast(e.error || 'Error', 'error'));
    load(); toast('Template deleted');
  }

  async function runNow(tpl) {
    if (!confirm(`Generate invoice for "${tpl.description}" now?`)) return;
    try {
      await API.post(`/recurring/${tpl.id}/run`, {});
      toast('Invoice drafted');
    } catch (e) { toast(e.error || 'Error', 'error'); }
  }

  const coMap = Object.fromEntries(companies.map(c => [c.id, c.name]));

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Recurring invoices</h1>
          <div className="page-subtitle">Templates auto-draft on schedule</div>
        </div>
        <div className="page-actions">
          <button className="btn btn--primary" onClick={() => setModal({})}>+ New template</button>
        </div>
      </div>

      <div className="card" style={{margin:0}}>
        <div className="table-wrap">
          <table className="data-table" style={{padding:'0 20px'}}>
            <thead><tr><th>Template</th><th>Customer</th><th>Frequency</th><th>Next run</th><th>Auto-send</th><th>Active</th><th></th></tr></thead>
            <tbody>
              {templates.length === 0 && <tr><td colSpan={7}><div className="empty-state">No recurring templates</div></td></tr>}
              {templates.map(tpl => (
                <tr key={tpl.id}>
                  <td style={{fontWeight:500}}>{tpl.description}</td>
                  <td>{coMap[tpl.customer_id] || '—'}</td>
                  <td><span className="badge">{tpl.frequency}</span></td>
                  <td className="mono">{tpl.next_run_at ? new Date(tpl.next_run_at).toLocaleDateString('nl-NL') : '—'}</td>
                  <td>{tpl.auto_send ? <span className="status status--sent">yes</span> : <span className="status status--draft">no</span>}</td>
                  <td>
                    <button className={`status ${tpl.active ? 'status--approved' : 'status--draft'}`} style={{cursor:'pointer',background:'none',border:'1px solid'}} onClick={() => toggle(tpl)}>
                      {tpl.active ? 'active' : 'paused'}
                    </button>
                  </td>
                  <td>
                    <div className="row-actions">
                      <button className="btn btn--ghost btn--sm" onClick={() => runNow(tpl)}>Run now</button>
                      <button className="btn btn--ghost btn--sm" onClick={() => setModal(tpl)}>Edit</button>
                      <button className="btn btn--danger btn--sm" onClick={() => del(tpl)}>Del</button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div className="card" style={{marginTop:16}}>
        <div className="card-body" style={{fontSize:12,color:'var(--fg-muted)',lineHeight:1.7}}>
          <span style={{fontFamily:'var(--font-mono)',fontSize:10,color:'var(--fg-subtle)',textTransform:'uppercase',letterSpacing:'0.1em'}}>Cron schedule</span><br/>
          Recurring invoices are triggered daily at 07:00 UTC by a Cloudflare Cron Trigger. If <span style={{fontFamily:'var(--font-mono)'}}>auto_send = false</span>, a draft is created for your review. If <span style={{fontFamily:'var(--font-mono)'}}>auto_send = true</span>, the invoice is sent directly to the customer billing contact via Resend.
        </div>
      </div>

      {modal !== null && (
        <TemplateModal tpl={modal.id ? modal : null} companies={companies} onSave={() => { load(); setModal(null); }} onClose={() => setModal(null)} />
      )}
    </div>
  );
}
window.RecurringInvoices = RecurringInvoices;
