import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import AlertBar from '../components/AlertBar'
import DomainAttention from '../components/DomainAttention'
import HealthCards from '../components/HealthCards'
import IncidentsStrip from '../components/IncidentsStrip'
import KpiBar from '../components/KpiBar'
import ShortcutsRow from '../components/ShortcutsRow'
import { collectDomainAttention, loadConsoleHomeData } from '../lib/console-home'
import { MOCK_TENANTS } from '../mock'
import { apiGet } from '../lib/api'

function InfraTable({ tenants }) {
  return (
    <div className="card table-wrap">
      <h3 style={{ marginTop: 0, fontSize: '0.95rem' }}>Nós de infraestrutura</h3>
      <p style={{ fontSize: '0.82rem', color: 'var(--lb-text-secondary)', marginTop: 0 }}>
        Registo de VMs e serviços Ligbox (antigo menu Tenants no Desk).
      </p>
      <table className="data-table">
        <thead>
          <tr>
            <th>ID</th><th>Nome</th><th>IP</th><th>Papel</th><th>Desde</th>
          </tr>
        </thead>
        <tbody>
          {tenants.map((t) => (
            <tr key={t.id}>
              <td>{t.id}</td>
              <td><strong>{t.name}</strong></td>
              <td><code>{t.ip}</code></td>
              <td>{t.role}</td>
              <td>{t.created_at ? new Date(t.created_at).toLocaleDateString('pt-BR') : '—'}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

export default function ConsoleHome() {
  const [infra, setInfra] = useState(MOCK_TENANTS)
  const [home, setHome] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      const data = await loadConsoleHomeData()
      if (cancelled) return
      setHome(data)
      setLoading(false)
      try {
        const tData = await apiGet('/api/v1/tenants')
        if (!cancelled && tData?.tenants?.length) setInfra(tData.tenants)
      } catch { /* mock infra */ }
    })()
    return () => { cancelled = true }
  }, [])

  const auditTenants = home?.audit?.tenants || []
  const domainRows = collectDomainAttention(auditTenants)
  const usingMock = home ? !home.fromApi : true

  return (
    <>
      <h2 className="page-title">Console</h2>
      <p className="page-lead">
        Home unificada — KPIs, saúde da plataforma, alertas Wazuh 24h e infraestrutura.
        {usingMock ? ' Dados de demonstração até login API (JWT Desk).' : ' Dados live da API ops.'}
      </p>

      {loading ? <p className="status-pill">A carregar indicadores…</p> : null}

      {home ? (
        <>
          <KpiBar summary={home.summary} alertCounts={home.alertCounts} />
          <AlertBar counts={home.alertCounts} />

          <section className="wz-section">
            <h2 className="wz-section-title">Saúde da plataforma</h2>
            <HealthCards tenants={auditTenants} />
          </section>

          <IncidentsStrip incidents={home.incidents} />
          <DomainAttention rows={domainRows} />
          <ShortcutsRow />
          <InfraTable tenants={infra} />

          <div className="card">
            <h3 style={{ marginTop: 0, fontSize: '0.95rem' }}>Chamados recentes</h3>
            <ul className="timeline">
              {home.chamados.map((c) => (
                <li key={c.public_id}>
                  <Link to={`/chamados/${c.public_id}`}>{c.public_id}</Link> — {c.domain}{' '}
                  {c.max_severity ? <span className="badge badge-sev-high">L{c.max_severity}</span> : null}
                  {c.status ? <span className="badge badge-onboard">{c.status}</span> : null}
                </li>
              ))}
            </ul>
          </div>
        </>
      ) : null}
    </>
  )
}
