import React from 'react'

function DataTable({ table, maxHeight = 320 }) {
  if (!table || !table.columns || !table.rows) {
    return <div className="empty-box">Sem dados.</div>
  }

  const MAX_RENDER_ROWS = 1200
  const rowsToRender = table.rows.length > MAX_RENDER_ROWS
    ? table.rows.slice(0, MAX_RENDER_ROWS)
    : table.rows
  const renderTruncated = rowsToRender.length < table.rows.length

  return (
    <div className="table-wrapper" style={{ maxHeight }}>
      <table>
        <thead>
          <tr>
            {table.columns.map((col) => (
              <th key={col}>{col}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rowsToRender.map((row, i) => (
            <tr key={i}>
              {table.columns.map((col) => (
                <td key={`${i}-${col}`}>{String(row[col] ?? '')}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
      {renderTruncated ? (
        <div className="table-hint">
          Renderizando {rowsToRender.length} de {table.rows.length} linhas recebidas para manter desempenho.
        </div>
      ) : null}
      {table.truncated ? (
        <div className="table-hint">Mostrando {table.returned_rows} de {table.total_rows} linhas.</div>
      ) : null}
    </div>
  )
}

export default React.memo(DataTable)
