import Router from 'next/router';
import { ofType } from 'redux-observable';
import { concat, of } from 'rxjs';
import { filter, mergeMap } from 'rxjs/operators';

import { TYPE_ERROR, TYPE_SUCCESS } from '@/modules/@common/notify/constants';
import { QUERY_PARAM_TAB, TAB_WATCH } from '@/modules/editorial/constants/routing';

import { playlistIdSelector, playlistsSelector } from '../../selectors';
import { updatePlaylistAction } from '../../slices';
import { targetClipIdSelector } from '@/modules/editorial/editorialSearchResults/redux/selectors';
import { targetClipIdEventAction } from '@/modules/editorial/editorialSearchResults/redux/slices';
import { isMobileApp } from '@/modules/layout/helpers';
import { showNotificationAction } from '@/modules/layout/redux/slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(targetClipIdEventAction.type),
    filter(() => targetClipIdSelector(state$.value) && !(Router.query[QUERY_PARAM_TAB] === TAB_WATCH)),
    mergeMap(() => {
      const targetClipId = targetClipIdSelector(state$.value);
      const playlists = playlistsSelector(state$.value);
      const playlistId = playlistIdSelector(state$.value);

      const playlist = playlists.find((playlist$) => playlist$.id === playlistId);

      if (playlist?.clips?.includes(targetClipId)) {
        return of(showNotificationAction({ type: TYPE_ERROR, message: 'The video is already in the playlist' }));
      }

      const newClips = [...(playlist?.clips ?? []), targetClipId];

      const actions = [of(updatePlaylistAction({ clips: newClips, publisherId: playlist?.publisherId }))];

      if (isMobileApp) {
        actions.push(of(showNotificationAction({ type: TYPE_SUCCESS, message: 'Video added to the playlist' })));
      }

      return concat(...actions);
    }),
  );
