import {
  cloneElement,
  CSSProperties,
  ReactElement,
  useCallback,
  useEffect,
  useRef,
  useState,
} from 'react';
import { useVirtualGridStateContext } from './VirtualGridStateContext';
import { VirtualTableRowMutatedState } from './VirtualTableRowMutatedState';

export function VirtualTableRowMutated(props: {
  index: number;
  style?: CSSProperties;
  itemKey?: (index: number) => number | string;
  rowIndex?: number;
  children: ReactElement[];
}) {
  const { children, index, style, itemKey, rowIndex } = props;

  const gridState = useVirtualGridStateContext();

  const element = children[index];

  const rowRef = useRef<HTMLTableRowElement>();

  const [state] = useState(
    () =>
      new VirtualTableRowMutatedState({
        rowRef,
        state: gridState,
        itemKey,
        index,
        rowIndex,
      }),
  );

  useEffect(() => {
    state.index = index;
  }, [index]);

  useEffect(() => {
    state.rowIndex = rowIndex;
  }, [rowIndex]);

  useEffect(() => {
    state.itemKey = itemKey;
  }, [itemKey]);

  useEffect(() => {
    state._measureRowContentsHeight();
  }, [rowRef, rowIndex]);

  useEffect(() => state.init(), []);

  const ref = useCallback((el: HTMLTableRowElement | undefined) => {
    rowRef.current = el;
  }, []);

  if (element == null) {
    return null;
  }

  return cloneElement(element, {
    style: { ...(element.props.style ?? {}), ...style },
    rowProps: {
      ...(element.props.rowProps ?? {}),
      'data-key':
        process.env.NODE_ENV === 'development' ? itemKey?.(index) : undefined,
      'data-index': `index-${index}`,
      ref,
    },
  });
}
