import * as React from 'react';
import styles from './index.less';
import classnames from 'classnames';
import { getSelectedDimensions, getSelectionScope } from '../store/selectors';
import smoothScrollIntoView from 'smooth-scroll-into-view-if-needed';
import RuntimeContext from '../RuntimeContext';
import { inFrozenArea, tryMoveSelectedIntoView } from './helper';
interface Props {}

const Selected: React.FC<Props> = props => {
  const context = React.useContext(RuntimeContext);
  const dim = getSelectedDimensions(context!.store.getState());

  const ref = React.useRef<HTMLDivElement>(null);
  React.useEffect(() => {
    const state = context!.store.getState();
    const { freezeAt } = state;

    if (freezeAt.i < 0 && freezeAt.j < 0) {
      // 如果没有设置冻结, 则平滑滚动到位
      ref.current! && smoothScrollIntoView(ref.current!, { scrollMode: 'if-needed' });
      return;
    }

    // 注意: 本质上, tryMoveSelectedIntoView方法可能修改scrollX/scrollY, 所以与spreadSheet的同名方法类似
    if (tryMoveSelectedIntoView(context!, dim)) {
      // 当滚动后, 对于滚出来的新行, 可能存在重算的需求
      setTimeout(() => {
        context!.setSheetDimensions();
      }, 0);
    }
  }, [dim.top, dim.left, dim.width, dim.height]);

  const readyDimensions = context!.store.getState().readyDimensions;

  return React.useMemo(() => {
    const style = {
      width: dim.offsetWidth,
      height: dim.offsetHeight,
      left: dim.offsetLeft,
      top: dim.offsetTop,
    };

    const state = context!.store.getState();
    return (!inFrozenArea(state) &&
      readyDimensions) /*正在准备滚动,且不在Frozen区域,则隐藏(防止在冻结区域闪动)*/ ||
      dim.offsetWidth == 0 ||
      dim.offsetHeight == 0 ? null : (
      <div
        ref={ref}
        className={classnames(styles['container'], 'sheet-selected')}
        style={style}
      ></div>
    );
  }, [dim.offsetWidth, dim.offsetHeight, dim.offsetLeft, dim.offsetTop, readyDimensions]);
};

export default Selected;
