import { EditCanvasRenderContext } from './EditCanvasRenderContext';

let draggingScrollBar = false;

export default function makeScrollbarRegion({
  timelineWrapperRect,
  songStartBeats,
  songEndBeats,
  scrollXRef,
  pxPerBeatRef,
  frameCountRef,
}: EditCanvasRenderContext) {
  const timelineStartBeats = scrollXRef.current / pxPerBeatRef.current;
  const timelineEndBeats =
    timelineStartBeats + timelineWrapperRect.width / pxPerBeatRef.current;

  let scrollBarX = Math.max(
    2,
    (Math.max(songStartBeats, timelineStartBeats) / songEndBeats) *
      timelineWrapperRect.width -
      4
  );

  const scrollBarTargetWidth = Math.min(
    timelineWrapperRect.width - 4 - scrollBarX,
    ((Math.min(songEndBeats, timelineEndBeats) -
      Math.max(songStartBeats, timelineStartBeats)) /
      songEndBeats) *
      timelineWrapperRect.width -
      4
  );

  const scrollBarWidth = Math.max(16, scrollBarTargetWidth);
  scrollBarX = Math.max(
    2,
    scrollBarX - (scrollBarWidth - scrollBarTargetWidth) / 2
  );

  const hideScrollbar = scrollBarWidth >= timelineWrapperRect.width - 6;

  if (hideScrollbar) return {};

  return {
    touchTarget: {
      bounds: {
        left: scrollBarX,
        right: scrollBarX + scrollBarWidth,
        top: timelineWrapperRect.height - 12,
        bottom: timelineWrapperRect.height - 4,
      },
      onMouseDown: (e: MouseEvent) => {
        const startX = e.clientX;
        const originalScrollX = scrollXRef.current;
        draggingScrollBar = true;
        const handleMouseMove = (e: MouseEvent) => {
          const scrollbarPxPerBeat =
            (timelineWrapperRect.width - 4) / (songEndBeats - songStartBeats);
          const deltaXFromStart = e.clientX - startX;
          const beatsDragged = deltaXFromStart / scrollbarPxPerBeat;
          const timelinePxDragged = beatsDragged * pxPerBeatRef.current;
          scrollXRef.current = originalScrollX + timelinePxDragged;
          frameCountRef.current++;
        };
        const handleMouseUp = () => {
          draggingScrollBar = false;
          window.removeEventListener('mouseup', handleMouseUp);
          window.removeEventListener('mousemove', handleMouseMove);
        };
        window.addEventListener('mouseup', handleMouseUp);
        window.addEventListener('mousemove', handleMouseMove);
      },
    },

    render: (ctx: CanvasRenderingContext2D, hovered: boolean) => {
      ctx.fillStyle = '#ffffff' + (hovered || draggingScrollBar ? '99' : '22');
      ctx.beginPath();
      ctx.roundRect(
        scrollBarX,
        timelineWrapperRect.height - 12,
        scrollBarWidth,
        8,
        4
      );
      ctx.fill();
    },
  };
}
