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

import { REDUX_ERROR_PROP_NAME } from '@/modules/@common/Form/constants';

import { hubSelector, playerOptionsSelector, playlistIdSelector, urlSelector } from '../selectors';
import {
  getPlaylistsByUrlAction,
  setErrorByPropAction,
  setPlaylistsByUrlAction,
  setScrollToFieldNameAction,
  validateSingleField,
} from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';
import {
  isValidPlaylistUrl,
  removeWorldWideWebPrefix,
} from '@/modules/editorial/RightSideBar/TabPlaylist/Edit/helpers/player';

const queryGQL = `
  query getPlaylists(
    $page: Int,
    $pageSize: Int,
    $publisherIds: [Int],
    $type: String,
    $searchText: String,
    $searchIn: String
  ) {
    getPlaylists(
      page: $page,
      pageSize: $pageSize,
      publisherIds: $publisherIds,
      type: $type,
      searchText: $searchText,
      searchIn: $searchIn
    ) {
      records {
        id
        playerId
        url
      }
      recordsTotal
      page
      pageSize
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getPlaylistsByUrlAction.type),
    debounceTime(500),
    filter(() => !!getToken()),
    filter(
      () => !!hubSelector(state$.value) && !!urlSelector(state$.value) && isValidPlaylistUrl(urlSelector(state$.value)),
    ),
    switchMap(() => {
      const url = removeWorldWideWebPrefix(urlSelector(state$.value));
      const playerOptions = playerOptionsSelector(state$.value);

      const variables = {
        page: 1,
        pageSize: 1000,
        publisherIds: [hubSelector(state$.value).value],
        type: 'EDITORIAL',
        searchText: url,
        searchIn: 'url',
      };

      return gqlRequest({ query: queryGQL, variables }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const playlistId = playlistIdSelector(state$.value);
            const playlists = data.getPlaylists.records.filter(
              (playlist) => playlist.id !== playlistId && url === removeWorldWideWebPrefix(playlist.url),
            );

            const validation = validateSingleField('url', url, {
              playerOptions,
              playlistsByUrl: playlists,
            });

            if (validation[REDUX_ERROR_PROP_NAME]) {
              actions.push(of(setErrorByPropAction([validation])));
              actions.push(of(setScrollToFieldNameAction(validation.fieldName)));
            }

            actions.push(of(setPlaylistsByUrlAction(playlists)));
          }

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