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

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

import createSupplyTagPriceRequestBody from '../../helpers/createSupplyTagPriceRequestBody';
import createSupplyTagRequestBody from '../../helpers/createSupplyTagRequestBody';
import * as selectors from '../selectors';
import { getInfoAction, setFieldAction, updateSupplyTagAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  mutation UpdateSupplyTag(
    $tags: [MarketplaceSupplyTagInputType]
  ) {
    updateSupplyTag(
      tags: $tags
    ) {
      data {
        id
        name
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(updateSupplyTagAction.type),
    switchMap(({ payload }) => {
      const state = state$.value;
      const userPermissions = getUserPermissionsSelector(state);
      const isAdminMP = hasPermission(PCN_GET_MARKETPLACE_DASHBOARD, userPermissions);

      const pageConfig = selectors.pageConfigSelector(state);

      const isPriceUpdate = payload?.data;
      const tag = !isPriceUpdate
        ? createSupplyTagRequestBody(state, isAdminMP)
        : createSupplyTagPriceRequestBody(state, payload.data, payload.key);

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

          if (!errors.length) {
            if (isPriceUpdate) {
              actions = [
                of(getInfoAction(pageConfig.id)),
                of(
                  showNotificationAction({
                    type: TYPE_SUCCESS,
                    message: 'Supply tag price added',
                  }),
                ),
              ];
            } else {
              const { updateSupplyTag } = data;
              const updatedTag = updateSupplyTag.data[0];

              const link = `/supply/${pageConfig.supplyAccount.id}/sites/${pageConfig.site.id}/tags/${updatedTag.id}`;
              // eslint-disable-next-line max-len
              // link += `?accountName=${encodeURIComponent(pageConfig.supplyAccount.name)}&siteName=${encodeURIComponent(pageConfig.site.name)}&tagName=${encodeURIComponent(updatedTag.name)}`;

              Router.push(link);

              actions = [
                of(getInfoAction(updatedTag.id)),
                of(
                  showNotificationAction({
                    type: TYPE_SUCCESS,
                    message: 'Supply tag updated',
                  }),
                ),
              ];
            }
          }

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

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