import { type VirtualItem } from '@tanstack/virtual-core';
import Stack from '@material-hu/mui/Stack';

import { type Acknowledgement } from '../../types';

import { KudosListItem } from './KudosListItem';

type KudosListVirtualizedProps = {
  acknowledgements: Acknowledgement[];
  virtualRows: VirtualItem[];
  rowVirtualizer: {
    getTotalSize: () => number;
    measureElement: (element: Element | null) => void;
  };
};

export const KudosListVirtualized = ({
  acknowledgements,
  virtualRows,
  rowVirtualizer,
}: KudosListVirtualizedProps) => {
  return (
    <Stack
      sx={{
        height: `${rowVirtualizer.getTotalSize()}px`,
        width: '100%',
        position: 'relative',
        overflow: 'hidden',
        flexShrink: 0,
      }}
    >
      {virtualRows.map(virtualRow => {
        const acknowledgement = acknowledgements[virtualRow.index];
        if (!acknowledgement) return null;
        return (
          <KudosListItem
            key={acknowledgement.id}
            virtualRow={virtualRow}
            acknowledgement={acknowledgement}
            measureElement={rowVirtualizer.measureElement}
          />
        );
      })}
    </Stack>
  );
};
