import { getBeatsFromZero } from '@suno/studiokit/timeMapping';

import { encodeTimeFormat } from '@/utils/utils';

import { CanvasRegion } from './CanvasRenderer';
import { EditCanvasRenderContext } from './EditCanvasRenderContext';

export default function makePlayheadRegion({
  playbackContext,
  timing,
  beatsToCanvasPx,
  sectionY,
  handleClickDrag,
  songEndSeconds,
  timelineWrapperRect,
  frameCountRef,
}: EditCanvasRenderContext): CanvasRegion {
  const smallCornerRadius = 4;
  const labelHeight = 16;
  const currentTimeSeconds = playbackContext.getCurrentTime();
  const playheadBeats = getBeatsFromZero(currentTimeSeconds, timing);

  const playheadY = sectionY - 26;
  const playheadCenterX = beatsToCanvasPx(playheadBeats);
  const height = timelineWrapperRect.height - playheadY;

  const width = 50;

  return {
    touchTarget: {
      bounds: {
        top: playheadY,
        bottom: playheadY + labelHeight,
        left: playheadCenterX - width / 2,
        right: playheadCenterX + width / 2,
      },
      hoverCursor: 'grab',
      dragCursor: 'grabbing',
      onMouseDown: handleClickDrag(() => ({
        onMouseMove: ({ moveSeconds }) => {
          playbackContext.seek(
            Math.min(Math.max(0, moveSeconds), songEndSeconds)
          );
          frameCountRef.current++;
        },
      })),
    },
    render: (ctx) => {
      ctx.fillStyle = '#00000066';
      ctx.fillRect(playheadCenterX - 2, playheadY, 4, height);
      ctx.fillStyle = '#FFFFFF';
      ctx.beginPath();
      ctx.roundRect(
        playheadCenterX - width / 2,
        playheadY,
        width,
        labelHeight,
        6
      );
      ctx.closePath();
      ctx.fill();

      ctx.beginPath();
      ctx.moveTo(playheadCenterX - 1, playheadY + labelHeight);
      ctx.arc(
        playheadCenterX - (1 + smallCornerRadius),
        playheadY + labelHeight + smallCornerRadius,
        smallCornerRadius,
        Math.PI * 1.5,
        Math.PI * 2,
        false
      );
      ctx.lineTo(playheadCenterX - 1, playheadY + height);
      ctx.lineTo(playheadCenterX + 1, playheadY + height);
      ctx.lineTo(
        playheadCenterX + 1,
        playheadY + labelHeight + smallCornerRadius
      );
      ctx.arc(
        playheadCenterX + (1 + smallCornerRadius),
        playheadY + labelHeight + smallCornerRadius,
        smallCornerRadius,
        Math.PI * 1,
        Math.PI * 1.5,
        false
      );
      ctx.lineTo(playheadCenterX - 1, playheadY + labelHeight);
      ctx.closePath();
      ctx.fill();

      ctx.fillStyle = '#333333';
      ctx.font = '10px "Input Sans", monospace';
      ctx.textAlign = 'center';

      ctx.fillText(
        encodeTimeFormat(currentTimeSeconds) || '0:00',
        playheadCenterX,
        playheadY + labelHeight * 0.55,
        40
      );
    },
  };
}
