'use client';

import { useCallback, useMemo } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { getSunoShortType } from '@/components/song/songUtils';
import { ContextType } from '@/logging/contextTypes';
import { CAROUSEL_ITEM_GAP_MULTIPLIER } from '@/utils/constants';

import SongCard from '../../song/SongCard';

export const SongCardItem = ({
  index,
  style,
  data,
}: {
  index: number;
  style: any;
  data: any;
}) => {
  const {
    elements,
    playbar,
    setPreviewClip,
    contextId,
    contextType = ContextType.DiscoverCarousel,
    styleType,
  } = data;
  const { clips } = useStores();
  const clip = clips.clipById[elements[index].id];

  const styleProps = useMemo(
    () => ({
      ...style,
      left:
        index === 0 ? style.left : style.left * CAROUSEL_ITEM_GAP_MULTIPLIER, // add a bit more padding for SongCards on homepage
    }),
    [style, index]
  );

  const handleClick = useCallback(() => {
    if (playbar.clip?.id === clip?.id) {
      playbar.togglePlay();
      return;
    }
    setPreviewClip(clip);
    playbar.root.queue.setPlayContext({
      clips: elements,
      currentIndex: index,
      contextId,
      contextType,
    });
    playbar.playClip(clip);
  }, [playbar, clip, setPreviewClip, elements, index, contextId, contextType]);

  return (
    <div style={styleProps}>
      <SongCard
        onClick={handleClick}
        onPlay={handleClick}
        clip={clip}
        contextId={contextId}
        sunoShortType={getSunoShortType(clip)}
        styleType={styleType}
        carouselIndex={data.carouselIndex}
        carouselSectionName={data.sectionName}
        index={index}
      />
    </div>
  );
};
