import { ComponentProps, DisplayComponent, FSComponent, Subscribable, VNode } from '@microsoft/msfs-sdk';
import { Controls } from '../controls/controls';

interface TLRProps extends ComponentProps {
  content: Subscribable<string>;
  reload: () => void;
  position: Subscribable<number>;
}

export class TLR extends DisplayComponent<TLRProps> {
  private containerRef = FSComponent.createRef<HTMLDivElement>();

  constructor(props: TLRProps) {
    super(props);
  }

  private defineDragScroll = (horizontalScroll = true, verticalScroll = true): void => {
    if (!this.containerRef.instance) return;

    let pos = { top: 0, left: 0, x: 0, y: 0 };

    const mouseDownHandler = (e: MouseEvent) => {
      pos = {
        left: this.containerRef.instance.scrollLeft,
        top: this.containerRef.instance.scrollTop,
        x: e.clientX,
        y: e.clientY,
      };
      document.addEventListener('mousemove', mouseMoveHandler);
      document.addEventListener('mouseup', mouseUpHandler);
      document.addEventListener('mouseleave', mouseUpHandler);
    };

    const mouseMoveHandler = (e: MouseEvent) => {
      const dx = e.clientX - pos.x;
      const dy = e.clientY - pos.y;

      if (verticalScroll) {
        this.containerRef.instance.scrollTop = pos.top - dy;
      }
      if (horizontalScroll) {
        this.containerRef.instance.scrollLeft = pos.left - dx;
      }
    };

    const mouseUpHandler = (e: MouseEvent) => {
      document.removeEventListener('mousemove', mouseMoveHandler);
      document.removeEventListener('mouseup', mouseUpHandler);
      document.removeEventListener('mouseleave', mouseUpHandler);
    };

    this.containerRef.instance.addEventListener('mousedown', mouseDownHandler);
  };

  public render = (): VNode => (
    <>
      <div ref={this.containerRef} id="KH_FE_FPLAN" class="p2">
        <div id="TLR">
          <div>
            <pre>{this.props.content}</pre>
          </div>
        </div>
      </div>
      <Controls containerRef={this.containerRef} position={this.props.position} reload={this.props.reload} page={1} />
    </>
  );

  public onAfterRender = (): void => {
    this.defineDragScroll();
  };
}
