import { type ReactNode } from 'react';
import { ItemTypes } from '@theorchard/songwhip-api';

import type { SelectedCustomPage, SelectedItem } from '~/src/store/types';
import type { PageSectionComponent } from '../types';
import type { PageTitleSectionProps } from './types';

import { ArtistNames, PageTitleText } from './components';

export const PageTitleSection: PageSectionComponent<PageTitleSectionProps> = ({
  layoutData,

  // section props
  customArtistNames,
  withArtistLinks = false,
  isArtistNamesHidden = false,
}) => {
  const { item } = layoutData;

  const sectionProps = {
    customArtistNames,
    withArtistLinks,
    isArtistNamesHidden,
  };

  const title = resolveTitle(item, sectionProps);
  const subtitle = resolveSubtitle(item, sectionProps);

  if (!title) return;

  return (
    <div data-testid="pageTitleSection">
      <PageTitleText text={title} subtitle={subtitle} />
    </div>
  );
};

const resolveTitle = (
  item: SelectedItem | SelectedCustomPage,
  { customArtistNames }: PageTitleSectionProps
) => {
  if (item.type === ItemTypes.ARTIST) return customArtistNames || item.name;
  return item.name;
};

const resolveSubtitle = (
  item: SelectedItem | SelectedCustomPage,
  {
    customArtistNames,
    withArtistLinks,
    isArtistNamesHidden,
  }: PageTitleSectionProps
): ReactNode => {
  if (item.type === ItemTypes.ARTIST || isArtistNamesHidden) return;

  // custom artist names take precedence over actual artist names
  return (
    customArtistNames || (
      <ArtistNames artistIds={item.artistIds} withLinks={withArtistLinks} />
    )
  );
};
