import { useEffect, useMemo, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { loadDiscoverEvents } from '../lib/events'
import { bucketLabel, filterByBucket } from '../lib/severity'

function fmtWhen(iso) {
  if (!iso) return '—'
  try {
    return new Date(iso).toLocaleString('pt-BR', { dateStyle: 'short', timeStyle: 'short' })
  } catch {
    return iso
  }
}

export default function Discover() {
  const [searchParams, setSearchParams] = useSearchParams()
  const bucket = searchParams.get('bucket')
  const [events, setEvents] = useState([])
  const [fromApi, setFromApi] = useState(false)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      setLoading(true)
      const { events: rows, fromApi: api } = await loadDiscoverEvents()
      if (!cancelled) {
        setEvents(rows)
        setFromApi(api)
        setLoading(false)
      }
    })()
    return () => { cancelled = true }
  }, [])

  const filtered = useMemo(() => {
    if (!bucket) return events
    return filterByBucket(events, bucket)
  }, [events, bucket])

  const clearFilter = () => setSearchParams({})

  return (
    <>
      <p><Link to="/">← Console</Link></p>
      <h2 className="page-title">Discover</h2>
      {bucket ? (
        <div className="discover-filter-banner card">
          <div>
            <strong>Filtro activo:</strong> {bucketLabel(bucket)} — {filtered.length} alerta(s) nas últimas 24h
          </div>
          <button type="button" className="btn" onClick={clearFilter}>Limpar filtro</button>
        </div>
      ) : (
        <p className="page-lead">
          Feed unificado Wazuh + onboard. Cada linha mostra <strong>agente</strong>, <strong>regra</strong> e ligação ao chamado.
          {fromApi ? '' : ' (demonstração — login API para dados live)'}
        </p>
      )}

      {loading ? (
        <p className="page-lead">Carregando eventos…</p>
      ) : filtered.length === 0 ? (
        <div className="card">
          <p style={{ margin: 0 }}>Nenhum alerta neste filtro nas últimas 24 horas.</p>
        </div>
      ) : (
        <div className="card table-wrap">
          <table className="data-table">
            <thead>
              <tr>
                <th>Quando</th>
                <th>Sev</th>
                <th>Agente</th>
                <th>Regra</th>
                <th>Descrição</th>
                <th>Domínio</th>
                <th>Chamado</th>
                <th>Wazuh</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((e) => (
                <tr key={e.id}>
                  <td>{fmtWhen(e.created_at)}</td>
                  <td>
                    {e.severity != null ? (
                      <Link to={`/discover?bucket=${e.severity >= 15 ? 'critical' : e.severity >= 12 ? 'high' : e.severity >= 7 ? 'medium' : 'low'}`}>
                        L{e.severity}
                      </Link>
                    ) : '—'}
                  </td>
                  <td><code>{e.agent || '—'}</code></td>
                  <td>{e.rule_id ? <code>{e.rule_id}</code> : '—'}</td>
                  <td>{e.summary || e.event_type}</td>
                  <td>{e.domain || '—'}</td>
                  <td>
                    {e.chamado_public_id ? (
                      <Link to={`/chamados/${e.chamado_public_id}`}>{e.chamado_public_id}</Link>
                    ) : '—'}
                  </td>
                  <td>
                    {e.source === 'wazuh' ? (
                      <a href="https://wazuh.itecnologys.com/" target="_blank" rel="noreferrer noreferrer" className="btn" style={{ padding: '0.2rem 0.5rem', fontSize: '0.75rem' }}>
                        Abrir
                      </a>
                    ) : (
                      <span className={`badge badge-${e.source}`}>{e.source}</span>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </>
  )
}
