import React, { forwardRef, HTMLAttributes, ReactElement } from 'react';
import { useVirtualGridRepeaterContext } from './VirtualGridRepeaterContext';
import { VirtualGridItem } from './VirtualGridItem';
import { ForceRenderIndexesObserver } from './ForceRenderIndexes';

export const GridForceRenderIndexes = forwardRef<
  HTMLDivElement,
  { children: ReactElement[] } & HTMLAttributes<HTMLDivElement>
>(({ children, ...props }, ref) => {
  const { state } = useVirtualGridRepeaterContext();

  return (
    <ForceRenderIndexesObserver
      ItemElementType={VirtualGridItem}
      contentsWrapper={({ contents, listAttributes }) => (
        <div
          data-hook="virtual-inner-element"
          data-count={state.gridState.itemsToRenderCount}
          ref={(el) => {
            if (typeof ref === 'function') {
              ref(el);
            } else if (ref) {
              ref.current = el;
            }
            state.innerElement = el;
          }}
          {...listAttributes}
          {...props}
        >
          {contents}
        </div>
      )}
    >
      {children}
    </ForceRenderIndexesObserver>
  );
});
