// Admin view: audit log + user management

function UsersTab({ user }) {
  const [users, setUsers]         = React.useState([]);
  const [invites, setInvites]     = React.useState([]);
  const [loading, setLoading]     = React.useState(true);
  const [inviteEmail, setInviteEmail] = React.useState('');
  const [inviteRole, setInviteRole]   = React.useState('operator');
  const [inviteStatus, setInviteStatus] = React.useState(null); // null | 'loading' | 'ok' | 'error'
  const [inviteErr, setInviteErr]     = React.useState('');
  const [inviteLink, setInviteLink]   = React.useState('');
  const [patchStatus, setPatchStatus] = React.useState({}); // {userId: 'loading'|'ok'|'error'}

  async function load() {
    try {
      const [uRes, iRes] = await Promise.all([fetch('/users'), fetch('/users/invitations')]);
      if (uRes.ok) setUsers(await uRes.json());
      if (iRes.ok) setInvites(await iRes.json());
    } catch (_) {}
    setLoading(false);
  }

  React.useEffect(() => { load(); }, []);

  async function sendInvite(e) {
    e?.preventDefault?.();
    if (!inviteEmail) return;
    setInviteStatus('loading'); setInviteErr('');
    try {
      const res = await fetch('/users/invite', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: inviteEmail, role: inviteRole }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        setInviteStatus('error'); setInviteErr(data.detail || 'Error al enviar invitación.'); return;
      }
      const data = await res.json();
      setInviteLink(data.link || '');
      setInviteStatus('ok'); setInviteEmail('');
      load();
    } catch (_) {
      setInviteStatus('error'); setInviteErr('Error de conexión.');
    }
  }

  async function revokeInvite(id) {
    try {
      await fetch(`/users/invitations/${id}`, { method: 'DELETE' });
      load();
    } catch (_) {}
  }

  async function toggleActive(u) {
    setPatchStatus(p => ({ ...p, [u.id]: 'loading' }));
    try {
      const res = await fetch(`/users/${u.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ active: !u.active }),
      });
      setPatchStatus(p => ({ ...p, [u.id]: res.ok ? 'ok' : 'error' }));
      if (res.ok) load();
      setTimeout(() => setPatchStatus(p => { const n={...p}; delete n[u.id]; return n; }), 2000);
    } catch (_) {
      setPatchStatus(p => ({ ...p, [u.id]: 'error' }));
    }
  }

  const isMe = (u) => u.id === user.id;

  const roleColors = { admin: { bg: BC.supervisory.bg, fg: BC.supervisory.fg }, operator: { bg: BC.trouble.bg, fg: BC.trouble.fg } };
  function RoleChip({ role }) {
    const c = roleColors[role] || { bg: BC.bgAlt, fg: BC.inkSubtle };
    return <span style={{ fontSize:10, fontWeight:700, padding:'2px 8px', borderRadius:4, background:c.bg, color:c.fg, textTransform:'uppercase', letterSpacing:'.04em' }}>{role}</span>;
  }

  const formatDate = ts => ts ? new Date(ts).toLocaleDateString('es-CL') : '—';

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:18 }}>

      {/* Invite panel */}
      <div style={{ background:BC.surface, border:'1px solid '+BC.border, borderRadius:8, boxShadow:BC.shadow }}>
        <div style={{ padding:'14px 18px', borderBottom:'1px solid '+BC.border }}>
          <div style={{ fontSize:14, fontWeight:600 }}>Invitar usuario</div>
          <div style={{ fontSize:11, color:BC.inkSubtle, marginTop:2 }}>
            El usuario recibirá un enlace para crear su cuenta. La invitación expira en 72 horas.
          </div>
        </div>
        <form onSubmit={sendInvite} style={{ padding:'14px 18px', display:'flex', gap:8, alignItems:'flex-end', flexWrap:'wrap' }}>
          <div style={{ flex:2, minWidth:200 }}>
            <label style={{ display:'block', fontSize:11, fontWeight:600, color:BC.inkSubtle, textTransform:'uppercase', letterSpacing:'.06em', marginBottom:5 }}>Correo</label>
            <input className="bc-input" type="email" value={inviteEmail} onChange={e => setInviteEmail(e.target.value)} placeholder="correo@empresa.com"
              style={{ width:'100%', padding:'8px 10px', border:'1px solid '+BC.border, borderRadius:5, background:BC.surfaceAlt, fontSize:13, color:BC.ink }}/>
          </div>
          <div style={{ flex:1, minWidth:120 }}>
            <label style={{ display:'block', fontSize:11, fontWeight:600, color:BC.inkSubtle, textTransform:'uppercase', letterSpacing:'.06em', marginBottom:5 }}>Rol</label>
            <select value={inviteRole} onChange={e => setInviteRole(e.target.value)}
              style={{ width:'100%', padding:'8px 10px', border:'1px solid '+BC.border, borderRadius:5, background:BC.surfaceAlt, fontSize:13, color:BC.ink }}>
              <option value="operator">Operador</option>
              <option value="admin">Administrador</option>
            </select>
          </div>
          <div>
            <button type="submit" disabled={inviteStatus==='loading'} className="bc-btn"
              style={{ padding:'8px 16px', background:BC.brand, color:'#fff', border:'none', borderRadius:5, fontSize:13, fontWeight:600 }}>
              {inviteStatus==='loading' ? '…' : 'Enviar invitación'}
            </button>
          </div>
        </form>
        {inviteStatus === 'ok' && inviteLink && (
          <div style={{ margin:'0 18px 14px', padding:'12px 14px', background:BC.ok.bg, border:'1px solid '+BC.ok.bar, borderRadius:5 }}>
            <div style={{ fontSize:12, color:BC.ok.fg, display:'flex', alignItems:'center', gap:6, marginBottom:8 }}>
              <Icon name="check" size={13}/> Invitación creada. Comparte este enlace con el usuario:
            </div>
            <div style={{ display:'flex', gap:6, alignItems:'center' }}>
              <input readOnly value={inviteLink}
                style={{ flex:1, padding:'6px 10px', border:'1px solid '+BC.border, borderRadius:4, background:BC.surface, fontSize:11, color:BC.inkMuted, fontFamily:BC.mono }}
                onFocus={e => e.target.select()}/>
              <button className="bc-btn" onClick={() => { navigator.clipboard.writeText(inviteLink); }}
                style={{ padding:'6px 12px', background:BC.brand, color:'#fff', border:'none', borderRadius:4, fontSize:12, fontWeight:600, whiteSpace:'nowrap' }}>
                Copiar
              </button>
            </div>
          </div>
        )}
        {inviteStatus === 'error' && (
          <div style={{ margin:'0 18px 14px', padding:'8px 12px', background:BC.fire.bg, color:BC.fire.fg, border:'1px solid '+BC.fire.bar, borderRadius:5, fontSize:12, display:'flex', alignItems:'center', gap:6 }}>
            <Icon name="warning" size={13}/> {inviteErr}
          </div>
        )}
      </div>

      {/* Pending invitations */}
      {invites.length > 0 && (
        <div style={{ background:BC.surface, border:'1px solid '+BC.border, borderRadius:8, boxShadow:BC.shadow }}>
          <div style={{ padding:'14px 18px', borderBottom:'1px solid '+BC.border, fontSize:13, fontWeight:600 }}>
            Invitaciones pendientes <span style={{ fontFamily:BC.mono, fontSize:11, padding:'1px 6px', borderRadius:4, background:BC.pending.bg, color:BC.pending.fg, marginLeft:6 }}>{invites.length}</span>
          </div>
          <div className="bc-admin-table-wrap"><table className="bc-tbl" style={{ width:'100%', borderCollapse:'collapse' }}>
            <thead><tr><th>Correo</th><th>Rol</th><th>Expira</th><th></th></tr></thead>
            <tbody>
              {invites.map(inv => (
                <tr key={inv.id}>
                  <td style={{ fontSize:12, fontFamily:BC.mono }}>{inv.email}</td>
                  <td><RoleChip role={inv.role}/></td>
                  <td style={{ fontSize:11, color:BC.inkSubtle }}>{formatDate(inv.expires_at)}</td>
                  <td>
                    <button onClick={() => revokeInvite(inv.id)} className="bc-btn"
                      style={{ padding:'3px 10px', fontSize:11, background:'transparent', color:BC.fire.fg, border:'1px solid '+BC.fire.bar, borderRadius:4 }}>
                      Revocar
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table></div>
        </div>
      )}

      {/* Users table */}
      <div style={{ background:BC.surface, border:'1px solid '+BC.border, borderRadius:8, boxShadow:BC.shadow }}>
        <div style={{ padding:'14px 18px', borderBottom:'1px solid '+BC.border }}>
          <div style={{ fontSize:14, fontWeight:600 }}>Usuarios</div>
          <div style={{ fontSize:11, color:BC.inkSubtle, marginTop:2 }}>Usuarios activos e inactivos de tu empresa.</div>
        </div>
        {loading ? (
          <div style={{ padding:'40px', textAlign:'center', color:BC.inkFaint, fontSize:12 }}>Cargando…</div>
        ) : (
          <div className="bc-admin-table-wrap"><table className="bc-tbl" style={{ width:'100%', borderCollapse:'collapse' }}>
            <thead><tr><th>Usuario</th><th>Correo</th><th>Rol</th><th>Estado</th><th></th></tr></thead>
            <tbody>
              {users.length === 0 && (
                <tr><td colSpan={5} style={{ textAlign:'center', padding:'24px', color:BC.inkFaint }}>Sin usuarios.</td></tr>
              )}
              {users.map(u => (
                <tr key={u.id}>
                  <td style={{ fontWeight:500, fontSize:13 }}>
                    {u.username}
                    {isMe(u) && <span style={{ fontSize:10, color:BC.inkFaint, marginLeft:6 }}>(tú)</span>}
                  </td>
                  <td style={{ fontSize:12, color:BC.inkMuted }}>{u.email || '—'}</td>
                  <td><RoleChip role={u.role}/></td>
                  <td>
                    <span style={{ fontSize:11, display:'inline-flex', alignItems:'center', gap:4, color: u.active ? BC.ok.fg : BC.fire.fg }}>
                      <Icon name={u.active ? 'check' : 'close'} size={12}/>{u.active ? 'Activo' : 'Inactivo'}
                    </span>
                  </td>
                  <td>
                    {!isMe(u) && (
                      <button onClick={() => toggleActive(u)} disabled={patchStatus[u.id]==='loading'} className="bc-btn"
                        style={{ padding:'3px 10px', fontSize:11, background:'transparent', border:'1px solid '+BC.border, borderRadius:4, color:BC.inkMuted }}>
                        {patchStatus[u.id]==='loading' ? '…' : u.active ? 'Desactivar' : 'Activar'}
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table></div>
        )}
      </div>
    </div>
  );
}

function AdminView({ user }) {
  const [tab, setTab] = React.useState('audit');
  const [audit, setAudit] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    let cancelled = false;
    async function fetchAudit() {
      try {
        const res = await fetch('/audit?limit=100');
        if (!res.ok) return;
        const data = await res.json();
        if (!cancelled) setAudit(data);
      } catch (_) {}
      if (!cancelled) setLoading(false);
    }
    fetchAudit();
    const t = setInterval(fetchAudit, 5000);
    return () => { cancelled = true; clearInterval(t); };
  }, []);

  const tabs = [
    { id: 'audit', label: 'Auditoría', icon: 'terminal', count: audit.length },
    ...(user.role === 'admin' ? [{ id: 'users', label: 'Usuarios', icon: 'user', count: null }] : []),
  ];

  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', background:BC.bg, minHeight:0 }}>
      <div style={{ padding:'18px 22px 0', background:BC.surface, borderBottom:'1px solid '+BC.border }}>
        <div style={{ fontSize:18, fontWeight:600, marginBottom:4, display:'flex', alignItems:'center', gap:10 }}>
          <Icon name="shield-admin" size={20} color={BC.brand}/>
          Administración
          <RoleBadge role={user.role}/>
        </div>
        <div style={{ fontSize:12, color:BC.inkSubtle, marginBottom:14 }}>Registro de auditoría de acciones de usuarios y comandos enviados a paneles.</div>
        <div style={{ display:'flex', gap:0, borderBottom:'none' }}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} className={'bc-btn bc-tab ' + (tab===t.id ? 'active' : '')}
              style={{ display:'flex', alignItems:'center', gap:8, padding:'10px 18px', border:'none', background:'transparent', color: tab===t.id ? BC.brand : BC.inkMuted, fontSize:13, fontWeight: tab===t.id ? 600 : 500, borderBottom:'2px solid '+(tab===t.id ? BC.brand : 'transparent'), marginBottom:-1, fontFamily:'inherit' }}>
              <Icon name={t.icon} size={14}/> {t.label}
              {t.count !== null && <span style={{ fontFamily:BC.mono, fontSize:10, padding:'1px 6px', borderRadius:4, background:tab===t.id ? BC.brandTint : BC.bgAlt, color:tab===t.id ? BC.brand : BC.inkSubtle }}>{t.count}</span>}
            </button>
          ))}
        </div>
      </div>

      <div className="bc-scroll" style={{ flex:1, overflowY:'auto', padding:22 }}>
        {tab === 'users' && <UsersTab user={user}/>}
        {tab === 'audit' && (
          <div style={{ background:BC.surface, border:'1px solid '+BC.border, borderRadius:8, boxShadow:BC.shadow }}>
            <div style={{ padding:'14px 18px', borderBottom:'1px solid '+BC.border }}>
              <div style={{ fontSize:14, fontWeight:600 }}>Registro de auditoría</div>
              <div style={{ fontSize:11, color:BC.inkSubtle, marginTop:2 }}>Acciones de usuarios y comandos enviados a paneles.</div>
            </div>
            {loading ? (
              <div style={{ padding:'40px 12px', textAlign:'center', color:BC.inkFaint, fontSize:12 }}>Cargando…</div>
            ) : (
              <div className="bc-admin-table-wrap"><table className="bc-tbl" style={{ width:'100%', borderCollapse:'collapse' }}>
                <thead><tr><th>Fecha</th><th>Acción</th><th>Usuario</th><th>Panel</th><th>Mensaje</th><th>Resultado</th></tr></thead>
                <tbody>
                  {audit.length === 0 && (
                    <tr><td colSpan={6} style={{ textAlign:'center', padding:'24px', color:BC.inkFaint }}>Sin registros de auditoría.</td></tr>
                  )}
                  {audit.map(a => {
                    const isError = !a.success;
                    return (
                      <tr key={a.id}>
                        <td style={{ fontFamily:BC.mono, fontSize:12, color:BC.inkSubtle }}>{formatTs(a.at, { full:true })}</td>
                        <td><span style={{ fontFamily:BC.mono, fontSize:11, padding:'2px 8px', background: isError ? BC.fire.bg : BC.brandTint, color: isError ? BC.fire.fg : BC.brandDeep, borderRadius:4 }}>{a.action}</span></td>
                        <td>{a.user}</td>
                        <td style={{ fontSize:12, color:BC.inkMuted }}>{a.client_description || '—'}</td>
                        <td style={{ fontFamily:BC.mono, fontSize:12, color:BC.ink }}>{a.message || '—'}</td>
                        <td>
                          <span style={{ display:'inline-flex', alignItems:'center', gap:5, fontSize:11, color: isError ? BC.fire.fg : BC.ok.fg }}>
                            <Icon name={isError ? 'warning' : 'check'} size={12}/>
                            {isError ? 'Error' : 'OK'}
                          </span>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table></div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

window.AdminView = AdminView;
