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

import { DEMAND_TAG_FREQUENCY_TAB_STATUS, DEMAND_TAG_PAGE_CONFIRM_FREQUENCY_CAP_MODAL } from '../../constants';

import * as selectors from '../selectors';
import { openModalAction, showConfirmModalAction, updateDemandTagAction } from '../slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(showConfirmModalAction.type),
    switchMap(() => {
      const state = state$.value;

      const frequencyCap = selectors.frequencyCapSelector(state);
      const { status, value, timeframe, amount, prevSavedData } = frequencyCap;

      if (
        prevSavedData?.status === DEMAND_TAG_FREQUENCY_TAB_STATUS.active &&
        status === DEMAND_TAG_FREQUENCY_TAB_STATUS.disabled
      ) {
        return concat(
          of(
            openModalAction({
              id: DEMAND_TAG_PAGE_CONFIRM_FREQUENCY_CAP_MODAL,
            }),
          ),
        );
      }

      if (prevSavedData?.timeframe === timeframe && value / amount > prevSavedData?.value / prevSavedData?.amount) {
        return concat(
          of(
            openModalAction({
              id: DEMAND_TAG_PAGE_CONFIRM_FREQUENCY_CAP_MODAL,
            }),
          ),
        );
      }

      return concat(of(updateDemandTagAction()));
    }),
  );
