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

const CATEGORIES = ['terms','dpa','contract','quote','policy','other'];
const CAT_LABEL  = { terms:'Algemene Voorwaarden', dpa:'Verwerkersovereenkomst', contract:'Contract', quote:'Offerte / Quote', policy:'Policy / SLA', other:'Other' };
const SCOPES     = ['general','group','customer'];
const SCOPE_LABEL= { general:'General (all customers)', group:'Group', customer:'Customer-specific' };

function fmtSize(b) {
  if (!b) return '—';
  if (b < 1024) return b + ' B';
  if (b < 1048576) return (b/1024).toFixed(0) + ' KB';
  return (b/1048576).toFixed(1) + ' MB';
}

function DocModal({ doc, groups, companies, onSave, onClose }) {
  const isNew = !doc?.id;
  const [form, setForm] = useState({
    name:'', description:'', category:'other', doc_scope:'general',
    version:'', group_ids:[], company_ids:[],
    ...(doc ? { ...doc, group_ids: doc.group_ids||[], company_ids: doc.company_ids||[] } : {}),
  });
  const [file, setFile] = useState(null);
  const [busy, setBusy] = useState(false);
  const { toast } = useApp();
  const f = k => e => setForm(p => ({ ...p, [k]: e.target.value }));

  function toggleArr(key, val) {
    setForm(p => {
      const arr = p[key];
      return { ...p, [key]: arr.includes(val) ? arr.filter(x=>x!==val) : [...arr, val] };
    });
  }

  async function save(e) {
    e.preventDefault();
    if (isNew && !file) return toast('Select a file to upload', 'error');
    setBusy(true);
    try {
      let r2_key = form.r2_key, file_name = form.file_name, file_size = form.file_size, mime_type = form.mime_type;
      if (file) {
        const fd = new FormData(); fd.append('file', file); fd.append('folder', 'documents');
        const up = await API.upload('/upload', fd);
        r2_key = up.key; file_name = file.name; file_size = file.size; mime_type = file.type;
      }
      const body = { ...form, r2_key, file_name, file_size, mime_type };
      isNew ? await API.post('/documents', body) : await API.put(`/documents/${doc.id}`, body);
      toast(isNew ? 'Document uploaded' : 'Document 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 ? 'Upload document' : 'Edit document'}</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')} placeholder="e.g. Algemene Voorwaarden 2024" />
              </div>
              <div className="field">
                <label className="field-label">Category</label>
                <select className="field-select" value={form.category} onChange={f('category')}>
                  {CATEGORIES.map(c => <option key={c} value={c}>{CAT_LABEL[c]}</option>)}
                </select>
              </div>
              <div className="field">
                <label className="field-label">Version</label>
                <input className="field-input" value={form.version} onChange={f('version')} placeholder="e.g. 2024-01" />
              </div>
              <div className="field">
                <label className="field-label">Scope</label>
                <select className="field-select" value={form.doc_scope} onChange={f('doc_scope')}>
                  {SCOPES.map(s => <option key={s} value={s}>{SCOPE_LABEL[s]}</option>)}
                </select>
              </div>
              <div className="field field--full">
                <label className="field-label">Description</label>
                <textarea className="field-textarea" rows={2} value={form.description} onChange={f('description')} />
              </div>

              {form.doc_scope === 'group' && (
                <div className="field field--full">
                  <label className="field-label">Customer groups</label>
                  <div style={{display:'flex',flexWrap:'wrap',gap:6,marginTop:4}}>
                    {groups.map(g => (
                      <label key={g.id} style={{display:'flex',alignItems:'center',gap:6,padding:'4px 10px',border:'1px solid var(--border)',borderRadius:4,cursor:'pointer',fontSize:12,background: form.group_ids.includes(g.id)?'var(--accent-bg)':'var(--bg-surface)'}}>
                        <input type="checkbox" checked={form.group_ids.includes(g.id)} onChange={()=>toggleArr('group_ids',g.id)} style={{margin:0}} />
                        {g.name}
                      </label>
                    ))}
                    {groups.length === 0 && <span style={{fontSize:12,color:'var(--fg-muted)'}}>No groups yet — create one first</span>}
                  </div>
                </div>
              )}

              {form.doc_scope === 'customer' && (
                <div className="field field--full">
                  <label className="field-label">Companies</label>
                  <div style={{maxHeight:160,overflowY:'auto',border:'1px solid var(--border)',borderRadius:4,padding:4}}>
                    {companies.filter(c=>c.type==='customer'||c.type==='both').map(c => (
                      <label key={c.id} style={{display:'flex',alignItems:'center',gap:8,padding:'5px 8px',cursor:'pointer',fontSize:12,borderRadius:3,background: form.company_ids.includes(c.id)?'var(--accent-bg)':'transparent'}}>
                        <input type="checkbox" checked={form.company_ids.includes(c.id)} onChange={()=>toggleArr('company_ids',c.id)} style={{margin:0}} />
                        {c.name}
                      </label>
                    ))}
                  </div>
                </div>
              )}

              <div className="field field--full">
                <label className="field-label">{isNew ? 'File *' : 'Replace file (optional)'}</label>
                <input type="file" accept=".pdf,.docx,.doc,.xlsx,.xls,.txt,.png,.jpg" onChange={e=>setFile(e.target.files[0])} style={{fontSize:12,color:'var(--fg-muted)'}} />
                {!isNew && form.file_name && !file && (
                  <div style={{fontSize:11,marginTop:4,color:'var(--fg-muted)'}}>{form.file_name} ({fmtSize(form.file_size)})</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…':isNew?'Upload':'Save'}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function Documents() {
  const [docs, setDocs]           = useState([]);
  const [groups, setGroups]       = useState([]);
  const [companies, setCompanies] = useState([]);
  const [modal, setModal]         = useState(null);
  const [filter, setFilter]       = useState('all');
  const { toast } = useApp();

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

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

  async function toggleVisible(doc) {
    await API.put(`/documents/${doc.id}`, { visible: doc.visible ? 0 : 1 }).catch(e=>toast(e.error||'Error','error'));
    load();
  }

  async function del(doc) {
    if (!confirm(`Delete "${doc.name}"? This cannot be undone.`)) return;
    await API.del(`/documents/${doc.id}`).catch(e=>toast(e.error||'Error','error'));
    load(); toast('Document deleted');
  }

  const visible = docs.filter(d => filter==='all' || d.category===filter || d.doc_scope===filter);
  const groupMap = Object.fromEntries(groups.map(g=>[g.id,g.name]));
  const coMap    = Object.fromEntries(companies.map(c=>[c.id,c.name]));

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Documents</h1>
          <div className="page-subtitle">General, group, and customer-specific files</div>
        </div>
        <div className="page-actions">
          <button className="btn btn--primary" onClick={()=>setModal({})}>+ Upload document</button>
        </div>
      </div>

      <div className="tabs">
        <button className={`tab ${filter==='all'?'is-active':''}`} onClick={()=>setFilter('all')}>All</button>
        <button className={`tab ${filter==='general'?'is-active':''}`} onClick={()=>setFilter('general')}>General</button>
        <button className={`tab ${filter==='group'?'is-active':''}`} onClick={()=>setFilter('group')}>Group</button>
        <button className={`tab ${filter==='customer'?'is-active':''}`} onClick={()=>setFilter('customer')}>Customer</button>
        {CATEGORIES.map(c=><button key={c} className={`tab ${filter===c?'is-active':''}`} onClick={()=>setFilter(c)}>{c}</button>)}
      </div>

      <div className="card" style={{margin:0}}>
        <div className="table-wrap">
          <table className="data-table" style={{padding:'0 20px'}}>
            <thead><tr><th>Name</th><th>Category</th><th>Scope</th><th>Target</th><th>Size</th><th>Views</th><th>Visible</th><th></th></tr></thead>
            <tbody>
              {visible.length===0 && <tr><td colSpan={8}><div className="empty-state">No documents yet</div></td></tr>}
              {visible.map(doc=>(
                <tr key={doc.id} style={{opacity:doc.visible?1:0.5}}>
                  <td style={{fontWeight:500}}>
                    {doc.name}
                    {doc.version && <span style={{marginLeft:6,fontSize:10,fontFamily:'var(--font-mono)',color:'var(--fg-subtle)'}}>{doc.version}</span>}
                  </td>
                  <td><span className="badge">{doc.category}</span></td>
                  <td><span className={`status ${doc.doc_scope==='general'?'status--approved':doc.doc_scope==='group'?'status--sent':'status--pending'}`}>{doc.doc_scope}</span></td>
                  <td style={{fontSize:11,color:'var(--fg-muted)'}}>
                    {doc.doc_scope==='general' && 'All customers'}
                    {doc.doc_scope==='group' && (doc.group_ids?.map(id=>groupMap[id]||id).join(', ')||'—')}
                    {doc.doc_scope==='customer' && (doc.company_ids?.map(id=>coMap[id]||id).join(', ')||'—')}
                  </td>
                  <td className="mono" style={{fontSize:11}}>{fmtSize(doc.file_size)}</td>
                  <td className="mono" style={{fontSize:11}}>{doc.view_count||0}</td>
                  <td>
                    <button
                      className={`status ${doc.visible?'status--approved':'status--draft'}`}
                      style={{cursor:'pointer',background:'none',border:'1px solid'}}
                      onClick={()=>toggleVisible(doc)}
                    >{doc.visible?'visible':'hidden'}</button>
                  </td>
                  <td>
                    <div className="row-actions">
                      <button className="btn btn--ghost btn--sm" onClick={()=>setModal(doc)}>Edit</button>
                      <button className="btn btn--danger btn--sm" onClick={()=>del(doc)}>Del</button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {modal!==null && (
        <DocModal
          doc={modal.id?modal:null}
          groups={groups}
          companies={companies}
          onSave={()=>{load();setModal(null);}}
          onClose={()=>setModal(null)}
        />
      )}
    </div>
  );
}
window.Documents = Documents;
