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

import { mapApiError } from '@/modules/@common/constants/mapApiError';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { createVideoAction, getListOfCreatedVideo, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import * as selectors from '@/modules/editorial/aiWorkbench/AiWorkbench/components/CreateVideoForm/redux/selectors';
import { selectedVideoSelector } from '@/modules/editorial/aiWorkbench/AiWorkbench/redux/selectors';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const queryGQL = `
  mutation AiWorkbenchHighlightsCreateVideoQuery(
    $video: AiWorkbenchHighlightsCreateVideoInputType,
  ) {
    aiWorkbenchHighlightsCreateVideo(
      video: $video,
    ) {
      uid
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(createVideoAction.type),
    switchMap((action) => {
      const state = state$.value;
      const successCallback = action.payload;

      const { uid: videoId } = selectedVideoSelector(state);

      const fadeIn = selectors.fadeInSelector(state);
      const fadeInIsActive = selectors.fadeInIsActiveSelector(state);
      const fadeOut = selectors.fadeOutSelector(state);
      const fadeOutIsActive = selectors.fadeOutIsActiveSelector(state);

      const name = selectors.titleSelector(state);
      const plot = selectors.descriptionSelector(state);
      const lang = selectors.languageSelector(state).value;
      const feedSourceId = selectors.feedSelector(state).value;
      const accessLevel = selectors.accessLevelSelector(state);
      const hubs = selectors.hubsSelector(state);

      const videoCreationDate = selectors.dateSelector(state);
      const notes = selectors.notesSelector(state);
      const evergreen = selectors.evergreenSelector(state);
      const label = selectors.labelsSelector(state);
      const keywords = selectors.keywordsSelector(state);
      const iab = selectors.iabSelector(state);
      const isNotify = selectors.isNotifySelector(state);
      const isHubsNotify = selectors.isHubsNotifySelector(state);

      const videoCreationDateCalculated = dayjs().isBefore(dayjs(videoCreationDate))
        ? dayjs(new Date())
        : dayjs(videoCreationDate);

      const video = {
        videoId,
        name,
        plot,
        lang,
        feedSourceId,
        videoCreationDate: videoCreationDateCalculated.utc().valueOf(),
        notes,
        evergreen,
        label,
        keywords,
        iab,
        accessLevel,
        hubs,
        isNotify,
        isHubsNotify,
      };

      if (fadeInIsActive && fadeIn) {
        video.fadeIn = +fadeIn;
      }

      if (fadeOutIsActive && fadeOut) {
        video.fadeOut = +fadeOut;
      }

      const stream$ = gqlRequest(
        {
          query: queryGQL,
          variables: { video },
        },
        {
          mapError: mapApiError(),
        },
      ).pipe(
        switchMap(({ data, errors }) => {
          const actions = [of(setAction({ isLoading: false }))];

          if (!errors?.length) {
            const { uid } = data.aiWorkbenchHighlightsCreateVideo;
            actions.push(
              of(getListOfCreatedVideo()),
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message:
                    'Highlights video is being generated... The new video could be open from "Highlights Videos"',
                }),
              ),
              of(setAction({ lastCreatedVideoId: uid })),
            );
            successCallback();
          }

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

      return concat(of(setAction({ isLoading: true })), stream$);
    }),
  );
