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 {
  WIDGET_DISPLAY_STATE_DATA,
  WIDGET_DISPLAY_STATE_ERROR,
  WIDGET_DISPLAY_STATE_NO_DATA,
} from '@/modules/analytics/common/constants';

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

const videoQuery = `
  query PerformanceTopVideosQuery(
    $publisherId: Int,
    $watchId: Int,
    $channelId: Int,
    $origin: String,
    $dateRange: AnalyticsDateRangeInputType,
    $dateRangeComparison: AnalyticsDateRangeInputType,
    $sort: AnalyticsSortingInputType,
    $total: Boolean,
    $query: String,
    $size: Int,
    $exactMatch: Boolean,
    $includeArchived: Boolean
  ) {
    performanceTopVideos(
      publisherId: $publisherId,
      watchId: $watchId,
      channelId: $channelId,
      origin: $origin,
      dateRange: $dateRange,
      dateRangeComparison: $dateRangeComparison,
      sort: $sort,
      query: $query,
      total: $total,
      size: $size,
      exactMatch: $exactMatch,
      includeArchived: $includeArchived
    ) {
      total
      videos {
        uuid
        name
        thumbnail
        numOfViews
        attentionSpan
        engScore
        duration
        status
        thumbnails {
          file
          width
          height
        }
      }
      rid
    }
  }
`;

const channelQuery = `
  query PerformanceTopChannelsQuery(
    $publisherId: Int,
    $watchId: Int,
    $channelId: Int,
    $origin: String,
    $dateRange: AnalyticsDateRangeInputType,
    $dateRangeComparison: AnalyticsDateRangeInputType,
    $sort: AnalyticsSortingInputType,
    $total: Boolean,
    $query: String,
    $size: Int,
    $exactMatch: Boolean,
    $includeArchived: Boolean
  ) {
    performanceTopChannels(
      publisherId: $publisherId,
      watchId: $watchId,
      channelId: $channelId,
      origin: $origin,
      dateRange: $dateRange,
      dateRangeComparison: $dateRangeComparison,
      sort: $sort,
      query: $query,
      total: $total,
      size: $size,
      exactMatch: $exactMatch,
      includeArchived: $includeArchived
    ) {
      total
      channels {
        channelId
        channelName
        numOfViews
        attentionSpan
        engScore
      }
      rid
    }
  }
`;

const siteQuery = `
  query PerformanceTopSitesQuery(
    $publisherId: Int,
    $watchId: Int,
    $channelId: Int,
    $origin: String,
    $dateRange: AnalyticsDateRangeInputType,
    $dateRangeComparison: AnalyticsDateRangeInputType,
    $sort: AnalyticsSortingInputType,
    $total: Boolean,
    $query: String,
    $size: Int,
    $exactMatch: Boolean,
    $includeArchived: Boolean
  ) {
    performanceTopSites(
      publisherId: $publisherId,
      watchId: $watchId,
      channelId: $channelId,
      origin: $origin,
      dateRange: $dateRange,
      dateRangeComparison: $dateRangeComparison,
      sort: $sort,
      query: $query,
      total: $total,
      size: $size,
      exactMatch: $exactMatch,
      includeArchived: $includeArchived
    ) {
      total
      sites {
        site
        siteName
        numOfViews
        attentionSpan
        engScore
      }
      rid
    }
  }
`;

const watchQuery = `
  query PerformanceTopWatchesQuery(
    $publisherId: Int,
    $watchId: Int,
    $channelId: Int,
    $origin: String,
    $dateRange: AnalyticsDateRangeInputType,
    $dateRangeComparison: AnalyticsDateRangeInputType,
    $sort: AnalyticsSortingInputType,
    $total: Boolean,
    $query: String,
    $size: Int,
    $exactMatch: Boolean,
    $includeArchived: Boolean
  ) {
    performanceTopWatches(
      publisherId: $publisherId,
      watchId: $watchId,
      channelId: $channelId,
      origin: $origin,
      dateRange: $dateRange,
      dateRangeComparison: $dateRangeComparison,
      sort: $sort,
      query: $query,
      total: $total,
      size: $size,
      exactMatch: $exactMatch,
      includeArchived: $includeArchived
    ) {
      total
      watches {
        watchId
        watchName
        numOfViews
        attentionSpan
        engScore
      }
      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(getTableItemsAction.type),
    debounce((action) => timer(action.payload?.query?.length ? 1000 : 0)),
    switchMap(({ payload = {} }) => {
      const { total = true, exactMatch = false } = 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 includeArchived = selectors.includeArchivedSelector(state);
      const search = selectors.searchSelector(state);
      const sortBy = selectors.sortBySelector(state);
      const sortOrder = selectors.sortOrderSelector(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 (search?.value) {
        filters = {
          ...filters,
          query: search.value,
        };
      }

      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: {
          total,
          exactMatch,
          includeArchived,
          size: 20,
          ...filters,
          sort: {
            by: sortBy,
            order: sortOrder,
          },
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (data && !errors.length) {
            const response = {
              ...data.performanceTopVideos,
              ...data.performanceTopChannels,
              ...data.performanceTopSites,
              ...data.performanceTopWatches,
            };

            let items = [];

            if (activeTabId === TABS_CONFIG.VIDEOS.id) {
              items = response.videos;
            } else if (activeTabId === TABS_CONFIG.CHANNELS.id) {
              items = response.channels?.map(({ channelId, channelName, ...other }) => ({
                uuid: channelId,
                name: channelName,
                ...other,
              }));
            } else if (activeTabId === TABS_CONFIG.HUBS.id) {
              items = response.sites?.map(({ site, siteName, ...other }) => ({
                uuid: site,
                name: siteName,
                ...other,
              }));
            } else if (activeTabId === TABS_CONFIG.WATCHES.id) {
              items = response.watches?.map(({ watchId, watchName, ...other }) => ({
                uuid: watchId,
                name: watchName,
                ...other,
              }));
            }

            if (total && activeTabId === TABS_CONFIG.VIDEOS.id) {
              actions.push(
                of(
                  setFieldAction({
                    total: response.total,
                  }),
                ),
              );
            }

            const firstItemId = items?.[0]?.uuid ?? null;

            actions.push(
              of(
                setFieldAction({
                  tableItems: items,
                  selectedItemId: firstItemId,
                  displayStateTopVideos:
                    !items?.length && !search?.value ? WIDGET_DISPLAY_STATE_NO_DATA : WIDGET_DISPLAY_STATE_DATA,
                }),
              ),
            );

            if (firstItemId) {
              actions.push(of(getItemMetricsAction(firstItemId)));
            }
          } else {
            actions.push(
              of(
                setFieldAction({
                  displayStateTopVideos: WIDGET_DISPLAY_STATE_ERROR,
                }),
              ),
            );
          }

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

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