import * as React from 'react';
import {
  CSSProperties,
  FunctionComponent,
  useContext,
  useEffect,
  useCallback,
} from 'react';
import { EditorViewContext } from '../../contexts/EditorViewContext';
import { useRefEffect, useOnClickInside, useMeasure } from '../../hooks';
import { css } from '../../utilities';
import { WritingMode, from } from '../../config/writingMode';

import './OverflowGuard.css';

type Props = {
  // none
};

export const OverflowGuard: FunctionComponent<Props> = (props) => {
  const { children } = props;

  const {
    writingMode,
    editor,
    leftToRightHorizontalWriting,
    widthKey,
    heightKey,
  } = useContext(EditorViewContext);

  const [ref, rect] = useMeasure();

  const onWheel = useCallback(
    (evt: React.WheelEvent<HTMLDivElement>) => {
      evt.stopPropagation();
      const { deltaY } = evt;

      const top = editor.getScrollTop();
      editor.setScrollTop(Math.max(0, top + deltaY / 4));
    },
    [editor]
  );

  const containerRef = useRefEffect<HTMLDivElement>((container) => {
    ref(container);
  });

  // useOnClickInside(containerRef, (evt) => {
  //   // evt.stopPropagation();
  //   evt.preventDefault();
  //   editor.focus();
  // });

  useEffect(() => {
    const width = rect[widthKey];
    const height = rect[heightKey];

    editor.layout({
      width,
      height,
    });
  }, [rect, writingMode, editor, widthKey, heightKey]);

  const style: CSSProperties = {
    width: `${rect.width}px`,
    height: `${rect.height}px`,
    writingMode: from(writingMode).toCSSProperties(),
  };

  const classNames = css('overflow-guard', from(writingMode).toString());
  return (
    <div
      className="monaka-editor"
      ref={containerRef}
      style={{
        width: '100%',
        height: '100%',
      }}
      onWheel={onWheel}
    >
      <div className={classNames} style={style}>
        {children}
      </div>
    </div>
  );
};
