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

const EMPTY_CO = { name:'', kvk:'', btw_number:'', type:'customer', approved:1, address_street:'', address_city:'', address_postcode:'', address_country:'NL', pay_address_street:'', pay_address_city:'', pay_address_postcode:'', pay_address_country:'', payment_terms_days:30, notes:'', default_cost_category:'', default_payment_method_id:'', default_business_pct:'', sector:'', invoice_delivery:'link' };

const CO_SECTORS = [
  { value:'', label:'— none —' },
  { value:'energy', label:'Energy' },
  { value:'transport', label:'Transport' },
  { value:'banking', label:'Banking / Financial' },
  { value:'health', label:'Healthcare' },
  { value:'water', label:'Water / Waste water' },
  { value:'digital_infra', label:'Digital infrastructure' },
  { value:'public_admin', label:'Public administration' },
];

const COST_CATS_R = ['hosting','software','professional','travel','office','marketing','hardware','subscriptions','other'];
const COST_CAT_LABEL_R = { hosting:'Hosting', software:'Software', professional:'Professional services', travel:'Travel', office:'Office', marketing:'Marketing', hardware:'Hardware', subscriptions:'Subscriptions', other:'Other' };
const EMPTY_CT = { name:'', email:'', phone:'', role:'', is_primary:0 };

