import { useCallback } from 'react';

import type { FC, RefObject } from 'react';
import type { TrackItemContext } from '../types';

import ItemPageActions from '~/src/components/ItemPage/components/ItemPageActions';
import { toShareUrl } from '~/src/components/ItemPage/utils';
import useSelectArtists from '~/src/hooks/useSelectArtists';
import { toPublicEndpoint } from '~/src/lib/getPublicEndpoint';
import { useI18n } from '~/src/lib/i18n';

export const TrackPageActions: FC<{
  itemContext: TrackItemContext;
  isOpen: boolean;
  actionButtonRef: RefObject<HTMLElement | null>;
  onClose: () => void;
}> = ({ itemContext, isOpen, actionButtonRef, onClose }) => {
  const { showArtistIds, hasArtistActions } = itemContext.config;
  const artists = useSelectArtists(showArtistIds);
  const artistNames = artists?.map(({ name }) => name).join(', ');
  const track = itemContext.data.item;
  const { t } = useI18n();

  const shareUrl = toShareUrl({
    isOwned: track.isOwned,
    pageBrand: track.pageBrand,
  });

  const shareText = track.name && `"${track.name}" by ${artistNames}`;

  return (
    <ItemPageActions
      isOpen={isOpen}
      item={track}
      targetElRef={actionButtonRef}
      onClose={onClose}
      userCanEdit={!!track.userCanEdit}
      pagePath={track.pagePath}
      shareUrl={shareUrl}
      shareText={shareText}
      toActionItems={useCallback(
        ({ sections }) => {
          if (track.userCanEdit) {
            sections[0].push({
              content: t('item.actions.viewInDashboard'),
              href: `/dashboard/song/${track.id}`,
              icon: 'chart',
              testId: 'viewInDashboard',
            });
          }

          const artistsToShow = hasArtistActions
            ? artists?.filter(({ deleted }) => !deleted)
            : undefined;

          if (artistsToShow?.length) {
            sections.push(
              artistsToShow.map(({ name, pagePath }) => ({
                content: name,
                href: toPublicEndpoint(pagePath),
                icon: 'person',
              }))
            );
          }

          return sections;
        },
        [track]
      )}
    />
  );
};
