import type { RosterArtist } from '../../components';
import type { CreateFlowStage } from '../../components/CreateFlow/types';

import { useAppRouter } from '~/src/lib/router2';
import { createArtistApi } from '~/src/lib/songwhipApi/artists';
import { useSelector } from '~/src/store/redux';
import {
  selectSessionUserId,
  selectUserCountry,
} from '~/src/store/session/selectors';
import { ArtistSearch } from '../../components';

export const ChooseArtistStage: CreateFlowStage = () => {
  const router = useAppRouter();

  const userId = useSelector(selectSessionUserId);
  const country = useSelector(selectUserCountry);

  if (!userId) {
    throw new Error('User must be logged in to create a content link');
  }

  const handleSelectArtist = async ({ id }: RosterArtist) => {
    const artist = await createArtistApi({ rosterArtistId: id, country });

    await router.setQuery({
      stage: 'destination',
      artistId: String(artist.id),
      artistPath: artist.path,
    });
  };

  return <ArtistSearch userId={userId} onSelectArtist={handleSelectArtist} />;
};
