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

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

import { getTemplateByIdAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import parseTemplateResponseToState from '@/modules/forms/editor/helpers/parseTemplateResponseToState';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  query GetFormTemplateGalleryByIdQuery(
    $id: Int!
  ) {
    getFormTemplateGalleryById(
      id: $id
    ) {
      id
      formTemplateCategoryId
      account {
        id
        name
      }
      name
      title
      logo
      metadata
    }
  }
`;

const getResponse = ({ data: { getFormTemplateGalleryById } }) => getFormTemplateGalleryById;

export default (action$) =>
  action$.pipe(
    ofType(getTemplateByIdAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          id: action.payload,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const data = getResponse(response);
            const actions = [];
            try {
              const state = parseTemplateResponseToState(data);

              actions.push(of(setFieldAction(state)));
              // eslint-disable-next-line @typescript-eslint/no-unused-vars
            } catch (e) {
              actions.push(
                of(
                  showNotificationAction({
                    type: TYPE_ERROR,
                    message: 'Cant open template. Metadata format is wrong',
                  }),
                ),
              );

              Router.push('/forms');
            }

            return concat(...actions);
          }

          return EMPTY;
        }),
      );

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