import dayjs from 'dayjs';
import timezonePlugin from 'dayjs/plugin/timezone';
import utcPlugin from 'dayjs/plugin/utc';
import weekOfYearPlugin from 'dayjs/plugin/weekOfYear';
import { ofType } from 'redux-observable';
import { concat, of } from 'rxjs';
import { filter, switchMap } from 'rxjs/operators';

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

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

dayjs.extend(utcPlugin);
dayjs.extend(timezonePlugin);
dayjs.extend(weekOfYearPlugin);

const videoQuery = `
  query PerformanceVideoMetricsQuery(
    $id: String,
    $publisherId: Int,
    $watchId: Int,
    $channelId: Int,
    $origin: String,
    $dateRange: AnalyticsDateRangeInputType,
    $interval: String,
    $metric: String,
    $includeArchived: Boolean
  ) {
    performanceVideoMetrics(
      id: $id,
      publisherId: $publisherId,
      watchId: $watchId,
      channelId: $channelId,
      origin: $origin,
      dateRange: $dateRange,
      interval: $interval,
      metric: $metric,
      includeArchived: $includeArchived
    ) {
      data {
        time
        value
        total
      }
      rid
    }
  }
`;

const channelQuery = `
  query PerformanceChannelMetricsQuery(
    $id: String,
    $publisherId: Int,
    $watchId: Int,
    $channelId: Int,
    $origin: String,
    $dateRange: AnalyticsDateRangeInputType,
    $interval: String,
    $metric: String,
    $includeArchived: Boolean
  ) {
    performanceChannelMetrics(
      id: $id,
      publisherId: $publisherId,
      watchId: $watchId,
      channelId: $channelId,
      origin: $origin,
      dateRange: $dateRange,
      interval: $interval,
      metric: $metric,
      includeArchived: $includeArchived
    ) {
      data {
        time
        value
        total
      }
      rid
    }
  }
`;

const watchQuery = `
  query PerformanceWatchMetricsQuery(
    $id: String,
    $publisherId: Int,
    $watchId: Int,
    $channelId: Int,
    $origin: String,
    $dateRange: AnalyticsDateRangeInputType,
    $interval: String,
    $metric: String,
    $includeArchived: Boolean
  ) {
    performanceWatchMetrics(
      id: $id,
      publisherId: $publisherId,
      watchId: $watchId,
      channelId: $channelId,
      origin: $origin,
      dateRange: $dateRange,
      interval: $interval,
      metric: $metric,
      includeArchived: $includeArchived
    ) {
      data {
        time
        value
        total
      }
      rid
    }
  }
`;

const siteQuery = `
  query PerformanceSiteMetricsQuery(
    $id: String,
    $publisherId: Int,
    $watchId: Int,
    $channelId: Int,
    $origin: String,
    $dateRange: AnalyticsDateRangeInputType,
    $interval: String,
    $metric: String,
    $includeArchived: Boolean
  ) {
    performanceSiteMetrics(
      id: $id,
      publisherId: $publisherId,
      watchId: $watchId,
      channelId: $channelId,
      origin: $origin,
      dateRange: $dateRange,
      interval: $interval,
      metric: $metric,
      includeArchived: $includeArchived
    ) {
      data {
        time
        value
        total
      }
      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(getItemMetricsAction.type),
    filter(({ payload }) => {
      const selectedItemId = selectors.selectedItemIdSelector(state$.value);

      return selectedItemId?.length || payload?.length;
    }),
    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 selectedItemId = selectors.selectedItemIdSelector(state);
      const activeMetric = selectors.activeMetricSelector(state);
      const activeTabId = selectors.activeTabIdSelector(state);
      const includeArchived = selectors.includeArchivedSelector(state);

      const id = selectedItemId || payload;

      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,
          },
          interval: calendarCustom.interval,
        };
      } else {
        filters = {
          ...filters,
          dateRange: {
            ...dateRange,
            timezone,
          },
          interval,
        };
      }

      const stream$ = gqlRequest({
        query: QUERIES[activeTabId],
        variables: {
          id,
          includeArchived,
          ...filters,
          metric: activeMetric,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const response = {
              ...data.performanceVideoMetrics,
              ...data.performanceChannelMetrics,
              ...data.performanceWatchMetrics,
              ...data.performanceSiteMetrics,
            };

            actions.push(
              of(
                setFieldAction({
                  itemMetrics: response.data?.map((item) => ({
                    ...item,
                    date: dayjs(item.time).tz(timezone).format('MMM DD'),
                    hours: dayjs(item.time).tz(timezone).format('h A'),
                    weeks: `Week ${dayjs(item.time).tz(timezone).week()}`,
                  })),
                }),
              ),
            );
          } else {
            actions.push(
              of(
                setFieldAction({
                  displayStateMainMetrics: WIDGET_DISPLAY_STATE_ERROR,
                }),
              ),
            );
          }

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

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