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 { chaptersSelector, selectedChaptersSelector } from '../selectors';
import { createVideoAction, getListOfCreatedVideoAction, 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 AiWorkbenchChaptersCreateVideosQuery(
    $payload: AiWorkbenchChaptersCreateVideosInputType,
  ) {
    aiWorkbenchChaptersCreateVideos(
      payload: $payload,
    ) {
      uid
    }
  }
`;

function getChaptersForVideosGenerate(chapters, selectedChapters, videoLength) {
  const selected = new Set(selectedChapters);
  const chaptersForVideoGenerate = [];

  for (let i = 0; i < chapters.length; i++) {
    if (selected.has(chapters[i].time)) {
      const { time: startTime, name, description } = chapters[i];
      const chapterForCreateVideo = {
        startTime,
        endTime: chapters[i + 1]?.time || videoLength,
        name: `[CHAPTER] ${i + 1} ${name}`,
        description,
      };
      chaptersForVideoGenerate.push(chapterForCreateVideo);
    }
  }

  return chaptersForVideoGenerate;
}

function ifOneChapterAddNameAndPlotFromForm(chapters, data) {
  return chapters.length === 1 ? [{ ...chapters[0], ...data }] : chapters;
}

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

      const { uid: videoId, videoLength } = selectedVideoSelector(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 chapters = chaptersSelector(state);
      const selectedChapters = selectedChaptersSelector(state);

      const generateChapterVideos = ifOneChapterAddNameAndPlotFromForm(
        getChaptersForVideosGenerate(chapters, selectedChapters, videoLength),
        {
          name,
          description: plot,
        },
      );

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

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

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

          if (!errors?.length) {
            actions.push(
              of(getListOfCreatedVideoAction()),
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Chapter videos are being generated. The new video could be open from "Chapter Videos"',
                }),
              ),
            );
            successCallback();
          }

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

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