import { CSSProperties, memo, useEffect, useState } from 'react';
import { RenderItem } from './RenderItem';
import { VirtualGridRepeaterState } from './VirtualGridRepeaterState';
import { TimeoutProps } from 'react-transition-group/Transition';
import { runInAction } from 'mobx';
import { observer } from 'mobx-react-lite';

export type VirtualInternalMemoItemProps = {
  index: number;
  rowIndex: number;
  columnIndex: number;
  renderItem: RenderItem;
  state: VirtualGridRepeaterState;
  itemKey: (params: {
    columnIndex: number;
    rowIndex: number;
  }) => string | number;
  style?: CSSProperties;
} & Partial<TimeoutProps<undefined>>;

const _VirtualInternalMemoItem = ({
  index,
  rowIndex,
  columnIndex,
  renderItem,
  itemKey,
  state,
  style,
  ...timeoutProps
}: VirtualInternalMemoItemProps) => {
  const [ready, setReady] = useState(() =>
    runInAction(() => !state.gridState.toolbar.isScrolling),
  );

  useEffect(() => {
    if (!ready) {
      // An optimization for rendering the item lazily when scrolling fast (this is experimental and might be changed)
      const id = window.requestAnimationFrame(() => {
        setReady(true);
      });

      return () => {
        window.cancelAnimationFrame(id);
      };
    }

    return undefined;
  }, [ready]);

  return renderItem(index, {
    timeoutProps,
    style,
    itemKey: state._itemKeyRecycler,
    index2d: { rowIndex, columnIndex },
  });
};

export const VirtualInternalMemoItem = memo(
  observer(_VirtualInternalMemoItem),
  (a, b) =>
    a.index === b.index &&
    a.in === b.in &&
    a.renderItem === b.renderItem &&
    a.itemKey === b.itemKey &&
    a.style === b.style,
);
