import { noop } from 'lodash-es';

import CreateFormContext from '@/app/(root)/create/v2/CreateFormContext';
import { ConditionTypes } from '@/app/(root)/create/v2/types';
import { useContextSelector } from '@/hooks/useContextSelector';
import { DownloadIcon, MusicIcon, RemixIcon } from '@/icons';

import { ContextMenuGroup, ContextMenuItem } from '../contextMenu/ContextMenu';
import { getPlaintextLyrics } from '../edit2025/lyrics/getPlaintextLyrics';
import SpinnerSVG from '../svg/SpinnerSVG';
import { Tooltip } from '../tooltip/Tooltip';
import StudioContext from './StudioContext';
import DEFAULT_STATE from './defaultState';
import getStateAlignedLyrics from './getStateAlignedLyrics';
import { getTrimmedUnmutedTracks } from './helpers/getTrimmedUnmutedTracks';
import { getDerivedTiming, getSelectedClips } from './selectors';
import { StudioProjectState } from './types';
import { useLogStudioWebUserEvent } from './useLogStudioWebUserEvent';
import { StudioLayoutManagerContext } from './useStudioLayoutManager';

interface StudioSelectionActionsProps {
  downloadingWAV: boolean;
  handleDownloadAudio: () => Promise<void>;
  enableMIDI: boolean;
  gettingMIDI: boolean;
  handleGetMIDI: () => Promise<void>;
  onClose: () => void;
}

export default function StudioSelectionActions({
  downloadingWAV,
  handleDownloadAudio,
  enableMIDI,
  gettingMIDI,
  handleGetMIDI,
  onClose,
}: StudioSelectionActionsProps) {
  const stateRef = useContextSelector(
    StudioContext,
    (context) => context.stateRef
  );
  const setCreatePanelExpanded = useContextSelector(
    StudioLayoutManagerContext,
    (context) => context?.setCreatePanelExpanded ?? noop
  );
  const selectionStartBeats = useContextSelector(StudioContext, (context) =>
    context.state.selection.anchorBeats < context.state.selection.focusBeats
      ? context.state.selection.anchorBeats
      : context.state.selection.focusBeats
  );
  const selectionEndBeats = useContextSelector(StudioContext, (context) =>
    context.state.selection.anchorBeats > context.state.selection.focusBeats
      ? context.state.selection.anchorBeats
      : context.state.selection.focusBeats
  );
  const projectId = useContextSelector(
    StudioContext,
    (context) => context.projectId
  );
  const studioProjectId = useContextSelector(
    StudioContext,
    (context) => context.studioProjectId
  );
  const alignedLyricsByClipId = useContextSelector(
    StudioContext,
    (context) => context.alignedLyricsByClipId
  );
  const addStudioProjectStateCondition = useContextSelector(
    CreateFormContext,
    (context) => context.addStudioProjectStateCondition
  );

  const logStudioWebUserEvent = useLogStudioWebUserEvent();

  return (
    <ContextMenuGroup>
      <ContextMenuItem
        icon={<RemixIcon className='h-4 w-4' />}
        onClick={() => {
          const tracks = getTrimmedUnmutedTracks(stateRef.current);
          const timing = getDerivedTiming(stateRef.current);
          const state: StudioProjectState = {
            ...DEFAULT_STATE,
            tracks,
            timing: {
              type: 'manual',
              ...timing,
            },
          };
          setCreatePanelExpanded(true);
          addStudioProjectStateCondition(state, ConditionTypes.COVER, {
            projectId: projectId,
            studioProjectId: studioProjectId,
            startBeats: selectionStartBeats,
            endBeats: selectionEndBeats,
            lyrics: getPlaintextLyrics(
              getStateAlignedLyrics(state, alignedLyricsByClipId, {
                startBeats: selectionStartBeats,
                endBeats: selectionEndBeats,
              })
            ),
          });
          onClose();
        }}
      >
        Remix Selection
      </ContextMenuItem>
      <ContextMenuItem
        disabled={downloadingWAV}
        icon={
          downloadingWAV ? (
            <SpinnerSVG className='h-4 w-4' />
          ) : (
            <DownloadIcon className='h-4 w-4' />
          )
        }
        onClick={async () => {
          logStudioWebUserEvent({
            actionName: 'StudioDownloadSelection',
            context: {
              format: 'wav',
              selectedClipIds: getSelectedClips(stateRef.current)
                .map((clip) => clip.clipId)
                .filter(Boolean) as string[],
            },
          });
          handleDownloadAudio();
        }}
      >
        Download .WAV
      </ContextMenuItem>
      {enableMIDI && (
        <Tooltip label='10 credits' placement='right'>
          <ContextMenuItem
            disabled={gettingMIDI}
            icon={
              gettingMIDI ? (
                <SpinnerSVG className='h-4 w-4' />
              ) : (
                <MusicIcon className='h-4 w-4' />
              )
            }
            onClick={async () => {
              logStudioWebUserEvent({
                actionName: 'StudioDownloadSelection',
                context: {
                  format: 'midi',
                  selectedClipIds: getSelectedClips(stateRef.current)
                    .map((clip) => clip.clipId)
                    .filter(Boolean) as string[],
                },
              });
              handleGetMIDI();
            }}
          >
            Get MIDI
          </ContextMenuItem>
        </Tooltip>
      )}
    </ContextMenuGroup>
  );
}
