import * as React from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
import './List.css';

const books = new Array(100_000).fill(null).map((_, id) => ({
  id,
  title: 'Design Patterns',
  author: 'Erich Gamma',
  isbn: '978-0201633610',
  rating: 5,
}));

const List: React.FC = () => {
  const parentRef = React.useRef<HTMLDivElement>(null);

  const rowVirtualizer = useVirtualizer({
    count: books.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 40,
  });

  return (
    <div ref={parentRef} className="table-wrap">
      <table className="v-table">
        <thead className="v-head">
          <tr className="v-row" style={{ position: 'relative' }}>
            <th className="v-cell col-wide">Titel</th>
            <th className="v-cell">Autor</th>
            <th className="v-cell">ISBN</th>
            <th className="v-cell">Bewertung</th>
          </tr>
        </thead>

        <tbody
          className="v-body"
          style={{ height: rowVirtualizer.getTotalSize() }}
        >
          {rowVirtualizer.getVirtualItems().map((vRow) => {
            const book = books[vRow.index];
            return (
              <tr
                key={vRow.key}
                className="v-row"
                style={{
                  transform: `translateY(${vRow.start}px)`,
                  height: vRow.size,
                }}
              >
                <td className="v-cell col-wide">{book.title}</td>
                <td className="v-cell">{book.author}</td>
                <td className="v-cell">{book.isbn}</td>
                <td className="v-cell">{'★'.repeat(book.rating)}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};

export default List;
