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

function Company() {
  const [co, setCo]     = useState(null);
  const [form, setForm] = useState(null);
  const [busy, setBusy] = useState(false);
  const [saved, setSaved] = useState(false);

  useEffect(() => {
    PORTAL.get('/company').then(d=>{ setCo(d); setForm(d); }).catch(()=>{});
  }, []);

  const f = k => e => setForm(p=>({...p,[k]:e.target.value}));

  async function save(e) {
    e.preventDefault(); setBusy(true); setSaved(false);
    await PORTAL.put('/company', form).catch(()=>{});
    setSaved(true); setBusy(false);
  }

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

  return (
    <div>
      <h1 className="page-title">Company settings</h1>
      <div className="page-subtitle">Billing address and invoice preferences</div>

      <div className="card" style={{maxWidth:560}}>
        <div className="card-head"><span className="card-title">{co.name}</span></div>
        <form onSubmit={save}>
          <div className="card-body">
            {saved && <div className="alert" style={{background:'rgba(82,183,136,0.1)',border:'1px solid var(--ok)',color:'var(--ok)',marginBottom:12}}>Saved successfully</div>}
            <div className="form-grid">
              <div className="field field--full">
                <label className="field-label">Street</label>
                <input className="field-input" value={form.address_street||''} onChange={f('address_street')} />
              </div>
              <div className="field">
                <label className="field-label">City</label>
                <input className="field-input" value={form.address_city||''} onChange={f('address_city')} />
              </div>
              <div className="field">
                <label className="field-label">Postcode</label>
                <input className="field-input" value={form.address_postcode||''} onChange={f('address_postcode')} />
              </div>
              <div className="field">
                <label className="field-label">Country</label>
                <input className="field-input" value={form.address_country||'NL'} onChange={f('address_country')} />
              </div>
              <div className="field field--full">
                <label className="field-label">Invoice delivery preference</label>
                <select className="field-select" value={form.invoice_delivery||'link'} onChange={f('invoice_delivery')}>
                  <option value="link">Portal link (receive email with link to portal)</option>
                  <option value="pdf">PDF attachment (invoice attached to email)</option>
                  <option value="both">Both (link + PDF attachment)</option>
                </select>
              </div>
            </div>

            <div style={{margin:'20px 0 12px',paddingTop:20,borderTop:'1px solid var(--border)',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
              <div style={{fontSize:11,fontFamily:'var(--font-mono)',color:'var(--fg-subtle)',textTransform:'uppercase',letterSpacing:'0.1em'}}>Invoice defaults</div>
              <button type="button" className="btn btn--ghost btn--sm" onClick={() => {
                const parts = [form.name, form.address_street, [form.address_postcode, form.address_city].filter(Boolean).join(' '), form.address_country && form.address_country !== 'NL' ? form.address_country : ''].filter(Boolean);
                setForm(p => ({ ...p, billing_address: parts.join('\n') }));
              }}>Build from address above</button>
            </div>
            <div className="form-grid">
              <div className="field field--full">
                <label className="field-label">Invoice address <span style={{fontSize:10,fontWeight:400,color:'var(--fg-subtle)'}}>printed on every invoice</span></label>
                <textarea className="field-textarea" rows={4} value={form.billing_address||''} onChange={f('billing_address')} placeholder={'Company name\nStreet address\nPostcode City\nBTW: NL...'} style={{fontFamily:'var(--font-mono)',fontSize:12}} />
              </div>
              <div className="field">
                <label className="field-label">Invoice email</label>
                <input className="field-input" type="email" value={form.billing_email_to||''} onChange={f('billing_email_to')} placeholder="billing@yourcompany.com" />
              </div>
              <div className="field">
                <label className="field-label">CC</label>
                <input className="field-input" value={form.billing_email_cc||''} onChange={f('billing_email_cc')} placeholder="Comma-separated" />
              </div>
              <div className="field">
                <label className="field-label">BCC</label>
                <input className="field-input" value={form.billing_email_bcc||''} onChange={f('billing_email_bcc')} placeholder="Comma-separated" />
              </div>
              <div className="field">
                <label className="field-label">PO number <span style={{fontSize:10,fontWeight:400,color:'var(--fg-subtle)'}}>your reference on invoices</span></label>
                <input className="field-input" value={form.billing_po_number||''} onChange={f('billing_po_number')} placeholder="e.g. PO-2026-001" />
              </div>
            </div>
          </div>
          <div style={{padding:'12px 20px',borderTop:'1px solid var(--border)',display:'flex',justifyContent:'flex-end'}}>
            <button type="submit" className="btn btn--primary" disabled={busy}>{busy?'Saving…':'Save changes'}</button>
          </div>
        </form>
      </div>
    </div>
  );
}
window.Company = Company;
