const MAX_ROWS = 10
const MAX_CELL_LEN = 30

function truncate(val: unknown): string {
  const s = val === null || val === undefined ? 'null' : String(val)
  return s.length > MAX_CELL_LEN ? s.slice(0, MAX_CELL_LEN) + '…' : s
}

interface ResultsTableProps {
  rows: Record<string, unknown>[]
  rowCount: number
}

export function ResultsTable({ rows, rowCount }: ResultsTableProps) {
  if (rows.length === 0) {
    return (
      <div className="text-xs text-gray-500 italic px-3 py-2 border border-white/[0.06] rounded-xl">
        No rows returned.
      </div>
    )
  }

  const columns = Object.keys(rows[0])
  const displayRows = rows.slice(0, MAX_ROWS)

  return (
    <div className="overflow-auto max-h-60 rounded-xl border border-white/[0.06]" style={{ fontSize: 11 }}>
      {rowCount > MAX_ROWS && (
        <div className="px-3 py-1 text-[10px] text-amber-400/70 bg-amber-500/5 border-b border-amber-500/10 shrink-0">
          Showing {MAX_ROWS} of {rowCount} rows
        </div>
      )}
      <table className="w-full font-mono border-collapse">
        <thead>
          <tr
            className="border-b border-white/[0.06] sticky top-0"
            style={{ background: 'var(--bg-tertiary)' }}
          >
            {columns.map((col) => (
              <th
                key={col}
                className="px-3 py-1.5 text-left text-[10px] font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap"
              >
                {col}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {displayRows.map((row, i) => (
            <tr
              key={i}
              className="border-b border-white/[0.03] hover:bg-white/[0.02] transition-colors"
            >
              {columns.map((col) => (
                <td
                  key={col}
                  className={`px-3 py-1.5 whitespace-nowrap ${
                    row[col] === null ? 'text-gray-600 italic' : 'text-gray-300'
                  }`}
                  title={row[col] !== null ? String(row[col]) : undefined}
                >
                  {truncate(row[col])}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
      <div
        className="px-3 py-1 text-[10px] text-gray-600 border-t border-white/[0.04]"
        style={{ background: 'var(--bg-tertiary)' }}
      >
        Showing {displayRows.length} of {rowCount} rows
      </div>
    </div>
  )
}
