// Admin view: audit log

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 },
  ];

  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}
              <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 === '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;
