import { observer } from 'mobx-react-lite';
import { ComponentProps, memo } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { BaseButtonProps } from '@/components/button/Button';
import { useBreakpointMd } from '@/hooks/useBreakpoint';
import { Clip } from '@/state/clipStore';

import { SongMenuWithContext } from './SongMenuWithContext';

type SongMenuForMultiselectProps = Partial<
  BaseButtonProps & ComponentProps<'button'>
> & {
  clip: Clip;
  sectionName?: string;
  onOpenChange?: (open: boolean) => void;
  rowKey?: string;
};

/**
 * Wrapper around SongMenuWithContext that adds multi-select handling.
 * Use this in contexts where multi-select is supported (e.g., GridList).
 */
export const SongMenuWithContextForMultiselect = memo(
  observer(function SongMenuWithContextForMultiselect({
    clip,
    sectionName,
    onOpenChange,
    rowKey,
    ...buttonProps
  }: SongMenuForMultiselectProps) {
    const { menus } = useStores();
    const isMobile = !useBreakpointMd();

    // TODO: this is a hack to allow multi-select to work with the song menu in GridList
    // we should migrate over to the MultiSelectContextProvider instead and remove this
    const handleMenuButtonSelection = (e: React.PointerEvent) => {
      if (!isMobile) {
        // Always stop propagation to prevent GridList from handling the click
        if ([...(menus.selectedClipIds || [])].includes(clip?.id)) {
          e.stopPropagation();
        }

        // Only update selection if clip is not already selected
        // or if it's a single selection and not the current clip
        if (
          ![...(menus.selectedClipIds || [])].includes(clip?.id) ||
          ([...(menus.selectedClipIds || [])].length === 1 &&
            menus.currentClip?.id !== clip.id)
        ) {
          menus.setCurrentClip(clip);
          if (rowKey || clip?.id) {
            menus.setSelected(new Set([rowKey || clip?.id]));
          }
        }
      }
    };

    return (
      <div className='contents' onPointerDown={handleMenuButtonSelection}>
        <SongMenuWithContext
          clip={clip}
          sectionName={sectionName}
          onOpenChange={onOpenChange}
          {...buttonProps}
        />
      </div>
    );
  })
);
