import {
  ModalTypes,
  OpenModalWithDataFn,
} from '@/components/modal/constants/ModalTypes';
import { toast } from '@/components/toast/Toast';
import { Clip, ClipsStore } from '@/state/clipStore';
import { SessionStore } from '@/state/sessionStore';

import {
  MAX_PINNED_SONGS_ARTIST_PROFILE,
  MAX_PINNED_SONGS_PROFILE,
} from './constants';

export const getPinModalOptions = ({
  clipIsPrivate,
  pinnedCount,
  isPublishFlow = false,
  maxPins = 5,
}: {
  clipIsPrivate: boolean;
  pinnedCount: number;
  isPublishFlow?: boolean;
  maxPins?: number;
}) => {
  let showModal = false;
  const pinLimitReached = pinnedCount >= maxPins;
  let title = 'Pin limit reached!';
  let message = `You can only pin up to ${maxPins} songs to your Profile. Pinning this song will replace your oldest pinned song`;

  if (pinLimitReached && clipIsPrivate && !isPublishFlow) {
    message = `You can only pin up to ${maxPins} songs to your Profile. Pinning this song will replace your oldest pinned song and make this song Public`;
    showModal = true;
  } else if (pinLimitReached) {
    message = `You can only pin up to ${maxPins} songs to your Profile. Pinning this song will replace your oldest pinned song`;
    showModal = true;
  } else if (clipIsPrivate && !isPublishFlow) {
    title = 'Pinning Private Song!';
    message =
      'Pinning a private song will make it public. Are you sure you want to continue?';
    showModal = true;
  }

  return { title, message, showModal };
};

export const handlePinOrConfirm = async ({
  clip,
  clips,
  openModalWithData,
  session,
}: {
  clip: Clip;
  clips: ClipsStore;
  openModalWithData: OpenModalWithDataFn;
  session: SessionStore;
}) => {
  const clipIsPrivate = !clip.is_public;
  const pinnedCount = clips.getPinnedCount();
  const isPinned = clips.isClipPinned(clip.id);
  const { title, message, showModal } = getPinModalOptions({
    clipIsPrivate,
    pinnedCount,
    maxPins: session.flags?.['artist-profiles']
      ? MAX_PINNED_SONGS_ARTIST_PROFILE
      : MAX_PINNED_SONGS_PROFILE,
  });
  if (!isPinned && showModal) {
    // Open the confirmation modal with data
    openModalWithData(ModalTypes.CONFIRM_PIN_REPLACEMENT, {
      clipId: clip.id,
      title: title,
      message: message,
    });
  } else {
    // If we don't need confirmation, proceed directly
    await clips.pinClipToProfile({ clipId: clip.id });

    toast({
      title: `This song has been ${isPinned ? 'unpinned from Profile' : 'pinned to Profile'}.`,
      duration: 2000,
      isClosable: true,
    });
  }
};
