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

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

import { getChannelFromStore } from '../../helpers/channels';
import * as watchesSelectors from '../selectors';
import { updatePlaylistAction } from '../slices';
import { targetClipIdSelector } from '@/modules/editorial/editorialSearchResults/redux/selectors';
import { targetClipIdEventAction } from '@/modules/editorial/editorialSearchResults/redux/slices';
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 channel = getChannelFromStore(state$.value);

      if (!channel?.playlistId) {
        return of(
          showNotificationAction({
            type: TYPE_ERROR,
            message: "The channel doesn't have playlist id",
          }),
        );
      }

      const playlistsEntities = watchesSelectors.playlistsEntitiesSelector(state$.value);
      const playlist = playlistsEntities[channel.playlistId] ?? null;

      if (!playlist?.publisherId) {
        return EMPTY;
      }

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

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

      return of(
        updatePlaylistAction({
          playlistId: channel.playlistId,
          clips: newClips,
          publisherId: playlist.publisherId,
        }),
      );
    }),
  );
