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

import { CALENDAR_FILTER_VALUE } from '../../constants';
import {
  WIDGET_DISPLAY_STATE_DATA,
  WIDGET_DISPLAY_STATE_ERROR,
  WIDGET_DISPLAY_STATE_NO_DATA,
} from '@/modules/analytics/common/constants';

import * as selectors from '../selectors';
import { getPerformanceTopSearchesAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getUserTimezoneSelector } from '@/modules/@common/user/redux/selectors';

const query = `
  query PerformanceTopSearchesQuery(
    $publisherId: Int,
    $watchId: Int,
    $channelId: Int,
    $origin: String,
    $dateRange: AnalyticsDateRangeInputType,
    $size: Int,
    $includeArchived: Boolean
  ) {
    performanceTopSearches(
      publisherId: $publisherId,
      watchId: $watchId,
      channelId: $channelId,
      origin: $origin,
      dateRange: $dateRange,
      size: $size,
      includeArchived: $includeArchived
    ) {
      total
      searches {
        query
        count
        rate
      }
      rid
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getPerformanceTopSearchesAction.type),
    debounce((action) => timer(action.payload?.length ? 1000 : 0)),
    switchMap(() => {
      const state = state$.value;

      const hub = selectors.hubSelector(state);
      const watch = selectors.watchSelector(state);
      const watchChannel = selectors.watchChannelSelector(state);
      const origin = selectors.originSelector(state);
      const calendar = selectors.calendarSelector(state);
      const calendarCustom = selectors.calendarCustomSelector(state);
      const includeArchived = selectors.includeArchivedSelector(state);

      const { comparison, interval, videoChartDataKey, ...dateRange } = calendar;

      let filters = {};
      const timezone = getUserTimezoneSelector(state$.value);

      if (hub) {
        filters = {
          ...filters,
          publisherId: hub.value,
        };
      }

      if (watch) {
        filters = {
          ...filters,
          watchId: watch.value,
        };
      }

      if (watchChannel) {
        filters = {
          ...filters,
          channelId: watchChannel.value,
        };
      }

      if (origin !== 'ALL') {
        filters = {
          ...filters,
          origin,
        };
      }

      if (calendar === CALENDAR_FILTER_VALUE.custom) {
        filters = {
          ...filters,
          dateRange: {
            stringFrom: calendarCustom.dateStart,
            stringTo: calendarCustom.dateEnd,
            timezone,
          },
        };
      } else {
        filters = {
          ...filters,
          dateRange: {
            ...dateRange,
            timezone,
          },
        };
      }

      const stream$ = gqlRequest({
        query,
        variables: {
          includeArchived,
          size: 15,
          ...filters,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const topSearches = data?.performanceTopSearches?.searches ?? [];
            actions.push(
              of(
                setFieldAction({
                  topSearches,
                  displayStateTopSearches: topSearches.length
                    ? WIDGET_DISPLAY_STATE_DATA
                    : WIDGET_DISPLAY_STATE_NO_DATA,
                }),
              ),
            );
          } else {
            actions.push(
              of(
                setFieldAction({
                  displayStateTopSearches: WIDGET_DISPLAY_STATE_ERROR,
                }),
              ),
            );
          }

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

      return concat(stream$);
    }),
  );
