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

import { CALENDAR_FILTER_VALUE, TABS_CONFIG } from '../../constants';

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

const videoQuery = `
  query PerformanceVideoTopAutocompleteQuery(
    $publisherId: Int,
    $watchId: Int,
    $channelId: Int,
    $origin: String,
    $dateRange: AnalyticsDateRangeInputType,
    $size: Int,
    $prefix: String,
    $includeArchived: Boolean
  ) {
    performanceVideoTopAutocomplete(
      publisherId: $publisherId,
      watchId: $watchId,
      channelId: $channelId,
      origin: $origin,
      dateRange: $dateRange,
      size: $size,
      prefix: $prefix,
      includeArchived: $includeArchived
    ) {
      names
      rid
    }
  }
`;

const channelQuery = `
  query PerformanceChannelTopAutocompleteQuery(
    $publisherId: Int,
    $watchId: Int,
    $channelId: Int,
    $origin: String,
    $dateRange: AnalyticsDateRangeInputType,
    $size: Int,
    $prefix: String,
    $includeArchived: Boolean
  ) {
    performanceChannelTopAutocomplete(
      publisherId: $publisherId,
      watchId: $watchId,
      channelId: $channelId,
      origin: $origin,
      dateRange: $dateRange,
      size: $size,
      prefix: $prefix,
      includeArchived: $includeArchived
    ) {
      names
      rid
    }
  }
`;

const siteQuery = `
  query PerformanceSiteTopAutocompleteQuery(
    $publisherId: Int,
    $watchId: Int,
    $channelId: Int,
    $origin: String,
    $dateRange: AnalyticsDateRangeInputType,
    $size: Int,
    $prefix: String,
    $includeArchived: Boolean
  ) {
    performanceSiteTopAutocomplete(
      publisherId: $publisherId,
      watchId: $watchId,
      channelId: $channelId,
      origin: $origin,
      dateRange: $dateRange,
      size: $size,
      prefix: $prefix,
      includeArchived: $includeArchived
    ) {
      names
      rid
    }
  }
`;

const watchQuery = `
  query PerformanceWatchTopAutocompleteQuery(
    $publisherId: Int,
    $watchId: Int,
    $channelId: Int,
    $origin: String,
    $dateRange: AnalyticsDateRangeInputType,
    $size: Int,
    $prefix: String,
    $includeArchived: Boolean
  ) {
    performanceWatchTopAutocomplete(
      publisherId: $publisherId,
      watchId: $watchId,
      channelId: $channelId,
      origin: $origin,
      dateRange: $dateRange,
      size: $size,
      prefix: $prefix,
      includeArchived: $includeArchived
    ) {
      names
      rid
    }
  }
`;

const QUERIES = {
  [TABS_CONFIG.VIDEOS.id]: videoQuery,
  [TABS_CONFIG.CHANNELS.id]: channelQuery,
  [TABS_CONFIG.HUBS.id]: siteQuery,
  [TABS_CONFIG.WATCHES.id]: watchQuery,
};

export default (action$, state$) =>
  action$.pipe(
    ofType(getSearchOptionsAction.type),
    debounce((action) => timer(action.payload?.length ? 1000 : 0)),
    switchMap(({ payload = '' }) => {
      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 activeTabId = selectors.activeTabIdSelector(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: QUERIES[activeTabId],
        variables: {
          size: 15,
          prefix: payload,
          ...filters,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const response = {
              ...data.performanceVideoTopAutocomplete,
              ...data.performanceChannelTopAutocomplete,
              ...data.performanceWatchTopAutocomplete,
              ...data.performanceSiteTopAutocomplete,
            };

            actions.push(
              of(
                setFieldAction({
                  searchOptions: response.names?.length ? response.names.map((i) => ({ label: i, value: i })) : [],
                }),
              ),
            );
          }

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

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