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

import { STATUSES_ACTIVE } from '../../../List/constants';
import { INCLUDE } from '../../constants';
import { GET_XRAY_LINE_ITEM } from '@/graphql/services/xRayLineItems/constants';
import { TYPE_ERROR } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/xRayLineItems/types/payload/xRayLineItemList';

import { timestampToString } from '../../helpers/timestamp';
import { getItemAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  query ${GET_XRAY_LINE_ITEM}($payload: ${PAYLOAD_NAME}) {
    ${GET_XRAY_LINE_ITEM}(payload: $payload) {
      id
      publisher {
        id
        name
      }
      xrayCampaign {
        id
        name
      }
      name
      status
      priority
      xrayCreatives {
        id
        name
        status
      }
      startTime
      endTime
      timezone {
        id
        
      }
      rate
      impressionsBudget
      spendBudget
      watch {
        id
        title
      }
      watchChannel {
        id
        title
      }
      player {
        id
        name
        alias
      }
      videoName
      videoUid
      videoFromTimestamp
      videoToTimestamp
      targeting {
        domains {
          id
          name
          filterAction
        }
        devices {
          deviceId
        }
        geography {
          id
          name
          filterAction
        }
        inview
        notInview
        playerSizes {
          playerSizeId
        }
        iabCategories {
          name
          filterAction
        }
        people {
          id
          name
          filterAction
          taxonomyId
        }
        brands {
          id
          name
          filterAction
          taxonomyId
        }
        keywords {
          id
          name
          filterAction
          taxonomyId
        }
        labels {
          name
          value
          color
          filterAction
          taxonomyId
        }
        brandSafety {
          id
          name
          filterAction
        }
      }
    }
  }
`;

const getResponse = ({ data }) => {
  const { publisher, ...item } = data[GET_XRAY_LINE_ITEM];

  return {
    ...item,
    hub: publisher,
  };
};

const mapToActionAutocompleteFormat = (values) => {
  if (!values?.length) {
    return [];
  }

  return values.map((o) => ({
    value: o.id,
    label: o.name,
    include: o.filterAction === INCLUDE,
    taxonomyId: o.taxonomyId,
  }));
};

export default (action$) =>
  action$.pipe(
    ofType(getItemAction.type),
    switchMap((action) => {
      const { id, isDuplicate } = action.payload;
      const stream$ = gqlRequest(
        {
          query,
          variables: {
            payload: {
              id,
            },
          },
        },
        {
          showNotificationMessage: false,
        },
      ).pipe(
        switchMap((response) => {
          const actions = [];

          if (response.errors.length) {
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_ERROR,
                  message: "Can't open for edit",
                }),
              ),
            );

            Router.push('/x-ray/line-items');
          } else {
            const {
              name,
              xrayCreatives,
              targeting,
              videoName,
              videoUid,
              videoFromTimestamp,
              videoToTimestamp,
              status,
              ...restData
            } = getResponse(response);
            const [xrayCreative1 = null, xrayCreative2 = null, xrayCreative3 = null] = xrayCreatives;

            actions.push(
              of(
                setAction({
                  name: isDuplicate ? `Copy of ${name}` : name,
                  status: isDuplicate ? STATUSES_ACTIVE : status,
                  xrayCreative1,
                  xrayCreative2,
                  xrayCreative3,
                  domains: mapToActionAutocompleteFormat(targeting.domains),
                  devices: targeting.devices ? targeting.devices.map((o) => o.deviceId) : [],
                  geography: mapToActionAutocompleteFormat(targeting.geography),
                  playerSizes: targeting.playerSizes ? targeting.playerSizes.map((o) => o.playerSizeId) : [],
                  inview: targeting.inview,
                  notInview: targeting.notInview,
                  video: videoUid ? { id: videoUid, name: videoName } : null,
                  videoFromTimestamp: timestampToString(videoFromTimestamp),
                  videoToTimestamp: timestampToString(videoToTimestamp),
                  iabCategories: targeting.iabCategories
                    ? targeting.iabCategories.map((o) => ({
                        id: o.name,
                        include: o.filterAction === INCLUDE,
                      }))
                    : [],
                  people: mapToActionAutocompleteFormat(targeting.people),
                  brands: mapToActionAutocompleteFormat(targeting.brands),
                  keywords: mapToActionAutocompleteFormat(targeting.keywords),
                  brandSafety: mapToActionAutocompleteFormat(targeting.brandSafety),
                  labels: targeting.labels
                    ? targeting.labels.map((o) => ({
                        label: o.value,
                        value: `${o.taxonomyId}|${o.value}`,
                        name: o.name,
                        color: o.color,
                        include: o.filterAction === INCLUDE,
                        taxonomyId: o.taxonomyId,
                      }))
                    : [],
                  ...restData,
                }),
              ),
            );
          }

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

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