import Router from 'next/router';
import { ofType } from 'redux-observable';
import { concat, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import createDemandTagPriceRequestBody from '../../helpers/createDemandTagPriceRequestBody';
import createDemandTagRequestBody from '../../helpers/createDemandTagRequestBody';
import * as selectors from '../selectors';
import { getDemandTagPricingAction, getInfoAction, setFieldAction, updateDemandTagAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  mutation UpdateDemandTag(
    $tags: [MarketplaceDemandTagInputType]
  ) {
    updateDemandTag(
      tags: $tags
    ) {
      data {
        id
        name
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(updateDemandTagAction.type),
    switchMap(({ payload }) => {
      const state = state$.value;
      const pageConfig = selectors.pageConfigSelector(state);
      // const settings = selectors.settingsSelector(state);

      const isPriceUpdate = payload?.type && payload?.data;
      const tag = !isPriceUpdate ? createDemandTagRequestBody(state) : createDemandTagPriceRequestBody(state, payload);

      const stream$ = gqlRequest({
        query,
        variables: {
          tags: [tag],
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          let actions = [];

          if (!errors.length) {
            if (isPriceUpdate) {
              actions = [
                of(getDemandTagPricingAction(payload.type)),
                of(
                  showNotificationAction({
                    type: TYPE_SUCCESS,
                    message: 'Demand tag price added',
                  }),
                ),
              ];
            } else {
              const link = `${window.location.pathname}?accountName=${pageConfig.demandAccount.name}`;
              // eslint-disable-next-line max-len
              // link += `&advertiserName=${encodeURIComponent(pageConfig?.advertiser.name)}&tagName=${encodeURIComponent(settings.name)}`;

              Router.push(link);

              actions = [
                of(getInfoAction(data.updateDemandTag.data[0].id)),
                of(
                  showNotificationAction({
                    type: TYPE_SUCCESS,
                    message: 'Demand tag updated',
                  }),
                ),
              ];
            }
          }

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

      return concat(of(setFieldAction({ isLoading: true })), stream$, of(setFieldAction({ isLoading: false })));
    }),
  );
