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

import logWebUserEvent from '@/logging/logWebUserEvent';

import { getAnalyticsToolName } from '../EditModeContext';
import { getEditType } from '../getEditType';
import { CanvasRegion } from './CanvasRenderer';
import { EditCanvasRenderContext } from './EditCanvasRenderContext';
import makeRoundedRectRegion, {
  RectRenderParameters,
} from './makeRoundedRectRegion';

export default function makePreviewClipRegions({
  previewEdit,
  setPreviewEdit,
  arrangedClips,
  clipId,
  timing,
  pxPerBeat,
  scrollX,
  sectionY,
  waveformY,
  waveformHeight,
  sectionHeight,
  beatsToCanvasPx,
  applyPreviewEdit,
  editSessionId,
}: EditCanvasRenderContext): {
  background: CanvasRegion[];
  foreground: CanvasRegion[];
} {
  if (!previewEdit) {
    return {
      background: [],
      foreground: [],
    };
  }
  const foreground: CanvasRegion[] = [];
  const background: CanvasRegion[] = [];

  arrangedClips
    .filter((arrangedClip) => arrangedClip.clipId !== clipId)
    .forEach((arrangedClip) => {
      const sharedProps: Pick<
        RectRenderParameters,
        'startBeats' | 'endBeats' | 'pxPerBeat' | 'scrollX' | 'y'
      > = {
        startBeats: getBeatsFromZero(arrangedClip.startSeconds, timing),
        endBeats: getBeatsFromZero(arrangedClip.endSeconds, timing),
        pxPerBeat: pxPerBeat,
        scrollX: scrollX,
        y: sectionY - 1,
      };
      const startX = beatsToCanvasPx(sharedProps.startBeats);
      const endX = beatsToCanvasPx(sharedProps.endBeats);
      background.push(
        makeRoundedRectRegion({
          ...sharedProps,
          height: waveformY + waveformHeight - sectionY + 2,
          color: '#e64739',
          borderColor: '#ffffff',
          borderWidth: 2,
        })
      );
      background.push(
        makeRoundedRectRegion({
          ...sharedProps,
          height: sectionHeight + 1,
          color: 'transparent',
          text: arrangedClip.title.toUpperCase() + ` #${previewEdit.index + 1}`,
        })
      );
      if (endX - startX < 32) return;
      foreground.push({
        touchTarget: {
          bounds: {
            top: sectionY,
            bottom: sectionY + sectionHeight,
            left: endX - 30,
            right: endX,
          },
          onMouseDown: () => {
            setPreviewEdit(null);
          },
          hoverCursor: 'pointer',
        },
        render: (ctx: CanvasRenderingContext2D, hovered) => {
          ctx.fillStyle = '#e64739';
          ctx.fillRect(endX - 30, sectionY, 28, sectionHeight);

          ctx.fillStyle = '#ffffff' + (hovered ? '' : '88');
          ctx.font = '14px "Input Sans", monospace';
          ctx.textAlign = 'center';
          ctx.textBaseline = 'middle';
          ctx.fillText(`×`, endX - 15, sectionY + sectionHeight / 2);
        },
      });
      if (endX - startX < 68) return;
      foreground.push({
        touchTarget: {
          bounds: {
            top: waveformY + waveformHeight - 32,
            bottom: waveformY + waveformHeight - 8,
            left: endX - 60,
            right: endX - 8,
          },
          onMouseDown: () => {
            logWebUserEvent({
              actionName: 'ApplyEdit',
              context: {
                insertedClipId: previewEdit.clipId,
                editTool: getAnalyticsToolName(
                  previewEdit.clip
                    ? getEditType(previewEdit.clip) || 'none'
                    : 'none'
                ),
                editSessionId: editSessionId || 'MISSING_EDIT_SESSION_ID',
                editingClipId: clipId,
                actionIndex: -1, // todo?
              },
            });
            applyPreviewEdit();
          },
          hoverCursor: 'pointer',
        },
        render: (ctx: CanvasRenderingContext2D, hovered) => {
          ctx.fillStyle = '#ffffff' + (hovered ? '' : '88');
          ctx.beginPath();
          ctx.roundRect(endX - 60, waveformY + waveformHeight - 32, 52, 24, 12);
          ctx.closePath();
          ctx.fill();

          ctx.fillStyle = '#000000';
          ctx.font = '12px "PP Neue Montreal", sans-serif';
          ctx.textAlign = 'center';
          ctx.textBaseline = 'middle';
          ctx.fillText(`Apply`, endX - 34, waveformY + waveformHeight - 20);
        },
      });
    });
  return {
    background,
    foreground,
  };
}
