import { ofType } from 'redux-observable';
import { concat, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

import { selectedVideoSelector } from '../../../AiWorkbench/redux/selectors';
import { getSelectedVideoAction } from '../../../AiWorkbench/redux/slices';
import { thumbnailDraftPreviewSelector } from '../selectors';
import { updateThumbnailInVideoListOrDetailAction } from '../slices';
import { videosSelector } from '@/modules/editorial/editorialSearchResults/redux/selectors';
import { videosAction } from '@/modules/editorial/editorialSearchResults/redux/slices';
import { selectedVideoSelector as detailSelectedVideoSelector } from '@/modules/editorial/editorialVideoDetails/redux/selectors';
import { reloadSelectedVideoAction } from '@/modules/editorial/editorialVideoDetails/redux/slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(updateThumbnailInVideoListOrDetailAction.type),
    switchMap(() => {
      const { uid } = selectedVideoSelector(state$.value);
      const thumbnail = thumbnailDraftPreviewSelector(state$.value);
      const videos = videosSelector(state$.value);
      const isVideoDetailOpened = detailSelectedVideoSelector(state$.value);

      const updatedVideos = videos.map((originalVideo) =>
        originalVideo.uid === uid ? { ...originalVideo, thumbnailUrl: thumbnail?.url || '' } : originalVideo,
      );

      const actions = [];
      actions.push(of(videosAction(updatedVideos)), of(getSelectedVideoAction(uid)));
      if (isVideoDetailOpened) {
        actions.push(of(reloadSelectedVideoAction()));
      }

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