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

export const TableForceRenderIndexes = forwardRef<
  HTMLTableSectionElement,
  { children: ReactElement[] } & HTMLAttributes<HTMLTableSectionElement>
>((props, ref) => {
  const { children, style } = props;
  const { state } = useVirtualGridRepeaterContext();

  useEffect(() => {
    state.scrollHeight = style?.height;
  }, [style?.height]);

  return (
    <ForceRenderIndexesObserver
      ItemElementType={VirtualTableRow}
      contentsWrapper={({ contents, listAttributes }) => (
        <tbody
          key={props.id}
          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}
          style={{
            ...style,
            width: undefined, // we get the width from react-window but we want it to be auto, so we pass undefined
            position: 'relative',
            display: 'flex',
          }}
        >
          {contents}
        </tbody>
      )}
    >
      {children}
    </ForceRenderIndexesObserver>
  );
});
