const { useState, useMemo } = React;

function LogsPage({ logs, isLoading }) {
  const MX = window.MX, card = window.card, thStyle = window.thStyle;
  const styleInput = window.styleInput, btnGhost = window.btnGhost, btnSoft = window.btnSoft;

  const [filterTipo,    setFilterTipo]    = useState('');
  const [filterSucesso, setFilterSucesso] = useState('');
  const [filterText,    setFilterText]    = useState('');
  const [currentPage,   setCurrentPage]   = useState(1);
  const ITEMS = 8;

  const filtered = useMemo(() => logs.filter(log => {
    const matchTipo    = !filterTipo || log.tipo === filterTipo;
    const matchSucesso = filterSucesso === '' || log.sucesso === (filterSucesso === 'true');
    const txt = filterText.toLowerCase();
    const matchTxt = !txt || log.entidade.toLowerCase().includes(txt) || log.acao.toLowerCase().includes(txt) || log.usuario.toLowerCase().includes(txt);
    return matchTipo && matchSucesso && matchTxt;
  }), [logs, filterTipo, filterSucesso, filterText]);

  const totalPages    = Math.ceil(filtered.length / ITEMS);
  const paginatedLogs = filtered.slice((currentPage - 1) * ITEMS, currentPage * ITEMS);

  const formatDate = (str) => {
    const d = new Date(str);
    return d.toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', year: '2-digit', hour: '2-digit', minute: '2-digit' });
  };

  const stats = useMemo(() => ({
    total:      logs.length,
    success:    logs.filter(l => l.sucesso).length,
    fail:       logs.filter(l => !l.sucesso).length,
    empresa:    logs.filter(l => l.tipo === 'empresa').length,
  }), [logs]);

  const statCards = [
    { label: 'Total de registros', value: stats.total,   fg: MX.blue,   bg: MX.blueSoft   },
    { label: 'Com sucesso',        value: stats.success, fg: MX.green,  bg: MX.greenSoft  },
    { label: 'Com falha',          value: stats.fail,    fg: MX.red,    bg: MX.redSoft    },
    { label: 'De empresas',        value: stats.empresa, fg: MX.purple, bg: MX.purpleSoft },
  ];

  const filtersActive = !!(filterText || filterTipo || filterSucesso);

  return (
    <div style={{ padding: '36px 40px 60px', maxWidth: 1280 }}>
      {/* Header */}
      <div style={{ marginBottom: 26 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: MX.dim, letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: 6 }}>Histórico</div>
        <h1 style={{ margin: 0, fontSize: 28, fontWeight: 700, color: MX.text, letterSpacing: '-0.025em' }}>Logs de Atualizações</h1>
        <p style={{ margin: '6px 0 0', fontSize: 14, color: MX.muted }}>
          Acompanhe todas as alterações de categorias e situações.
        </p>
      </div>

      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
        {statCards.map(s => (
          <div key={s.label} style={{ ...card, padding: '20px 22px' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
              <span style={{ fontSize: 12, color: MX.muted, fontWeight: 500 }}>{s.label}</span>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: s.fg, flexShrink: 0 }}></span>
            </div>
            <div style={{ fontSize: 28, fontWeight: 700, color: MX.text, letterSpacing: '-0.03em' }}>{s.value}</div>
            <div style={{ marginTop: 12, height: 4, borderRadius: 99, background: s.bg, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: `${stats.total ? (s.value / stats.total) * 100 : 0}%`, background: s.fg, borderRadius: 99, transition: 'width 0.5s ease' }}></div>
            </div>
          </div>
        ))}
      </div>

      {/* Filters */}
      <div style={{ ...card, padding: '14px 16px', marginBottom: 16, display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
        <div style={{ position: 'relative', flex: 1, minWidth: 240 }}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke={MX.dim} strokeWidth="2" style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)' }}><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
          <input className="mx-input" placeholder="Buscar por entidade, ação ou usuário…" value={filterText} onChange={e => setFilterText(e.target.value)} style={{ ...styleInput, paddingLeft: 38 }} />
        </div>
        <select className="mx-select" value={filterTipo} onChange={e => setFilterTipo(e.target.value)} style={{ ...styleInput, flex: '0 0 auto', minWidth: 170 }}>
          <option value="">Todos os tipos</option>
          <option value="empresa">Empresa</option>
          <option value="entregador">Entregador</option>
        </select>
        <select className="mx-select" value={filterSucesso} onChange={e => setFilterSucesso(e.target.value)} style={{ ...styleInput, flex: '0 0 auto', minWidth: 180 }}>
          <option value="">Todos os resultados</option>
          <option value="true">Sucesso</option>
          <option value="false">Falha</option>
        </select>
        {filtersActive && (
          <button onClick={() => { setFilterText(''); setFilterTipo(''); setFilterSucesso(''); }} style={{ ...btnGhost, padding: '10px 14px' }}>Limpar</button>
        )}
      </div>

      {/* Table */}
      <div style={{ ...card, overflow: 'hidden', filter: isLoading ? 'blur(4px)' : 'none', transition: 'filter 0.3s' }}>
        <div style={{ padding: '16px 22px', borderBottom: `1px solid ${MX.border}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontWeight: 700, fontSize: 14, color: MX.text, display: 'flex', alignItems: 'center', gap: 9 }}>
            Registros
            <span style={{ background: MX.surface3, borderRadius: 99, padding: '2px 9px', fontSize: 11.5, color: MX.muted, fontWeight: 600 }}>{filtered.length}</span>
          </span>
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
            <thead>
              <tr>{['Data / Hora', 'Tipo', 'Entidade', 'Ação realizada', 'Resultado', 'Usuário'].map(col => <th key={col} style={thStyle}>{col}</th>)}</tr>
            </thead>
            <tbody>
              {filtered.length === 0 ? (
                <tr>
                  <td colSpan={6} style={{ textAlign: 'center', padding: '64px 24px', color: MX.dim, fontSize: 14 }}>
                    <div style={{ fontSize: 32, marginBottom: 10, opacity: 0.4 }}>◇</div>
                    Nenhum registro encontrado.
                  </td>
                </tr>
              ) : paginatedLogs.map((log, i) => (
                <tr key={log._id} style={{
                  background: i % 2 === 0 ? MX.surface : MX.surface2,
                  borderBottom: `1px solid ${MX.border}`,
                  opacity: log.sucesso ? 1 : 0.85,
                }}>
                  <td style={{ padding: '15px 22px', color: MX.muted, fontSize: 12, whiteSpace: 'nowrap' }} className="mono">{formatDate(log.dataHora)}</td>
                  <td style={{ padding: '15px 22px' }}>
                    <span style={{
                      display: 'inline-flex', alignItems: 'center', gap: 6,
                      background: log.tipo === 'empresa' ? MX.cyanSoft : MX.yellowSoft,
                      color: log.tipo === 'empresa' ? MX.cyan : MX.yellow,
                      borderRadius: 999, padding: '3px 11px', fontSize: 11.5, fontWeight: 600, whiteSpace: 'nowrap',
                    }}>
                      <span style={{ width: 5, height: 5, borderRadius: '50%', background: log.tipo === 'empresa' ? MX.cyan : MX.yellow, flexShrink: 0 }}></span>
                      {log.tipo === 'empresa' ? 'Empresa' : 'Entregador'}
                    </span>
                  </td>
                  <td style={{ padding: '15px 22px', color: MX.text, fontWeight: 500, maxWidth: 220, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={log.entidade}>{log.entidade}</td>
                  <td style={{ padding: '15px 22px', color: MX.muted }}>{log.acao}</td>
                  <td style={{ padding: '15px 22px' }}>
                    {log.sucesso ? (
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: MX.greenSoft, color: MX.green, borderRadius: 999, padding: '3px 11px', fontSize: 11.5, fontWeight: 600 }}>
                        <span style={{ width: 5, height: 5, borderRadius: '50%', background: MX.green }}></span>Sucesso
                      </span>
                    ) : (
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: MX.redSoft, color: MX.red, borderRadius: 999, padding: '3px 11px', fontSize: 11.5, fontWeight: 600 }}>
                        <span style={{ width: 5, height: 5, borderRadius: '50%', background: MX.red }}></span>Falha
                      </span>
                    )}
                  </td>
                  <td style={{ padding: '15px 22px', color: MX.muted, fontSize: 12.5 }}>{log.usuario}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {totalPages > 1 && (
          <div style={{ padding: '12px 22px', display: 'flex', justifyContent: 'center', gap: 8, borderTop: `1px solid ${MX.border}` }}>
            <button disabled={currentPage === 1} onClick={() => setCurrentPage(p => p - 1)} style={{ ...btnSoft, padding: '4px 10px', fontSize: 12 }}>Anterior</button>
            <span style={{ fontSize: 13, color: MX.dim, display: 'flex', alignItems: 'center' }}>Página {currentPage} de {totalPages}</span>
            <button disabled={currentPage === totalPages} onClick={() => setCurrentPage(p => p + 1)} style={{ ...btnSoft, padding: '4px 10px', fontSize: 12 }}>Próxima</button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { LogsPage });
