import React, { memo } from 'react';
import { areEqual } from 'react-window';
import { observer } from 'mobx-react-lite';
import { useVirtualGridRepeaterContext } from './VirtualGridRepeaterContext';
import { VirtualInternalMemoItem } from './VirtualInternalMemoItem';
import { VirtualItemProps } from './VirtualItem';

function _VirtualGridItem(props: VirtualItemProps) {
  const { columnIndex, rowIndex, style, ...timeoutProps } = props;

  const { state, itemKey, renderItem } = useVirtualGridRepeaterContext();

  const {
    calcGridProps: { columnCount },
    gridState: { gap },
  } = state;

  const index = rowIndex * columnCount + columnIndex;

  return (
    <div
      data-key={
        process.env.NODE_ENV === 'development'
          ? state._itemKeyRecycler(index)
          : undefined
      }
      style={{
        ...style,
        top: 0,
        left: 0,
        transform: `translate(${style.left}px, ${style.top}px)`,
      }}
    >
      <div
        data-hook="virtual-grid-item"
        data-index={`index-${index}`}
        style={{
          height: Number(style.height) - gap,
          width: Number(style.width) - gap,
        }}
      >
        <VirtualInternalMemoItem
          index={index}
          rowIndex={rowIndex}
          columnIndex={columnIndex}
          renderItem={renderItem}
          itemKey={itemKey}
          state={state}
          {...timeoutProps}
        />
      </div>
    </div>
  );
}

export const VirtualGridItem = memo(observer(_VirtualGridItem), areEqual);
