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

function GroupModal({ group, onSave, onClose }) {
  const isNew = !group?.id;
  const [form, setForm] = useState({ name:'', description:'', ...(group||{}) });
  const [busy, setBusy] = useState(false);
  const { toast } = useApp();
  const f = k => e => setForm(p => ({ ...p, [k]: e.target.value }));

  async function save(e) {
    e.preventDefault(); setBusy(true);
    try {
      isNew ? await API.post('/customer-groups', form) : await API.put(`/customer-groups/${group.id}`, form);
      toast(isNew ? 'Group created' : 'Group 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">
        <div className="modal-head">
          <span className="modal-title">{isNew?'New group':'Edit group'}</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">Group name *</label>
                <input className="field-input" required value={form.name} onChange={f('name')} placeholder="e.g. Retainer clients" />
              </div>
              <div className="field field--full">
                <label className="field-label">Description</label>
                <input className="field-input" value={form.description||''} onChange={f('description')} placeholder="Optional note" />
              </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'}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function CustomerGroups() {
  const [groups, setGroups]       = useState([]);
  const [companies, setCompanies] = useState([]);
  const [selected, setSelected]   = useState(null);
  const [detail, setDetail]       = useState(null);
  const [modal, setModal]         = useState(null);
  const { toast } = useApp();

  const load = useCallback(() => {
    API.get('/customer-groups').then(setGroups).catch(()=>{});
  }, []);

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

  useEffect(() => {
    if (selected) {
      API.get(`/customer-groups/${selected.id}`).then(setDetail).catch(()=>{});
    } else {
      setDetail(null);
    }
  }, [selected]);

  async function del(g) {
    if (!confirm(`Delete group "${g.name}"?`)) return;
    await API.del(`/customer-groups/${g.id}`).catch(e=>toast(e.error||'Error','error'));
    if (selected?.id===g.id) setSelected(null);
    load(); toast('Group deleted');
  }

  async function addMember(companyId) {
    await API.post(`/customer-groups/${selected.id}/members`, { company_id: companyId }).catch(e=>toast(e.error||'Error','error'));
    const d = await API.get(`/customer-groups/${selected.id}`);
    setDetail(d);
  }

  async function removeMember(companyId) {
    await fetch(`/api/customer-groups/${selected.id}/members`, {
      method:'DELETE', headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ company_id: companyId }),
    });
    const d = await API.get(`/customer-groups/${selected.id}`);
    setDetail(d);
  }

  const memberIds = new Set((detail?.members||[]).map(m=>m.id));
  const available = companies.filter(c=>!memberIds.has(c.id));

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Customer groups</h1>
          <div className="page-subtitle">Assign groups for document targeting</div>
        </div>
        <div className="page-actions">
          <button className="btn btn--primary" onClick={()=>setModal({})}>+ New group</button>
        </div>
      </div>

      <div style={{display:'grid',gridTemplateColumns:selected?'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>Group</th><th>Description</th><th>Members</th><th>Documents</th><th></th></tr></thead>
              <tbody>
                {groups.length===0 && <tr><td colSpan={5}><div className="empty-state">No groups yet</div></td></tr>}
                {groups.map(g=>(
                  <tr key={g.id} style={{cursor:'pointer'}} onClick={()=>setSelected(g===selected?null:g)}>
                    <td style={{fontWeight: selected?.id===g.id?600:400}}>{g.name}</td>
                    <td className="muted" style={{fontSize:12}}>{g.description||'—'}</td>
                    <td className="mono">{g.member_count}</td>
                    <td className="mono">{g.document_count}</td>
                    <td>
                      <div className="row-actions" onClick={e=>e.stopPropagation()}>
                        <button className="btn btn--ghost btn--sm" onClick={()=>setModal(g)}>Edit</button>
                        <button className="btn btn--danger btn--sm" onClick={()=>del(g)}>Del</button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {selected && detail && (
          <div className="card" style={{margin:0}}>
            <div className="card-head">
              <span className="card-title">{selected.name}</span>
            </div>
            <div style={{padding:'12px 20px',borderBottom:'1px solid var(--border)'}}>
              <div style={{fontSize:10,fontFamily:'var(--font-mono)',textTransform:'uppercase',letterSpacing:'0.08em',color:'var(--fg-subtle)',marginBottom:8}}>Members</div>
              {(detail.members||[]).length===0
                ? <div style={{fontSize:12,color:'var(--fg-muted)'}}>No members yet</div>
                : (detail.members||[]).map(m=>(
                  <div key={m.id} style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'5px 0',borderBottom:'1px solid var(--border)'}}>
                    <span style={{fontSize:13}}>{m.name}</span>
                    <button className="btn btn--danger btn--sm" onClick={()=>removeMember(m.id)}>×</button>
                  </div>
                ))
              }
              {available.length > 0 && (
                <div style={{marginTop:10}}>
                  <select className="field-select" style={{fontSize:12}} onChange={e=>{if(e.target.value){addMember(e.target.value);e.target.value=''}}}>
                    <option value="">+ Add company…</option>
                    {available.map(c=><option key={c.id} value={c.id}>{c.name}</option>)}
                  </select>
                </div>
              )}
            </div>
            {(detail.documents||[]).length>0 && (
              <div style={{padding:'12px 20px'}}>
                <div style={{fontSize:10,fontFamily:'var(--font-mono)',textTransform:'uppercase',letterSpacing:'0.08em',color:'var(--fg-subtle)',marginBottom:8}}>Linked documents</div>
                {(detail.documents||[]).map(d=>(
                  <div key={d.id} style={{fontSize:12,color:'var(--fg-muted)',padding:'3px 0'}}>
                    <span className="badge" style={{marginRight:6}}>{d.category}</span>{d.name}
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
      </div>

      {modal!==null && (
        <GroupModal group={modal.id?modal:null} onSave={()=>{load();setModal(null);}} onClose={()=>setModal(null)} />
      )}
    </div>
  );
}
window.CustomerGroups = CustomerGroups;