function CompanyModal({ company, onSave, onClose, defaultApproved, paymentMethods }) {
  const [form, setForm] = useState({ ...EMPTY_CO, ...(company || {}), approved: company ? (company.approved ?? 1) : (defaultApproved ?? 1) });
  const [rate, setRate] = useState({ hourly_rate:'', day_rate:'', currency:'EUR', default_vat_rate:0.21, notes:'' });
  const [busy, setBusy] = useState(false);
  const { toast } = useApp();

  useEffect(() => {
    if (company?.id) {
      API.get(`/companies/${company.id}/rate`).then(setRate).catch(() => {});
    }
  }, [company]);

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

  async function save(e) {
    e.preventDefault(); setBusy(true);
    try {
      const co = company?.id
        ? await API.put(`/companies/${company.id}`, form)
        : await API.post('/companies', form);
      if (form.type === 'customer' || form.type === 'both') {
        await API.put(`/companies/${co.id}/rate`, rate).catch(() => {});
      }
      toast(company ? 'Company updated' : 'Company created');
      onSave(co);
    } catch (e) { toast(e.error || 'Error saving', '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">{company ? 'Edit company' : 'New company'}</span>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>
        <form onSubmit={save} style={{display:'flex',flexDirection:'column',flex:1,minHeight:0,overflow:'hidden'}}>
          <div className="modal-body">
            <div className="form-grid" style={{marginBottom:20}}>
              <div className="field field--full">
                <label className="field-label">Company name *</label>
                <input className="field-input" required value={form.name} onChange={f('name')} />
              </div>
              <div className="field">
                <label className="field-label">Type</label>
                <select className="field-select" value={form.type} onChange={f('type')}>
                  <option value="customer">Customer</option>
                  <option value="supplier">Supplier</option>
                  <option value="both">Both</option>
                </select>
              </div>
              <div className="field">
                <label className="field-label">KvK number</label>
                <input className="field-input" value={form.kvk} onChange={f('kvk')} />
              </div>
              <div className="field">
                <label className="field-label">BTW / VAT number</label>
                <input className="field-input" value={form.btw_number} onChange={f('btw_number')} placeholder="NL000000000B01" />
              </div>
              <div className="field">
                <label className="field-label">Payment terms (days)</label>
                <input className="field-input" type="number" value={form.payment_terms_days} onChange={f('payment_terms_days')} />
              </div>
              <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} onChange={f('address_country')} />
              </div>
              <div className="field field--full">
                <label className="field-label">Notes</label>
                <textarea className="field-textarea" value={form.notes} onChange={f('notes')} rows={2} />
              </div>
              <div className="field">
                <label className="field-label">Sector <span style={{fontSize:10,fontWeight:400,color:'var(--fg-subtle)'}}>used for compliance</span></label>
                <select className="field-select" value={form.sector || ''} onChange={f('sector')}>
                  {CO_SECTORS.map(s => <option key={s.value} value={s.value}>{s.label}</option>)}
                </select>
              </div>
              <div className="field">
                <label className="field-label">Invoice delivery <span style={{fontSize:10,fontWeight:400,color:'var(--fg-subtle)'}}>portal preference</span></label>
                <select className="field-select" value={form.invoice_delivery || 'link'} onChange={f('invoice_delivery')}>
                  <option value="link">Portal link (default)</option>
                  <option value="pdf">PDF attachment</option>
                  <option value="both">Both</option>
                </select>
              </div>
            </div>

            {/* Supplier defaults */}
            {(form.type === 'supplier' || form.type === 'both') && (
              <div className="field">
                <label className="field-label">Default cost category</label>
                <select className="field-select" value={form.default_cost_category || ''} onChange={f('default_cost_category')}>
                  <option value="">— none —</option>
                  {COST_CATS_R.map(c => <option key={c} value={c}>{COST_CAT_LABEL_R[c]}</option>)}
                </select>
              </div>
            )}
            {(form.type === 'supplier' || form.type === 'both') && (
              <div className="field">
                <label className="field-label">Default business use %</label>
                <input className="field-input" type="number" min="0" max="100"
                  placeholder="e.g. 100 or 50"
                  value={form.default_business_pct ?? ''} onChange={f('default_business_pct')} />
              </div>
            )}
            {(form.type === 'supplier' || form.type === 'both') && (
              <div className="field">
                <label className="field-label">Default payment method</label>
                <select className="field-select" value={form.default_payment_method_id || ''} onChange={f('default_payment_method_id')}>
                  <option value="">— none —</option>
                  {(paymentMethods || []).map(m => (
                    <option key={m.id} value={m.id}>{m.name}{m.account_ref ? ` (${m.account_ref})` : ''}</option>
                  ))}
                </select>
              </div>
            )}

            {/* Payment address — show when populated or when user expands */}
            {(form.type === 'supplier' || form.type === 'both') && (
              <>
                <hr className="divider" />
                <div style={{marginBottom:12,fontSize:12,fontFamily:'var(--font-mono)',color:'var(--fg-subtle)',textTransform:'uppercase',letterSpacing:'0.1em'}}>Payment address <span style={{fontSize:10,letterSpacing:0,textTransform:'none',color:'var(--fg-subtle)',marginLeft:6}}>leave blank if same as above</span></div>
                <div className="form-grid">
                  <div className="field field--full">
                    <label className="field-label">Street</label>
                    <input className="field-input" value={form.pay_address_street} onChange={f('pay_address_street')} placeholder="e.g. Finance Dept, Postbus 123" />
                  </div>
                  <div className="field">
                    <label className="field-label">City</label>
                    <input className="field-input" value={form.pay_address_city} onChange={f('pay_address_city')} />
                  </div>
                  <div className="field">
                    <label className="field-label">Postcode</label>
                    <input className="field-input" value={form.pay_address_postcode} onChange={f('pay_address_postcode')} />
                  </div>
                  <div className="field">
                    <label className="field-label">Country</label>
                    <input className="field-input" value={form.pay_address_country} onChange={f('pay_address_country')} placeholder="NL" />
                  </div>
                </div>
              </>
            )}

            {/* Approval status — only editable for unvetted auto-created suppliers */}
            {!form.approved && (
              <div style={{
                display:'flex', alignItems:'center', gap:10,
                padding:'10px 14px', margin:'16px 0 0',
                borderRadius:6, background:'rgba(255,168,107,0.10)', border:'1px solid rgba(255,168,107,0.35)',
              }}>
                <span style={{fontSize:15}}>⚠</span>
                <div style={{flex:1, fontSize:12, fontFamily:'var(--font-mono)', color:'var(--ember)'}}>
                  Auto-created from invoice · not yet approved
                </div>
                <button type="button" className="btn btn--sm" style={{background:'var(--ember)',color:'#000',fontWeight:600,flexShrink:0}}
                  onClick={() => setForm(p => ({ ...p, approved: 1 }))}>
                  Approve
                </button>
              </div>
            )}

            {(form.type === 'customer' || form.type === 'both') && (
              <>
                <hr className="divider" />
                <div style={{marginBottom:12,fontSize:12,fontFamily:'var(--font-mono)',color:'var(--fg-subtle)',textTransform:'uppercase',letterSpacing:'0.1em'}}>Rate settings</div>
                <div className="form-grid">
                  <div className="field">
                    <label className="field-label">Hourly rate (€)</label>
                    <input className="field-input" type="number" step="0.01" value={rate.hourly_rate} onChange={r('hourly_rate')} placeholder="0.00" />
                  </div>
                  <div className="field">
                    <label className="field-label">Day rate (€)</label>
                    <input className="field-input" type="number" step="0.01" value={rate.day_rate} onChange={r('day_rate')} placeholder="0.00" />
                  </div>
                  <div className="field">
                    <label className="field-label">Default VAT rate</label>
                    <select className="field-select" value={rate.default_vat_rate} onChange={r('default_vat_rate')}>
                      <option value="0.21">21%</option>
                      <option value="0.09">9%</option>
                      <option value="0.00">0% (exempt / EU B2B)</option>
                    </select>
                  </div>
                  <div className="field">
                    <label className="field-label">Currency</label>
                    <select className="field-select" value={rate.currency} onChange={r('currency')}>
                      <option value="EUR">EUR</option>
                      <option value="USD">USD</option>
                      <option value="GBP">GBP</option>
                    </select>
                  </div>
                  <div className="field field--full">
                    <label className="field-label">Invoice notes (auto-fills)</label>
                    <textarea className="field-textarea" value={rate.notes} onChange={r('notes')} rows={2} />
                  </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 company'}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function ContactModal({ companyId, contact, onSave, onClose }) {
  const [form, setForm] = useState(contact || { ...EMPTY_CT, company_id: companyId });
  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 ct = contact?.id
        ? await API.put(`/contacts/${contact.id}`, form)
        : await API.post('/contacts', { ...form, company_id: companyId });
      toast(contact ? 'Contact updated' : 'Contact added');
      onSave(ct);
    } catch (e) { toast(e.error || 'Error saving', 'error'); }
    finally { setBusy(false); }
  }

  return (
    <div className="modal-overlay" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="modal">
        <div className="modal-head">
          <span className="modal-title">{contact ? 'Edit contact' : 'Add contact'}</span>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>
        <form onSubmit={save} style={{display:'flex',flexDirection:'column',flex:1,minHeight:0,overflow:'hidden'}}>
          <div className="modal-body">
            <div className="form-grid">
              <div className="field field--full">
                <label className="field-label">Name *</label>
                <input className="field-input" required value={form.name} onChange={f('name')} />
              </div>
              <div className="field">
                <label className="field-label">Email</label>
                <input className="field-input" type="email" value={form.email} onChange={f('email')} />
              </div>
              <div className="field">
                <label className="field-label">Phone</label>
                <input className="field-input" value={form.phone} onChange={f('phone')} />
              </div>
              <div className="field field--full">
                <label className="field-label">Role / title</label>
                <input className="field-input" value={form.role} onChange={f('role')} placeholder="e.g. Finance Manager" />
              </div>
              <div className="field field--full">
                <label style={{display:'flex',alignItems:'center',gap:8,cursor:'pointer'}}>
                  <input type="checkbox" checked={!!form.is_primary} onChange={f('is_primary')} />
                  <span className="field-label" style={{margin:0}}>Primary contact</span>
                </label>
              </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 contact'}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function Relations() {
  const [companies, setCompanies]       = useState([]);
  const [paymentMethods, setPayMethods] = useState([]);
  const [filter, setFilter]             = useState('all');
  const [search, setSearch]             = useState('');
  const [selectedCo, setSelectedCo]     = useState(null);
  const [contacts, setContacts]         = useState([]);
  const [coModal, setCoModal]           = useState(null);
  const [ctModal, setCtModal]           = useState(null);
  const { toast } = useApp();

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

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

  useEffect(() => {
    if (selectedCo) {
      API.get(`/contacts?company_id=${selectedCo.id}`).then(setContacts).catch(() => {});
    }
  }, [selectedCo]);

  async function approveCo(co) {
    await API.put(`/companies/${co.id}`, { ...co, approved: 1 }).catch(e => toast(e.error || 'Error', 'error'));
    load(); toast(`${co.name} approved`);
  }

  async function deleteCo(co) {
    if (!confirm(`Delete ${co.name}? This cannot be undone.`)) return;
    await API.del(`/companies/${co.id}`).catch(e => toast(e.error || 'Error', 'error'));
    if (selectedCo?.id === co.id) setSelectedCo(null);
    load();
    toast('Company deleted');
  }

  async function deleteCt(ct) {
    if (!confirm(`Remove ${ct.name}?`)) return;
    await API.del(`/contacts/${ct.id}`).catch(e => toast(e.error || 'Error', 'error'));
    setContacts(c => c.filter(x => x.id !== ct.id));
    toast('Contact removed');
  }

  const visible = companies.filter(co => {
    if (filter === 'pending') return !co.approved;
    if (filter !== 'all' && co.type !== filter && !(filter === 'customer' && co.type === 'both') && !(filter === 'supplier' && co.type === 'both')) return false;
    if (search && !co.name.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Relations</h1>
          <div className="page-subtitle">Companies and contacts</div>
        </div>
        <div className="page-actions">
          <button className="btn btn--primary" onClick={() => setCoModal({})}>+ New company</button>
        </div>
      </div>

      <div style={{display:'flex',gap:12,marginBottom:20,alignItems:'center'}}>
        <input className="field-input" style={{maxWidth:240}} placeholder="Search…" value={search} onChange={e => setSearch(e.target.value)} />
        <div className="tabs" style={{marginBottom:0,border:'none'}}>
          {[['all','All'],['customer','Customers'],['supplier','Suppliers'],['pending','Pending']].map(([v,l]) => (
            <button key={v} className={`tab ${filter===v?'is-active':''}`} onClick={() => setFilter(v)}>{l}</button>
          ))}
        </div>
      </div>

      <div style={{display:'grid',gridTemplateColumns:selectedCo?'1fr 340px':'1fr',gap:16}}>
        <div className="card" style={{margin:0}}>
          <div className="table-wrap">
            <table className="data-table" style={{padding:'0 20px'}}>
              <thead><tr><th>Name</th><th>Type</th><th>KvK</th><th>BTW</th><th>Terms</th><th></th></tr></thead>
              <tbody>
                {visible.length === 0 && <tr><td colSpan={6}><div className="empty-state">No companies yet</div></td></tr>}
                {visible.map(co => (
                  <tr key={co.id} style={{cursor:'pointer', opacity: co.approved ? 1 : 0.85}} onClick={() => setSelectedCo(co === selectedCo ? null : co)}>
                    <td style={{fontWeight: selectedCo?.id===co.id ? 600 : 400}}>
                      {co.name}
                      {!co.approved && (
                        <span style={{marginLeft:8,fontSize:9,fontFamily:'var(--font-mono)',letterSpacing:'0.06em',color:'var(--ember)',background:'rgba(255,168,107,0.15)',padding:'1px 5px',borderRadius:3}}>PENDING</span>
                      )}
                    </td>
                    <td><span className={`status status--${co.type}`}>{co.type}</span></td>
                    <td className="mono muted">{co.kvk || '—'}</td>
                    <td className="mono muted">{co.btw_number || '—'}</td>
                    <td className="mono">{co.payment_terms_days}d</td>
                    <td>
                      <div className="row-actions" onClick={e => e.stopPropagation()}>
                        {!co.approved && (
                          <button className="btn btn--sm" style={{background:'var(--ember)',color:'#000',fontWeight:600}}
                            onClick={() => approveCo(co)}>Approve</button>
                        )}
                        <button className="btn btn--ghost btn--sm" onClick={() => setCoModal(co)}>Edit</button>
                        <button className="btn btn--danger btn--sm" onClick={() => deleteCo(co)}>Del</button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {selectedCo && (
          <div className="card" style={{margin:0}}>
            <div className="card-head">
              <span className="card-title">{selectedCo.name}</span>
              <button className="btn btn--primary btn--sm" onClick={() => setCtModal({})}>+ Contact</button>
            </div>

            {/* Address summary */}
            {(selectedCo.address_city || selectedCo.pay_address_city) && (
              <div style={{padding:'10px 20px',borderBottom:'1px solid var(--border)',display:'flex',gap:20,fontSize:11,fontFamily:'var(--font-mono)',color:'var(--fg-subtle)'}}>
                {selectedCo.address_city && (
                  <div>
                    <div style={{fontSize:9,letterSpacing:'0.08em',textTransform:'uppercase',color:'var(--fg-subtle)',marginBottom:2}}>Address</div>
                    <div>{selectedCo.address_street}</div>
                    <div>{selectedCo.address_postcode} {selectedCo.address_city}</div>
                    {selectedCo.address_country && selectedCo.address_country !== 'NL' && <div>{selectedCo.address_country}</div>}
                  </div>
                )}
                {selectedCo.pay_address_city && (
                  <div>
                    <div style={{fontSize:9,letterSpacing:'0.08em',textTransform:'uppercase',color:'var(--ember)',marginBottom:2}}>Payment address</div>
                    <div>{selectedCo.pay_address_street}</div>
                    <div>{selectedCo.pay_address_postcode} {selectedCo.pay_address_city}</div>
                    {selectedCo.pay_address_country && selectedCo.pay_address_country !== 'NL' && <div>{selectedCo.pay_address_country}</div>}
                  </div>
                )}
              </div>
            )}

            <div className="card-body" style={{padding:'12px 20px'}}>
              {contacts.length === 0
                ? <div className="empty-state-label" style={{padding:'20px 0'}}>No contacts</div>
                : contacts.map(ct => (
                  <div key={ct.id} style={{padding:'10px 0',borderBottom:'1px solid var(--border)'}}>
                    <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start'}}>
                      <div>
                        <div style={{fontSize:13,fontWeight:ct.is_primary?600:400}}>{ct.name}{ct.is_primary ? <span style={{fontSize:9,fontFamily:'var(--font-mono)',color:'var(--signal)',marginLeft:6,letterSpacing:'0.08em'}}>PRIMARY</span> : ''}</div>
                        {ct.role && <div style={{fontSize:11,color:'var(--fg-muted)'}}>{ct.role}</div>}
                        {ct.email && <div style={{fontSize:11,color:'var(--fg-muted)'}}>{ct.email}</div>}
                        {ct.phone && <div style={{fontSize:11,color:'var(--fg-muted)'}}>{ct.phone}</div>}
                      </div>
                      <div style={{display:'flex',gap:4}}>
                        <button className="btn btn--ghost btn--sm" onClick={() => setCtModal(ct)}>Edit</button>
                        <button className="btn btn--danger btn--sm" onClick={() => deleteCt(ct)}>×</button>
                      </div>
                    </div>
                  </div>
                ))
              }
            </div>
          </div>
        )}
      </div>

      {coModal !== null && (
        <CompanyModal
          company={coModal.id ? coModal : null}
          paymentMethods={paymentMethods}
          onSave={co => { load(); setCoModal(null); if (!coModal.id) setSelectedCo(co); }}
          onClose={() => setCoModal(null)}
        />
      )}
      {ctModal !== null && selectedCo && (
        <ContactModal
          companyId={selectedCo.id}
          contact={ctModal.id ? ctModal : null}
          onSave={ct => {
            setContacts(c => ctModal.id ? c.map(x => x.id===ct.id?ct:x) : [...c, ct]);
            setCtModal(null);
          }}
          onClose={() => setCtModal(null)}
        />
      )}
    </div>
  );
}
window.Relations = Relations;
