/*
 *
 * Create
 *
 */

import PropTypes, { object } from 'prop-types';

import React from 'react';
import { bindActionCreators } from 'redux';
import { notification } from 'antd';
import {get, set, filter, isEmpty, map, forEach, uniqueId, cloneDeep, isEqual, findIndex} from 'lodash';
import { createStructuredSelector } from 'reselect';
import { intlShape, FormattedMessage } from 'react-intl';
import styled from 'styled-components';
import { CapSlideBox, CapHeader, CapTable, CapLink, CapRow, CapColumn, CapIcons, CapSpin, CapNotification } from '@capillarytech/cap-ui-library';
import { makeSelectCreate, makeSelectCreateResponse, makeSelectIosCta } from './selectors';
import { makeSelectMetaEntities, setInjectedTags } from '../../Cap/selectors';
import FormBuilder from '../../../v2Components/FormBuilder';
import './_mobilePushCreate.scss';
import * as actions from './actions';
import withCreatives from '../../../hoc/withCreatives';
import * as globalActions from '../../Cap/actions';
import {getMessageObject} from '../../../utils/messageUtils';
import { gtmPush } from '../../../utils/gtmTrackers';

import { makeSelectTemplates } from '../../Templates/selectors';
import messages from './messages';
import getEventsMap from '../eventsMap';
import { GA } from '@capillarytech/cap-ui-utils';
import { CREATE, TRACK_CREATE_MPUSH } from '../../App/constants';
import { MOBILE_PUSH } from '../../CreativesContainer/constants';
import { getContent } from '../commonMethods';
import { getCdnUrl } from '../../../utils/cdnTransformation';
import injectReducer from '../../../utils/injectReducer';
import injectSaga from '../../../utils/injectSaga';
import v2MobilePushCreateReducer from './reducer';
import { v2MobilePushWatchDuplicateTemplateSaga } from './sagas';
import { EXTERNAL_LINK_LOWERCASE } from './constants';
import TestAndPreviewSlidebox from '../../../v2Components/TestAndPreviewSlidebox';
import { checkForPersonalizationTokens, validateMobilePushContent } from '../../../utils/commonUtils';
import formBuilderMessages from '../../../v2Components/FormBuilder/messages';

const PrefixWrapper = styled.div`
  margin-right: 16px;
`;
export class Create extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    const eventsMap = getEventsMap(this);
    if (this.props.Templates.selectedWeChatAccount) {
      this.state = {
        formData: {},
        tabCount: 1,
        currentTab: 1,
        loading: false,
        isFormValid: true,
        tabKey: '',
        checkValidation: false,
        schema: {},
        eventsMap,
        errorData: {},
        displayProps: {},
        modalContent: {title: this.props.intl.formatMessage(messages.alertMessage), body: this.props.intl.formatMessage(messages.templateNotConfigured), type: 'confirm'},
        injectedTags: {},
      };
    }
    this.hasFetchedInitialTagsRef = false;
    this.lastFetchedTagContextRef = null;
  }
  componentWillMount = () => {
    if (this.props.route.name === 'view') {
      this.setState({loading: false});
      this.removeStandAlone();
    }
    if (this.props.params.mode) {
      this.setState({mode: this.props.params.mode});
    }
    if (!this.props.Templates.selectedWeChatAccount) {
      const type = this.props.location.query.type;
      const module = this.props.location.query.module ? this.props.location.query.module : 'default';
      this.props.router.push({
        pathname: `/MOBILEPUSH/`,
        query: type === 'embedded' ? {type: 'embedded', module} : {module},
      });
    }
  };

  componentDidMount = () => {
    const query = {
      layout: 'MOBILEPUSH',
      type: 'LAYOUT',
      version: "v2",
    };
    this.props.globalActions.fetchSchemaForEntity(query);
  };
  componentWillReceiveProps = (nextProps) => {
    // Library mode: on Done click (transition to isGetFormData), run extractTags only when no existing validation errors (braces, personalization, etc.)
    if (nextProps.isGetFormData && !this.props.isGetFormData && !nextProps.isFullMode) {
      // If form already has validation errors (braces, personalization tags, etc.), do not call extractTags or return payload; always return early
      if (!this.state.isFormValid) {
        if (typeof nextProps.onValidationFail === 'function') {
          nextProps.onValidationFail();
        }
        return;
      }
      const hasAllValidationCallbacks =
        typeof nextProps.getLiquidTags === 'function' &&
        typeof nextProps.showLiquidErrorInFooter === 'function' &&
        typeof nextProps.onValidationFail === 'function';

      if (hasAllValidationCallbacks) {
        const formDataArr = [this.state.formData?.[0], this.state.formData?.[1]];
        validateMobilePushContent(formDataArr, {
          currentTab: this.state.currentTab,
          getLiquidTags: nextProps.getLiquidTags,
          formatMessage: this.props.intl.formatMessage,
          messages: formBuilderMessages,
          onError: (err) => {
            const { standardErrors = [], liquidErrors = [] } = err;
            // _validatePlatformSpecificContent passes { standardErrors: { ANDROID, IOS, generic }, liquidErrors: { ... } }; footer expects arrays
            const toArray = (v) => (Array.isArray(v) ? v : (v && typeof v === 'object' ? [].concat(...Object.values(v)) : []));
            const STANDARD_ERROR_MSG = toArray(standardErrors);
            const LIQUID_ERROR_MSG = toArray(liquidErrors);
            if (typeof nextProps.showLiquidErrorInFooter === 'function') {
              nextProps.showLiquidErrorInFooter(
                { STANDARD_ERROR_MSG, LIQUID_ERROR_MSG },
                this.state.currentTab
              );
            }
            // Only trigger onValidationFail when there are actual errors; skip when helper called onError with empty arrays (reset case)
            if ((STANDARD_ERROR_MSG.length > 0 || LIQUID_ERROR_MSG.length > 0) && typeof nextProps.onValidationFail === 'function') {
              nextProps.onValidationFail();
            }
          },
          onSuccess: () => {
            if (this.state.isFormValid && typeof nextProps.getFormLibraryData === 'function') {
              nextProps.getFormLibraryData(this.getFormData());
            }
          },
        });
      } else {
        // Fail closed: require full validation callback set; treat any missing callback as validation failure
        if (typeof nextProps.onValidationFail === 'function') {
          nextProps.onValidationFail();
        }
      }
    } else if (nextProps.isGetFormData && this.props.isGetFormData !== nextProps.isGetFormData && this.props.isFullMode && !this.props.Create.createTemplateInProgress) {
      this.startValidation();
    }
    if (nextProps.Create.uploadedAssetData) {
      const formData = cloneDeep(this.state.formData);
      formData[this.state.currentTab - 1].image = nextProps.Create.uploadedAssetData.metaInfo.public_url;
      this.setState({formData});
      this.props.actions.clearAsset();
    }
    if (nextProps.params.mode) {
      this.setState({mode: nextProps.params.mode});
    }
    if (nextProps.Create.createTemplateError && !isEqual(nextProps.Create.createTemplateError, this.props.Create.createTemplateError)) {
      const message = getMessageObject('error', (nextProps.Create.createTemplateErrorMessage && nextProps.Create.createTemplateErrorMessage !== '') ? nextProps.Create.createTemplateErrorMessage : this.props.intl.formatMessage(messages.somethingWentWrong), true);
      this.props.onValidationFail();
      this.setState({showModal: false, startValidation: false});
      this.props.globalActions.addMessageToQueue(message);
    }
    if (nextProps.iosCtasData && isEmpty(this.state.templateCta)) {
      this.setState({showIosCtaTable: true});
    }
    if (nextProps.metaEntities && nextProps.metaEntities.layouts && nextProps.metaEntities.layouts.length > 0 && isEmpty(this.state.schema)) {
      const schema = this.props.params.mode === "text" ? nextProps.metaEntities.layouts[0].definition.textSchema : nextProps.metaEntities.layouts[0].definition.imageSchema;
      const isAndroidSupported = get(this, "props.Templates.selectedWeChatAccount.configs.android") === '1';
      const isIosSupported = get(this, "props.Templates.selectedWeChatAccount.configs.ios") === '1';
      if (!isAndroidSupported) {
        const androidField = get(schema, "containers[0].panes[0]");
        androidField.isSupported = false;
        this.setState({currentTab: 2});
        set(schema, "containers[0].panes[0]", androidField);
      }
      if (!isIosSupported) {
        const iosField = get(schema, "containers[0].panes[1]");
        iosField.isSupported = false;

        set(schema, "containers[0].panes[1]", iosField);
      }
      schema.standalone.sections.splice(1, 1);
      this.injectEvents(schema);
      if (!this.hasFetchedInitialTagsRef) {
        this.hasFetchedInitialTagsRef = true;
        const context = this.props.getDefaultTags
          || (this.props.location.query.type === 'embedded' ? this.props.location.query.module : 'default');
        this.lastFetchedTagContextRef = typeof context === 'string' ? context.toLowerCase() : context;
        const query = {
          layout: 'mobilepush',
          type: 'TAG',
          context: this.lastFetchedTagContextRef,
          embedded: this.props.location.query.type === 'embedded' ? this.props.location.query.type : 'full',
        };
        this.props.globalActions.fetchSchemaForEntity(query);
      }
    }
  };
  componentWillUnmount = () => {
    this.props.actions.resetStore();
    window.removeEventListener("message", this.handleFrameTasks);
  };
  onTemplateChange = () => {

  };

  onFormDataChange = (formData, tabCount, currentTab, inputField) => {
    const newFormData = cloneDeep(formData);
    const {templateCta} = this.state;
    const { defaultData = {}, isFullMode, showTemplateName} = this.props;
    
    // Check for personalization tokens if restriction is enabled and notify parent
    if (this.props.restrictPersonalization) {
      const hasTokens = checkForPersonalizationTokens(newFormData);
      if (this.props.onPersonalizationTokensChange) {
        this.props.onPersonalizationTokensChange(hasTokens);
      }
    }
    
    if (!isEmpty(templateCta)) {
      newFormData[this.state.currentTab - 1][`secondary-cta-${this.state.currentTab - 1}-label`] = get(templateCta, 'name');
      newFormData[this.state.currentTab - 1][`secondary-cta-${this.state.currentTab - 1}-action`] = get(templateCta, 'ctaTemplateDetails[0].buttonText');
      delete newFormData[this.state.currentTab - 1][`secondary-cta-${this.state.currentTab - 1}-action2`];
      if (get(templateCta, 'ctaTemplateDetails[1]')) {
        newFormData[this.state.currentTab - 1][`secondary-cta-${this.state.currentTab - 1}-action2`] = get(templateCta, 'ctaTemplateDetails[1].buttonText');
      }
    }


    const templateName = formData['template-name'];
    const defaultTemplateName = get(defaultData, 'template-name', '');


    // copy content code
    // if (newFormData[0]['copy-iphone-content'] === "") {
    //
    //   if(!!formData[1]['message-editor2'] && !!formData[1]['message-title2']){
    //     dispplayProps[0]['copy-iphone-content'] = true;
    //   }
    // } else {
    //   if(formData[1]['message-editor2'] === "" || formData[1]['message-title2'] === ""){
    //     newFormData[0]['copy-iphone-content'] = "";
    //   }
    // }
    // if (newFormData[1]['copy-android-content'] === "") {
    //
    //   if(!!formData[0]['message-editor'] && !!formData[0]['message-title']){
    //     newFormData[1]['copy-android-content'] = true;
    //   }
    // } else {
    //   if(formData[0]['message-editor'] === "" || formData[0]['message-title'] === ""){
    //     newFormData[1]['copy-android-content'] = "";
    //   }
    // }
     //assign newFormData['template-name'] to default name only once in inital render, if edited use latest form data
    if (isFullMode && defaultData && isEmpty(templateName) && !formData?.isTemplateNameEdited) {
      newFormData['template-name'] = defaultTemplateName;
    }

    if (inputField && inputField.id === "add-sec-cta") {
      if (!newFormData[0]["add-sec-cta"]) {
        newFormData[0]["add-sec-cta-2"] = false;
      }
    }
    const compareValue =
      newFormData?.[this.state?.currentTab - 1]?.[inputField?.id] || "";
    this.setState(
      {
        formData: newFormData,
        tabCount,
      },
      () => {
        if (isFullMode && showTemplateName) {
          showTemplateName({
            formData: this.state?.formData,
            onFormDataChange: this.onFormDataChange,
          });
        }
      }
    );
    this.setState({isSchemaChanged:
      (typeof compareValue === 'string' &&
        compareValue.toLowerCase() === EXTERNAL_LINK_LOWERCASE) ||
      !this.state?.isSchemaChanged});
  };

  onTagSelect = (data, currentTab, srcComp) => {
    const editorId = srcComp.target;
    this.insertAtCursor(document.getElementById(editorId), `{{${data}}}`, currentTab);
    document.getElementById(editorId).focus();
  };

  onTabChange = (data) => {
    this.setState({currentTab: data});
  };
  onTemplateNameChange = () => {
    //
  };


  onLinkTypeChange = (eventTriggered, formData, field) => {
    let schema = cloneDeep(this.state.schema);
    const inputFields = get(schema, `containers[0].panes[${this.state.currentTab - 1}].sections[0].childSections[0].childSections[0].inputFields`);
    
    forEach(inputFields, (inputField, fieldIndex) => {
      if (inputField) {
        forEach(inputField.cols, (col) => {
          if (col.id === field.id) {
            const deeplinks = this.props.Templates.selectedWeChatAccount && this.props.Templates.selectedWeChatAccount.configs && !!this.props.Templates.selectedWeChatAccount.configs.deeplink ? this.props.Templates.selectedWeChatAccount.configs.deeplink : '[]';
            const deepLinkOptions = this.props.Templates.selectedWeChatAccount ? map(JSON.parse(deeplinks), (link) => ({label: link.name, value: link.link, title: link.link }) ) : [];
            const deeplinkValue = formData[this.state.currentTab - 1][field.id];
            const componentIndex = fieldIndex + 1;
            const inputId = deeplinkValue && deeplinkValue.toLowerCase() === "deeplink" ? `${col.id}-select` : `${col.id}-text`;
            if ( deeplinkValue && deeplinkValue.toLowerCase() === "deeplink" && (fieldIndex === inputFields.length - 1 || inputFields[componentIndex].id !== "cta-deeplink-select-section")) {
              const row = {
                rowClassName: 'mobile-push-row',
                id: 'cta-deeplink-select-section',
                cols: [

                  {
                    id: inputId,
                    placeholder: this.props.intl.formatMessage(messages.selectDeeplink),
                    type: "select",  //Resembles component to be used
                    options: deepLinkOptions,
                    metaType: "text",
                    datatype: "string",
                    errorMessage: this.props.intl.formatMessage(messages.selectADeeplink),
                    required: true,
                    fluid: true,
                    width: 18,
                    offset: 1,
                    style: {
                      width: '100%',

                      marginBottom: '16px',
                    },
                    styling: "semantic",
                    order: 1,
                    customComponent: false,
                    supportedEvents: [
                      'onSelect',
                    ],
                  },
                ],
              };
              if (!inputFields[fieldIndex + 1] || inputFields[componentIndex].id === "cta-external-link") {
                inputFields[componentIndex] = row;
              } else {
                inputFields.splice(componentIndex, 0, row);
              }
            } else if ( deeplinkValue && deeplinkValue.toLowerCase() === "external link") {
              const row = {
                rowClassName: 'mobile-push-row',
                id: 'cta-external-link',
                cols: [
                  {
                    // Add label control for external link input
                    id: "title-tagList",
                    label: "Add label",
                    type: "tag-list",
                    metaType: "List",
                    datatype: "select",
                    required: true,
                    fluid: true,
                    onlyDisplay: true,
                    style: {
                      marginRight: "24%",
                      marginTop: "-3%",
                      display: 'flex',
                      justifyContent: 'end',
                      width: '100%',
                    },
                    styling: "semantic",
                    order: 2,
                    customComponent: true,
                    // Helps handler identify the destination input
                    target: inputId,
                    supportedEvents: [
                      "onTagSelect",
                    ],
                  },
                  {
                    id: inputId,
                    placeholder: this.props.intl.formatMessage(messages.externalLink),
                    type: "input",  //Resembles component to be used
                    metaType: "text",
                    datatype: "string",
                    errorMessage: <FormattedMessage {...messages.invalidExternalLink}/>,
                    required: true,
                    fluid: true,
                    width: 18,
                    offset: 1,
                    style: {
                      width: '95%',
                    },
                    styling: "semantic",
                    order: 1,
                    customComponent: false,
                    standalone: false,
                  },
                ],
              };
              if (!inputFields[fieldIndex + 1] || inputFields[componentIndex].id === "cta-deeplink-select-section") {
                inputFields[componentIndex] = row;
                if (inputFields[componentIndex + 1] && inputFields[componentIndex + 1].id === "show-cta-deeplink-keys-label") {
                  inputFields.splice(componentIndex + 1, 1);
                }
                if (inputFields[componentIndex + 1] && inputFields[componentIndex + 1].id === "cta-deeplink-keys") {
                  let configkeys = filter(JSON.parse(deeplinks), (dl) => dl.link === formData[this.state.currentTab - 1][`${col.id}-select`]);
                  if (configkeys[0]) {
                    configkeys = configkeys[0].keys;
                  }
                  if (configkeys.length) {
                    //inputFields = inputFields.slice(0, componentIndex + 1).concat(inputFields.slice( componentIndex + 1 + configkeys.length, inputFields.length));

                    inputFields.splice(componentIndex + 1, configkeys.length);
                  }
                }
              } else {
                inputFields.splice(componentIndex, 0, row);
              }
            }
          }
        });
      }
    });
    schema = set(schema, `containers[0].panes[${this.state.currentTab - 1}].sections[0].childSections[0].childSections[0].inputFields`, inputFields);
    this.setState({schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, isSchemaChanged: true});
    this.injectEvents(schema);
  };
  onTemplateContentChange = () => {

  };
  onModalCancel = () => {
    if (this.state.modalContent && this.state.modalContent.show) {
      this.setState({modalContent: {...this.state.modalContent, show: false}});
    }
  };
  getLinkName = (link) => {
    const ck = this.props.Templates.selectedWeChatAccount.configs ? !!this.props.Templates.selectedWeChatAccount.configs.deeplink : false;
    const deeplinks = ck ? this.props.Templates.selectedWeChatAccount.configs.deeplink : '[]';
    const deepLinkOptions = filter(JSON.parse(deeplinks), (l) => l.link === link);
    if (deepLinkOptions[0]) {
      return deepLinkOptions[0].name;
    }
    return undefined;
  };

  getMappedEvent = (id, event) => {
    const eventsMap = this.state.eventsMap;
    return eventsMap[id][event];
  };
  getCurrentWindow = (e) => {
    const response = {
      action: e.action,
      value: 'edit',
      direction: e.value,
    };
    parent.postMessage(JSON.stringify(response), '*');
  };
  getFormData = (e) => {
    const templateData = this.getTransformedData(this.state.formData);
    const response = {
      action: "getFormData",
      value: templateData,
      validity: this.state.isFormValid,
      type: templateData.type,
    };
    this.setState({checkValidation: true}, this.showError);
    if (e) {
      e.source.postMessage(JSON.stringify(response), e.origin);
    }
    return response;
  };
  setFormValidity = (isFormValid, errorData) => {

    const newState = {isFormValid, errorData};
    this.setState(newState);
  };
  getTransformedData = (formData) => {
    const obj = {};
    obj.versions = {
      base: {},
    };
    obj.type = 'MOBILEPUSH';
    obj.name = formData['template-name'];
    if (this.props?.Templates?.selectedWeChatAccount?.sourceTypeName === 'MAPP_SDK') {
      obj.definition = {
        accountId: this.props.Templates.selectedWeChatAccount.id,
        licenseCode: this.props.Templates.selectedWeChatAccount.sourceAccountIdentifier,
        gatewayId: this.props.Templates.selectedWeChatAccount.configs.gatewayId,
        gatewayAccountId: this.props.Templates.selectedWeChatAccount.configs.gatewayAccountId,
        mode: this.props.params.mode,
        sourceType: this.props.Templates.selectedWeChatAccount.sourceTypeName,
      };
    } else {
      obj.definition = {
        accountId: this.props.Templates.selectedWeChatAccount.id,
        licenseCode: this.props.Templates.selectedWeChatAccount.sourceAccountIdentifier,
        mode: this.props.params.mode,
        sourceType: this.props.Templates.selectedWeChatAccount.sourceTypeName,
      };
    }
    const android = {};
    Object.keys(formData[0]).forEach((data) => {
      if (!!formData[0][data] && data !== "tabKey") {
        android[data] = formData[0][data];
      }
    });
    const ios = {};
    Object.keys(formData[1]).forEach((data) => {
      if (!!formData[1][data] && data !== "tabKey") {
        ios[data] = formData[1][data];
      }
    });
    obj.versions.base = {};
    delete android.base;
    if (!isEmpty(android)) {
      obj.versions.base.ANDROID = {
        luid: "{{luid}}",
        cuid: "{{cuid}}",
        communicationId: "{{communicationId}}",
        title: android['message-title'],
        message: android['message-editor'],
        expandableDetails: {
          style: "BIG_TEXT",
          message: android['message-editor'],
        },
        custom: map(android, (field, key) => {
          if (key.indexOf('custom-value') > -1) {
            return field !== "" ? {key: key.replace('custom-value-', "").replace('-cta-deeplink-select', '').replace('-cta-deeplink-secondary-cta-0-select', '').replace('-cta-deeplink-secondary-cta-1-select', ''), value: field} : undefined;
          }
          return undefined;
        }).filter((custom) => custom),
      };
      obj.name = isEmpty(obj.name) ? android['message-title'] : obj.name;
    }
    if (android['cta-deeplink'] && android['cta-deeplink'] !== "") {
      obj.versions.base.ANDROID.cta = {
        type: android['cta-deeplink'] && android['cta-deeplink'].toLowerCase() === "deeplink" ? "DEEP_LINK" : "EXTERNAL_URL",
        actionLink: android['cta-deeplink'] && android['cta-deeplink'].toLowerCase() === "deeplink" ? android['cta-deeplink-select'] : android['cta-deeplink-text'],
        deepLinkName: android['cta-deeplink'] && android['cta-deeplink'].toLowerCase() === "deeplink" ? this.getLinkName(android['cta-deeplink-select']) : undefined,
      };
      if (this.props.location.query.type === 'embedded') {
        delete obj.versions.base.ANDROID.cta.deepLinkName;
      }
    }
    if (!isEmpty(ios)) {
      obj.versions.base.IOS = {
        luid: "{{luid}}",
        cuid: "{{cuid}}",
        communicationId: "{{communicationId}}",
        title: ios['message-title2'],
        message: ios['message-editor2'],
        expandableDetails: {
          style: "BIG_TEXT",
          message: ios['message-editor2'],
          ctas: [
          ],
        },
        custom: map(ios, (field, key) => {
          if (key.indexOf('custom-value') > -1) {
            return field !== "" ? {key: key.replace('custom-value-', "").replace('-cta-deeplink2-select', '').replace('-cta-deeplink-secondary-cta-0-select', '').replace('-cta-deeplink-secondary-cta-1-select2', ''), value: field} : undefined;
          }
          return undefined;
        }).filter((custom) => custom),
      };
      obj.name = isEmpty(obj.name) ? ios['message-title2'] : obj.name;
    }
    if (ios['cta-deeplink2'] && ios['cta-deeplink2'] !== "") {
      obj.versions.base.IOS.cta = {
        type: ios['cta-deeplink2'] && ios['cta-deeplink2'].toLowerCase() === "deeplink" ? "DEEP_LINK" : "EXTERNAL_URL",
        actionLink: ios['cta-deeplink2'] && ios['cta-deeplink2'].toLowerCase() === "deeplink" ? ios['cta-deeplink2-select'] : ios['cta-deeplink2-text'],
        deepLinkName: ios['cta-deeplink2'] && ios['cta-deeplink2'].toLowerCase() === "deeplink" ? this.getLinkName(ios['cta-deeplink2-select']) : undefined,
      };
      if (this.props.location.query.type === 'embedded') {
        delete obj.versions.base.IOS.cta.deepLinkName;
      }
    }
    if (obj.versions.base.ANDROID) {
      if (obj.versions.base.ANDROID.cta && obj.versions.base.ANDROID.cta.type === "DEEP_LINK") {
        const params = map(android, (field, key) => {
          let actionLink;
          if (key.indexOf('custom-value') > -1 && key.indexOf('cta-deeplink-select') > -1) {
            const param = key.replace('custom-value-', "").replace('-cta-deeplink-select', '');
            actionLink = field !== "" ? `${param}=${field}` : undefined;
          }
          return actionLink;
        }).filter((actionLink) => actionLink);
        if (params.length) {
          obj.versions.base.ANDROID.cta.actionLink = `${obj.versions.base.ANDROID.cta.actionLink}?${params.join('&')}`;
        }
      }
      const secondaryCta1 = !!android["cta-deeplink-secondary-cta-0-select"] || !!android['secondary-cta-0-label'];
      const secondaryCta2 = !!android['cta-deeplink-secondary-cta-1-select'] || !!android['secondary-cta-1-label'];
      const imageLink = android.image;
      if (imageLink) {
        obj.versions.base.ANDROID.expandableDetails.image = getCdnUrl({url: imageLink, channelName: 'MOBILE_PUSH'});
        obj.versions.base.ANDROID.expandableDetails.style = "BIG_PICTURE";
      }
      if (secondaryCta1 || secondaryCta2 ) {
        obj.versions.base.ANDROID.expandableDetails.ctas = [];
        if (secondaryCta1) {
          const cta = {
            actionText: android['secondary-cta-0-label'],
            type: (android['cta-deeplink-secondary-cta-0'] || '').toLowerCase() === "deeplink" ? "DEEP_LINK" : "EXTERNAL_URL",
            actionLink: (android['cta-deeplink-secondary-cta-0'] || '').toLowerCase() === "deeplink" ? android['cta-deeplink-secondary-cta-0-select'] : android['cta-deeplink-secondary-cta-0-text'],
            seccdeepLinkName: this.getLinkName(android['cta-deeplink-secondary-cta-0-select']),
          };
          if (this.props.location.query.type === 'embedded') {
            delete cta.seccdeepLinkName;
          }
          obj.versions.base.ANDROID.expandableDetails.ctas.push(cta);
          if (obj.versions.base.ANDROID.expandableDetails.ctas[obj.versions.base.ANDROID.expandableDetails.ctas.length - 1].type === "DEEP_LINK") {
            const params = map(android, (field, key) => {
              let actionLink;
              if (key.indexOf('custom-value') > -1 && key.indexOf('cta-deeplink-secondary-cta-0-select') > -1) {
                const param = key.replace('custom-value-', "").replace('-cta-deeplink-secondary-cta-0-select', '');
                actionLink = field !== "" ? `${param}=${field}` : undefined;
              }
              return actionLink;
            }).filter((actionLink) => actionLink);
            if (params.length) {
              obj.versions.base.ANDROID.expandableDetails.ctas[obj.versions.base.ANDROID.expandableDetails.ctas.length - 1].actionLink = `${obj.versions.base.ANDROID.expandableDetails.ctas[obj.versions.base.ANDROID.expandableDetails.ctas.length - 1].actionLink}?${params.join('&')}`;
            }
          }
        }
        if (secondaryCta2) {
          const cta = {
            actionText: android['secondary-cta-1-label'],
            type: (android['cta-deeplink-secondary-cta-1'] || '').toLowerCase() === "deeplink" ? "DEEP_LINK" : "EXTERNAL_URL",
            actionLink: (android['cta-deeplink-secondary-cta-1'] || '').toLowerCase() === "deeplink" ? android['cta-deeplink-secondary-cta-1-select'] : android['cta-deeplink-secondary-cta-1-text'],
            seccdeepLinkName: this.getLinkName(android['cta-deeplink-secondary-cta-1-select']),
          };
          if (this.props.location.query.type === 'embedded') {
            delete cta.seccdeepLinkName;
          }
          obj.versions.base.ANDROID.expandableDetails.ctas.push(cta);
          if (obj.versions.base.ANDROID.expandableDetails.ctas[obj.versions.base.ANDROID.expandableDetails.ctas.length - 1].type === "DEEP_LINK") {
            const params = map(android, (field, key) => {
              let actionLink;
              if (key.indexOf('custom-value') > -1 && key.indexOf('cta-deeplink-secondary-cta-1-select') > -1) {
                const param = key.replace('custom-value-', "").replace('-cta-deeplink-secondary-cta-1-select', '');
                actionLink = field !== "" ? `${param}=${field}` : undefined;
              }
              return actionLink;
            }).filter((actionLink) => actionLink);
            if (params.length) {
              obj.versions.base.ANDROID.expandableDetails.ctas[obj.versions.base.ANDROID.expandableDetails.ctas.length - 1].actionLink = `${obj.versions.base.ANDROID.expandableDetails.ctas[obj.versions.base.ANDROID.expandableDetails.ctas.length - 1].actionLink}?${params.join('&')}`;
            }
          }
        }
      }
    }
    if (obj.versions.base.IOS) {
      if (obj.versions.base.IOS.cta && obj.versions.base.IOS.cta.type === "DEEP_LINK") {
        const params = map(ios, (field, key) => {
          let actionLink;
          if (key.indexOf('custom-value') > -1 && key.indexOf('cta-deeplink2-select') > -1) {
            const param = key.replace('custom-value-', "").replace('-cta-deeplink2-select', '');
            actionLink = field !== "" ? `${param}=${field}` : undefined;
          }
          return actionLink;
        }).filter((actionLink) => actionLink);
        if (params.length) {
          obj.versions.base.IOS.cta.actionLink = `${obj.versions.base.IOS.cta.actionLink}?${params.join('&')}`;
        }
      }
      const imageLinkIos = ios.image;
      const secondaryCtaIos = !!ios['cta-deeplink-secondary-cta-1-select'] || !!ios['secondary-cta-1-label'];
      if (imageLinkIos) {
        obj.versions.base.IOS.expandableDetails.image = getCdnUrl({url: imageLinkIos, channelName: 'MOBILE_PUSH'});
        obj.versions.base.IOS.expandableDetails.style = "BIG_PICTURE";
      }
      if (secondaryCtaIos) {
        obj.versions.base.IOS.expandableDetails.ctas = [];
        const templateCtaId = get(this.state, "templateCta.ctaTemplateDetails[0].id");
        const cta = {
          actionText: ios['secondary-cta-1-label'],
          actionLabel: ios['secondary-cta-1-action'],
          actionLabel2: ios['secondary-cta-1-action2'],
          type: ios['cta-deeplink-secondary-cta-1'] && (ios['cta-deeplink-secondary-cta-1'].toLowerCase() === "deeplink" ? "DEEP_LINK" : "EXTERNAL_URL"),
          actionLink: ios['cta-deeplink-secondary-cta-1'] && (ios['cta-deeplink-secondary-cta-1'].toLowerCase() === "deeplink" ? (ios['cta-deeplink-secondary-cta-1-select2'] || ios['cta-deeplink-secondary-cta-1-select']) : ios['cta-deeplink-secondary-cta-1-text']),
          ioscdeepLinkName: this.getLinkName(ios['cta-deeplink-secondary-cta-1-select']),
          templateCtaId,
        };
        if (this.props.location.query.type === 'embedded') {
          delete cta.ioscdeepLinkName;
        }
        obj.versions.base.IOS.expandableDetails.ctas.push(cta);
        obj.versions.base.IOS.expandableDetails.categoryId = get(this.state, "templateCta.id");
        if (obj.versions.base.IOS.expandableDetails.ctas[obj.versions.base.IOS.expandableDetails.ctas.length - 1].type === "DEEP_LINK") {
          const params = map(ios, (field, key) => {
            let actionLink;
            if (key.indexOf('custom-value') > -1 && key.indexOf('cta-deeplink-secondary-cta-1-select') > -1) {
              const param = key.replace('custom-value-', "").replace('-cta-deeplink-secondary-cta-1-select2', '');
              actionLink = field !== "" ? `${param}=${field}` : undefined;
            }
            return actionLink;
          }).filter((actionLink) => actionLink);
          if (params.length) {
            obj.versions.base.IOS.expandableDetails.ctas[obj.versions.base.IOS.expandableDetails.ctas.length - 1].actionLink = `${obj.versions.base.IOS.expandableDetails.ctas[obj.versions.base.IOS.expandableDetails.ctas.length - 1].actionLink}?${params.join('&')}`;
          }
        }
      }
    }
    return obj;
  };

  setModalContent = (type) => {
    if (type === 'ios') {
      const modalContent = {
        title: this.props.intl.formatMessage(messages.alertMessage),
        body: this.props.intl.formatMessage(messages.androidNotConfigured),
        type: 'confirm',
        id: 'ios',
      };
      this.setState({modalContent, showModal: true});
    } else if (type === 'android') {
      const modalContent = {
        title: this.props.intl.formatMessage(messages.alertMessage),
        body: this.props.intl.formatMessage(messages.iosNotConfigured),
        type: 'confirm',
        id: 'android',
      };
      this.setState({modalContent, showModal: true});
    }
  }
  showError = () => {
    const {intl} = this.props;
    const {errorData, schema} = this.state;
    const errorMessage = {key: 'validation-error', message: intl.formatMessage(messages.validationError)};
    if (!isEmpty(this.state.formData) && !this.state.isFormValid) {
      let tab = this.state.currentTab;
      const isAndroidInvalid = Object.values(errorData[0] || {}).includes(true);
      const isIosInvalid = Object.values(errorData[1] || {}).includes(true);
      const isIosTabVisible = get(schema, 'containers[0].panes[1].isSupported', true) !== false;
      if (isAndroidInvalid) {
        tab = 1;
        errorMessage.description = intl.formatMessage(messages.invalidAndroidMessage);
      } else if (isIosInvalid && isIosTabVisible) {
        tab = 2;
        errorMessage.description = intl.formatMessage(messages.invalidIosMessage);
      }
      if (tab !== this.state.currentTab) {
        CapNotification.error(errorMessage);
      }
    }
  }
  stopValidation = () => {
    this.setState({startValidation: false}, () => {
      this.showError();
      this.props.onValidationFail();
    });
  }
  startValidation = () => {
    this.setState({startValidation: true});
  }
  openNotificationWithIcon = (type, message) => {
    const dur = (type === 'error' || type === 'warning') ? null : 5;
    notification[type]({
      message: (`${type.toUpperCase()} ! ! ! `),
      description: message, //'This is the content of the notification. This is the content of the notification. This is the content of the notification.',
      duration: dur,
    });
  }

  handleCancelModal = () => {
    this.setState({showModal: false}, this.stopValidation);
  };

  moveToTemplates = () => {
    const modalContent = {
      title: this.props.intl.formatMessage(messages.alertMessage),
      body: this.props.intl.formatMessage(messages.goBackTemporaryChangesLost),
      type: 'confirm',
      id: 'template-back-confirm-modal',
      show: true,
    };
    this.setState({modalContent, showModal: true});
  };

  cancelTemplate = () => {
    const type = this.props.location.query.type;
    const module = this.props.location.query.module ? this.props.location.query.module : 'default';
    this.props.router.push({
      pathname: `/MOBILEPUSH/`,
      query: type === 'embedded' ? {type: 'embedded', module} : {module},
    });
  };

  injectEvents = (schema) => {
    const temp = schema;
    if (temp.standalone) {
      temp.standalone.sections = this.injectSections(temp.standalone.sections);
    }
    forEach(temp.containers, (container) => {
      let tempContainer = container;
      tempContainer = this.injectContainer(tempContainer);
      return tempContainer;
    });

    this.setState({schema, isSchemaChanged: true}, () => {
      this.removeStandAlone();
    });
    return schema;
  };

  injectContainer = (container) => {
    const temp = container;
    if (temp.type === 'tabs') {
      temp.injectedEvents = {};
      forEach(temp.supportedEvents, (event) => {
        temp.injectedEvents[event] = this.getMappedEvent(temp.id, event);
      });
      forEach(temp.panes, (pane) => {
        const tempPane = pane;
        tempPane.sectionsHeaders = this.injectSections(tempPane.sectionsHeaders);
        tempPane.sections = this.injectSections(tempPane.sections);
      });
    }
    return temp;
  };

  injectMultiColSection = (section) => {
    const { formatMessage } = this.props.intl;
    forEach(section.inputFields, (inputField) => {
      forEach(inputField.cols, (col) => {
        const temp = col;
        if (temp.type === 'popover') {
          temp.content.sections = this.injectSections(temp.content.sections);
          temp.value.sections = this.injectSections(temp.value.sections);
          return true;
        }
        if (temp.id === "discard-button") {
          temp.colStyle = {...temp.colStyle, display: 'none'};
        }
        if (temp.id === "cancel-button") {
          temp.offset = 11;
        }
        if (temp.id === "mobile-push-preview") {
          temp.content.appName = this.props.Templates.selectedWeChatAccount.name;
        }

        if (messages?.[temp?.value]) {
          temp.value = formatMessage(messages[temp.value]);
        }
        if (messages?.[temp?.label]) {
          temp.label = formatMessage(messages[temp.label]);
        }
        if (messages?.[temp?.errorMessage]) {
          temp.errorMessage = formatMessage(messages[temp.errorMessage]);
        }
        if (messages?.[temp?.placeholder]) {
          temp.placeholder = formatMessage(messages[temp.placeholder]);
        }
        if (messages?.[temp?.hoverText]) {
          temp.hoverText = formatMessage(messages[temp.hoverText]);
        }
        if (messages?.[temp?.previewProps?.label]) {
          temp.previewProps.label = formatMessage(messages[temp.previewProps.label]);
        }
        if (messages?.[temp?.previewProps?.inductiveText]) {
          temp.previewProps.inductiveText = formatMessage(messages[temp.previewProps.inductiveText]);
        }
        if (messages?.[temp?.previewProps?.errorMessage]) {
          temp.previewProps.errorMessage = formatMessage(messages[temp.previewProps.errorMessage]);
        }

        temp.injectedEvents = {};

        forEach(col.supportedEvents, (event) => {
          temp.injectedEvents[event] = this.getMappedEvent(col.id, event);
        });
        return true;
      });
    });
    forEach(section.actionFields, (actionField) => {
      forEach(actionField.cols, (col) => {
        const temp = col;
        if (temp.type === 'popover') {
          temp.content.sections = this.injectSections(temp.content.sections);
          temp.value.sections = this.injectSections(temp.value.sections);
          return true;
        }
        temp.injectedEvents = {};
        forEach(col.supportedEvents, (event) => {
          temp.injectedEvents[event] = this.getMappedEvent(col.id, event);
        });
        return true;
      });
    });
    return section;
  };

  injectColLabelSection = (section) => {
    forEach(section.inputFields, (inputField) => {
      const temp = inputField;
      if (temp.type === 'popover') {
        temp.content.sections = this.injectSections(temp.content.sections);
        temp.value.sections = this.injectSections(temp.value.sections);
        return true;
      }
      temp.injectedEvents = {};
      forEach(inputField.supportedEvents, (event) => {
        temp.injectedEvents[event] = this.getMappedEvent(inputField.id, event);
      });
      return true;
    });
    forEach(section.actionFields, (actionField) => {
      const temp = actionField;
      if (temp.type === 'popover') {
        temp.content.sections = this.injectSections(temp.content.sections);
        temp.value.sections = this.injectSections(temp.value.sections);
        return true;
      }
      temp.injectedEvents = {};
      forEach(actionField.supportedEvents, (event) => {
        temp.injectedEvents[event] = this.getMappedEvent(actionField.id, event);
      });
      return true;
    });
    return section;
  };

  injectSections = (sections) => {
    forEach(sections, (section) => {
      let temp = section;
      if (temp.type === 'col-label') {
        temp = this.injectColLabelSection(temp);
      } else if (section.type === 'multicols') {
        temp = this.injectMultiColSection(temp);
      } else if (section.type === 'parent') {
        temp = this.injectSections(temp.childSections);
      }
    });
    return sections;
  };

  injectParentSection = (section) => {
    forEach(section.childSections, (childSection) => {
      let temp = childSection;
      if (temp.type === 'col-label') {
        temp = this.injectColLabelSection(temp);
      } else if (section.type === 'multicols') {
        temp = this.injectMultiColSection(temp);
      } else if (section.type === 'parent') {
        temp = this.injectParentSection(temp);
      }
    });
    return section;
  };
  insertAtCursor = (field, myValue, currentTab) => {
    //IE support
    const myField = field;
    if (document.selection) {
      myField.focus();
      const sel = document.selection.createRange();
      sel.text = myValue;
    } else if (myField.selectionStart || myField.selectionStart === '0') { //MOZILLA and others
      const startPos = myField.selectionStart;
      const endPos = myField.selectionEnd;
      myField.value = myField.value.substring(0, startPos)
        + myValue
        + myField.value.substring(endPos, myField.value.length);
      myField.selectionStart = startPos + myValue.length;
      myField.selectionEnd = startPos + myValue.length;
    } else {
      myField.value += myValue;
    }
    const formData = cloneDeep(this.state.formData);
    formData[currentTab - 1][field.id] = myField.value;
    this.setState({formData});
  };

  startTemplateCreation = (data) => {
    const content = data.content;
    const id = uniqueId();
    const tempData = {
      'message-editor': content,
      'base': true,
      'tabKey': id,
    };
    const formData = {};
    formData[0] = tempData;
    formData.base = tempData;
    this.setState({formData, loading: false});
    if (data.tags) {
      this.props.globalActions.setInjectedTags(data.tags);
    }
  };

  startLoading = (ifEdit) => {
    if (ifEdit) {
      this.setState({loading: true});
    }
  };

  handleFrameTasks = (e) => {
    const type = e.data;

    if (typeof type === 'object') {
      const action = type.action;
      switch (action) {
        case "startTemplateCreation":
          this.startTemplateCreation(type.value);
          break;
        case "startLoading":
          this.startLoading(type.edit);
          break;
        case "getCurrentWindow":
          this.getCurrentWindow(type);
          break;
        default:
          break;
      }
    } else {
      switch (type) {
        case "getFormData":
          this.getFormData(e);
          break;
        case "startTemplateCreation":

          //this.getFormData(e);
          break;
        case "moveToTemplates":

          this.moveToTemplates();
          break;
        case "validateContent":

          this.validateContent(e);
          break;
        default:
          break;
      }
    }
  };

  removeStandAlone = () => {
    const schema = cloneDeep(this.state.schema);
    if (this.props.location.query.type === 'embedded' && this.props.location.query.module === 'loyalty') {
      schema.standalone.sections.splice(0, 1);
    } else if ((this.props.location.query.type === 'embedded' && typeof this.props.location.query.module !== 'undefined') || this.props.isFullMode) {
      delete schema.standalone;
    } else {
      schema.standalone.sections.splice(1, 1);
    }
    this.setState({ schema });
  };

  validateContent = (e) => {
    const response = {
      action: "validateContent",
      value: this.state.isFormValid,
    };
    e.source.postMessage(JSON.stringify(response), e.origin);
  };

  discardValues = () => {
    this.resetSchema();
    this.resetState();
  };

  resetState = () => {
    this.setState({
      formData: {},
      tabCount: 1,
      currentTab: 1,
    });
  };
  resetSchema = () => {
    this.setState({ schema: this.state.initialState ? this.state.initialState : this.state.schema});
  };
  showNext = () => {
    const response = {
      action: "showNext",
      value: true,
    };
    parent.postMessage(JSON.stringify(response), '*');
  };
  copyContent = () => {

  };
  addSecondoryCtaIos = (flag, formData, schemaField) => {
    const id = schemaField.id;
    if (formData[this.state.currentTab - 1][id]) {
      if (!this.props.iosCtasData) {
        this.props.actions.getIosCtas(this.props.Templates.selectedWeChatAccount.sourceAccountIdentifier);//TODO: need to get license code of accoutn and send as arg
      } else {
        this.deleteSecondaryCtaIos(() => { // oncick of change
          this.setState({showIosCtaTable: true});
        });
      }
    } else {
      const schema = cloneDeep(this.state.schema);
      const inputFields = get(schema, `containers[0].panes[${this.state.currentTab - 1}].sections[0].childSections[0].childSections[0].inputFields`);
      forEach(inputFields, (inputField, fieldIndex) => {
        forEach(inputField.cols, (col) => {
          if (col.id === id) {
            const indexOfNextField = inputFields.length;
            const deleteCount = indexOfNextField - fieldIndex;
            const newInputFields = [...inputFields.slice(0, fieldIndex + 1), ...inputFields.slice(fieldIndex + deleteCount, inputField.length)];
            set(schema, `containers[0].panes[${this.state.currentTab - 1}].sections[0].childSections[0].childSections[0].inputFields`, newInputFields);
            this.setState({schema});
          }
        });
      });
    }
  };
  showSelectedIosCta = (selectedConfig) => {
    const currentTab = this.state.currentTab;
    const schema = cloneDeep(this.state.schema);
    const deeplinks = this.props.Templates.selectedWeChatAccount && this.props.Templates.selectedWeChatAccount.configs && !!this.props.Templates.selectedWeChatAccount.configs.deeplink ? this.props.Templates.selectedWeChatAccount.configs.deeplink : '[]';
    const deepLinkOptions = this.props.Templates.selectedWeChatAccount ? map(JSON.parse(deeplinks), (link) => ({label: link.name, value: link.link, title: link.link }) ) : [];
    const inputFields = get(schema, `containers[0].panes[${this.state.currentTab - 1}].sections[0].childSections[0].childSections[0].inputFields`);
    forEach(inputFields, (inputField, fieldIndex) => {
      forEach(inputField.cols, (col) => {
        if (col.id === "add-sec-cta-ios") {
          const inputId = `secondary-cta-${currentTab - 1}`;

          inputFields.splice(fieldIndex + 1, 0, {
            rowClassName: 'mobile-push-row',
            cols: [
              {
                id: `${inputId}-action-display`,
                metaType: "label",
                value: <CapRow>
                  <CapColumn span={18}>
                    <CapHeader
                      title={this.state.templateCta.name}
                      description={get(this.state, "templateCta.ctaTemplateDetails[0].buttonText")}
                      size={"label"}/>
                  </CapColumn>
                  <CapColumn span={6}>
                    <CapLink title={this.props.intl.formatMessage(messages.change)} onClick={() => this.addSecondoryCtaIos(true, this.state.formData, {id: "add-sec-cta-ios"})}/>
                  </CapColumn>
                </CapRow>,
                primitive: true,
                dynamicTab: false,
                type: "div",
                width: 18,
                offset: 1,
              },
              {
                id: `${inputId}-action`,
                metaType: "label",
                value: "",
                primitive: true,
                dynamicTab: false,
                type: "div",
                width: 8,
                offset: 0,
                style: {
                  display: 'none',
                },
              },
              {
                id: `${inputId}-action2`,
                metaType: "label",
                value: "",
                primitive: true,
                dynamicTab: false,
                type: "div",
                width: 8,
                offset: 0,
                style: {display: 'none'},
              },

            ],
          });
          const selectedConfigTemplateCtaId = get(selectedConfig, 'ctaTemplateDetails[0].id');
          // the option to select deeplink and externa link should not come for these ctas
          if (selectedConfigTemplateCtaId && (selectedConfigTemplateCtaId.id !== "3heicig" && selectedConfigTemplateCtaId.id !== "6eigf4f" && selectedConfigTemplateCtaId.id !== "c97d0ed")) {
            inputFields.splice(fieldIndex + 2, 0, {
              rowClassName: "mobile-push-row",
              cols: [

                {
                  id: `cta-deeplink-${inputId}`,
                  type: "radioGroup",  //Resembles component to be used
                  metaType: "text",
                  datatype: "string",
                  options: ["Deeplink", "External Link"],
                  inductiveText: [<FormattedMessage {...messages.aPageWithMobileApp}/>, <FormattedMessage {...messages.anExternalWebPage}/>],
                  value: "Deeplink",
                  required: true,
                  width: 18,
                  offset: 1,
                  errorMessage: this.props.intl.formatMessage(messages.selectLinkType),
                  fluid: true,

                  styling: "semantic",
                  order: 1,
                  supportedEvents: ["onChange"],
                  customComponent: false,
                },
              ],
            });
            inputFields.splice(fieldIndex + 3, 0, {
              rowClassName: 'mobile-push-row',
              id: 'cta-deeplink-select-section',
              cols: [

                {
                  id: `cta-deeplink-${inputId}-select2`,
                  placeholder: this.props.intl.formatMessage(messages.selectDeeplink),
                  type: "select",  //Resembles component to be used
                  options: deepLinkOptions,
                  metaType: "text",
                  datatype: "string",
                  errorMessage: this.props.intl.formatMessage(messages.selectADeeplink),
                  required: true,
                  fluid: true,
                  width: 18,
                  offset: 1,
                  style: {
                    width: '100%',
                    marginBottom: '16px',
                  },
                  styling: "semantic",
                  order: 1,
                  customComponent: false,
                  supportedEvents: [
                    'onSelect',
                  ],
                },
              ],
            });
          }
        }
      });
    });
    // set(schema, `containers[0].panes[${this.state.currentTab - 1}].sections[0].childSections[0].childSections[0].inputFields`, inputFields);

    this.setState({schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, isSchemaChanged: true});
    this.injectEvents(schema);
  };
  addPrimaryCta = (flag, formData, schemaField) => {
    const id = schemaField.id;
    const schema = cloneDeep(this.state.schema);
    const deeplinks = this.props.Templates.selectedWeChatAccount && this.props.Templates.selectedWeChatAccount.configs && !!this.props.Templates.selectedWeChatAccount.configs.deeplink ? this.props.Templates.selectedWeChatAccount.configs.deeplink : '[]';
    const deepLinkOptions = this.props.Templates.selectedWeChatAccount ? map(JSON.parse(deeplinks), (link) => ({label: link.name, value: link.link, title: link.link }) ) : [];
    // const eventsMap = cloneDeep(this.state.eventsMap);
    const inputFields = get(schema, `containers[0].panes[${this.state.currentTab - 1}].sections[0].childSections[0].childSections[0].inputFields`);
    forEach(inputFields, (inputField, fieldIndex) => {
      forEach(inputField.cols, (col) => {
        const colId = col.id;
        if (colId === id) {
          if (formData[this.state.currentTab - 1][id]) { // add primary cta
            inputFields.splice(fieldIndex + 1, 0, {
              rowClassName: 'mobile-push-row',
              cols: [
                {
                  id: `cta-deeplink${this.state.currentTab > 1 ? this.state.currentTab : ''}`,
                  type: "radioGroup",  //Resembles component to be used
                  metaType: "text",
                  datatype: "string",
                  options: ["Deeplink", "External Link"],
                  inductiveText: [<FormattedMessage {...messages.aPageWithMobileApp}/>, <FormattedMessage {...messages.anExternalWebPage}/>],
                  value: "Deeplink",
                  required: true,
                  width: 18,
                  offset: 1,
                  errorMessage: this.props.intl.formatMessage(messages.selectLinkType),
                  fluid: true,
                  styling: "semantic",
                  order: 1,
                  customComponent: false,
                  supportedEvents: ["onChange"],
                },

              ],
            });
            inputFields.splice(fieldIndex + 2, 0, {
              rowClassName: 'mobile-push-row',
              id: 'cta-deeplink-select-section',
              cols: [

                {
                  id: `cta-deeplink${this.state.currentTab > 1 ? this.state.currentTab : ''}-select`,
                  placeholder: this.props.intl.formatMessage(messages.selectDeeplink),
                  type: "select",  //Resembles component to be used
                  options: deepLinkOptions,
                  metaType: "text",
                  datatype: "string",
                  required: true,
                  errorMessage: this.props.intl.formatMessage(messages.selectADeeplink),
                  fluid: true,
                  width: 18,
                  offset: 1,
                  style: {
                    width: '100%',


                    marginBottom: '16px',
                  },
                  styling: "semantic",
                  order: 1,
                  customComponent: false,
                  supportedEvents: [
                    'onSelect',
                  ],
                },
              ],
            });
          } else { // remove existing primary cta cuz primary cta is unchecked
            const identifier = (this.state.currentTab - 1) ? 'add-sec-cta-ios' : 'add-sec-cta';
            const indexOfNextField = findIndex(inputFields, {identifier});
            const deleteCount = indexOfNextField - fieldIndex;
            const newInputFields = [...inputFields.slice(0, fieldIndex + 1), ...inputFields.slice(fieldIndex + deleteCount, inputFields.length)];
            set(schema, `containers[0].panes[${this.state.currentTab - 1}].sections[0].childSections[0].childSections[0].inputFields`, newInputFields);
          }
        }
      });
    });
    this.setState({schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, isSchemaChanged: true, formData}, () => this.injectEvents(schema));
  };
  addSecondoryCta = (flag, formData, schemaField) => {
    const id = schemaField.id;
    const schema = cloneDeep(this.state.schema);
    const formDataCopy = cloneDeep(formData);
    const ck = this.props.Templates.selectedWeChatAccount.configs ? !!this.props.Templates.selectedWeChatAccount.configs.deeplink : false;
    const deeplinks = ck ? this.props.Templates.selectedWeChatAccount.configs.deeplink : '[]';
    const deepLinkOptions = this.props.Templates.selectedWeChatAccount ? map(JSON.parse(deeplinks), (link) => ({label: link.name, value: link.link, title: link.link }) ) : [];
    // const eventsMap = cloneDeep(this.state.eventsMap);
    const inputFields = get(schema, `containers[0].panes[${this.state.currentTab - 1}].sections[0].childSections[0].childSections[0].inputFields`);
    forEach(inputFields, (inputField, fieldIndex) => {
      forEach(inputField.cols, (col) => {
        if (col.id === id) {
          if (formData[this.state.currentTab - 1][id]) {
            const inputId = `secondary-cta-${col.fieldsCount}`;
            inputFields.splice(fieldIndex + 1, 0, {
              rowClassName: 'mobile-push-row',
              cols: [

                {
                  id: `${inputId}-label`,
                  label: "Button label",
                  type: "input",  //Resembles component to be used
                  metaType: "text",
                  datatype: "string",
                  required: true,
                  width: 18,
                  offset: 1,
                  placeholder: this.props.intl.formatMessage(messages.enterCTALabel),
                  fluid: true,
                  styling: "semantic",
                  order: 1,
                  customComponent: false,
                  errorMessage: this.props.intl.formatMessage(messages.ctaLabelCantEmpty),
                },

              ],
            });
            inputFields.splice(fieldIndex + 2, 0, {
              rowClassName: 'mobile-push-row',
              cols: [

                {
                  id: `cta-deeplink-${inputId}`,
                  type: "radioGroup",  //Resembles component to be used
                  metaType: "text",
                  datatype: "string",
                  options: ["Deeplink", "External Link"],
                  inductiveText: [<FormattedMessage {...messages.aPageWithMobileApp}/>, <FormattedMessage {...messages.anExternalWebPage}/>],
                  value: "Deeplink",
                  required: true,
                  width: 18,
                  offset: 1,
                  errorMessage: this.props.intl.formatMessage(messages.selectLinkType),
                  fluid: true,
                  styling: "semantic",
                  order: 1,

                  customComponent: false,
                  supportedEvents: ["onChange"],
                },
              ],
            });
            inputFields.splice(fieldIndex + 3, 0, {
              rowClassName: 'mobile-push-row',
              id: 'cta-deeplink-select-section',
              cols: [


                {
                  id: `cta-deeplink-${inputId}-select`,
                  placeholder: this.props.intl.formatMessage(messages.selectDeeplink),
                  type: "select",  //Resembles component to be used
                  options: deepLinkOptions,
                  errorMessage: this.props.intl.formatMessage(messages.selectADeeplink),
                  metaType: "text",
                  datatype: "string",
                  required: true,
                  fluid: true,
                  width: 18,
                  offset: 1,
                  style: {
                    width: '100%',
                    marginBottom: '16px',
                  },
                  styling: "semantic",
                  order: 1,
                  customComponent: false,
                  supportedEvents: [
                    'onSelect',
                  ],
                },
              ],
            });

            // eventsMap[`cta-deeplink-${inputId}`] = {"onChange": this.onLinkTypeChange};
          } else {
            const identifier = id === "add-sec-cta" ? 'add-sec-cta-2' : null;
            const indexOfNextField = identifier ? findIndex(inputFields, {identifier}) : inputFields.length;
            const deleteCount = indexOfNextField - fieldIndex;
            const newInputFields = [...inputFields.slice(0, fieldIndex + 1), ...inputFields.slice(fieldIndex + deleteCount, inputFields.length)];
            set(schema, `containers[0].panes[${this.state.currentTab - 1}].sections[0].childSections[0].childSections[0].inputFields`, newInputFields);
          }
        }
      });
    });
    if (id === "add-sec-cta") {
      //The following block of code enables and disables add secondary button based on the primary button
      const indexOfSecondary = findIndex(inputFields, {identifier: 'add-sec-cta-2'});
      inputFields[indexOfSecondary].cols[0].disabled = !formData[this.state.currentTab - 1][id];
      //Calling the following function to unset the data set under secondary button
      if (!formData[this.state.currentTab - 1][id]) {
        formDataCopy[this.state.currentTab - 1]['add-sec-cta-2'] = false;
      }
      //Calling set state here to update the state and schema before manually triggering secondarycta update
      this.setState(
        {schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, isSchemaChanged: true},
        () => {
          this.injectEvents(schema);
          this.addSecondoryCta(true, formDataCopy, inputFields[indexOfSecondary].cols[0]);
        });
    } else {
      this.setState({schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, isSchemaChanged: true}, () => { this.injectEvents(schema); });
    }
  };
  copyIphoneContent = () => {
    const formData = cloneDeep(this.state.formData);
    if (!!formData[1]['message-title2'] && !!formData[1]['message-editor2']) {
      formData[0]['message-title'] = formData[1]['message-title2'];
      formData[0]['message-editor'] = formData[1]['message-editor2'];
      this.setState({formData});
    } else {
      this.openNotificationWithIcon('warning', this.props.intl.formatMessage(messages.cantCopyEmptyFieldValues));
    }
  };
  copyAndroidContent = () => {
    const formData = cloneDeep(this.state.formData);
    if (!!formData[0]['message-title'] && !!formData[0]['message-editor']) {
      formData[1]['message-title2'] = formData[0]['message-title'];
      formData[1]['message-editor2'] = formData[0]['message-editor'];
      this.setState({formData});
    } else {
      this.openNotificationWithIcon('warning', this.props.intl.formatMessage(messages.cantCopyEmptyFieldValues));
    }
  };
  uploadImage = (data) => {
    if (data.fileParams.error) {
      CapNotification.error({
        message: this.props.intl.formatMessage(messages.uploadImageSizeErrorTitle),
        description: this.props.intl.formatMessage(messages.uploadImageSizeErrorDescription),
        duration: 2,
      });
    } else {
      this.props.actions.uploadAsset(data.file, data.type, data.fileParams);
    }
  };
  selectCtaIos = (selectedConfig) => {
    this.showSelectedIosCta(selectedConfig);
  };

  showCtaKeys = (eventTriggered, formData, field) => {
    const schema = cloneDeep(this.state.schema);
    const eventsMap = cloneDeep(this.state.eventsMap);
    forEach(schema.containers, (container) => {
      forEach(container.panes, (pane) => {
        forEach(pane.sections, (section) => {
          forEach(section.childSections, (childeSection) => {
            forEach(childeSection.childSections, (child) => {
              const formChaild = child;
              if (child.type === 'multicols') {
                forEach(child.inputFields, (inputField, fieldIndex) => {
                  forEach(inputField.cols, (col) => {
                    if (col.id === field.id) {
                      const formDataKey = col.id.replace("-show-keys", "");
                      const deeplinks = this.props.Templates.selectedWeChatAccount && this.props.Templates.selectedWeChatAccount.configs && !!this.props.Templates.selectedWeChatAccount.configs.deeplink ? this.props.Templates.selectedWeChatAccount.configs.deeplink : '[]';
                      let keys = this.props.Templates.selectedWeChatAccount ? filter(JSON.parse(deeplinks), (dl) => dl.link === formData[this.state.currentTab - 1][formDataKey]) : [];
                      if (keys[0]) {
                        keys = keys[0].keys;
                      }
                      let rows = map(keys, (key) => {
                        const row = {
                          rowClassName: 'mobile-push-row',
                          id: 'cta-deeplink-keys',
                          cols: [


                            {
                              id: `custom-value-${key}-${col.id}`,
                              label: key.replace('_', " "),
                              type: "input",  //Resembles component to be used
                              metaType: "text",
                              datatype: "string",
                              required: true,
                              width: 18,
                              offset: 1,
                              placeholder: `${this.props.intl.formatMessage(messages.pleaseInput)} ${key.replace('_', " ")} ${this.props.intl.formatMessage(messages.here)}`,
                              fluid: true,
                              styling: "semantic",
                              order: 1,
                              customComponent: false,
                              errorMessage: this.props.intl.formatMessage(messages.valueCantEmpty),
                            },
                          ],
                        };
                        //eventsMap[`custome-${key}`] = {"onChange": this.onMessageTitleChange};
                        return row;
                        // formChaild.inputFields[fieldIndex + index] = field;
                      });


                      const configkeys = filter(JSON.parse(deeplinks), (dl) => dl.link === this.state.formData[this.state.currentTab - 1][field.id]);
                      if (configkeys.length) {
                        const options = configkeys[0].keys;
                        formChaild.inputFields = formChaild.inputFields.slice(0, fieldIndex + 1).concat(formChaild.inputFields.slice( fieldIndex + options.length + 1, formChaild.inputFields.length));
                        // delete formData[self.state.currentTab - 1][`cta-deeplink-${id.replace('delete', 'select')}`];
                        // delete formData[self.state.currentTab - 1][`cta-deeplink-${id.replace('-delete', '')}`];
                      }
                      if (formChaild.inputFields[fieldIndex + 1] && formChaild.inputFields[fieldIndex + 1].id === "cta-deeplink-keys") {
                        rows = formChaild.inputFields.slice(0, fieldIndex + 1).concat(rows).concat(formChaild.inputFields.slice(fieldIndex + 1, formChaild.inputFields.length));
                        formChaild.inputFields = rows;
                      } else {
                        rows = formChaild.inputFields.slice(0, fieldIndex + 1).concat(rows).concat(formChaild.inputFields.slice(fieldIndex + 1, formChaild.inputFields.length));
                        formChaild.inputFields = rows;
                      }
                    }
                  });
                });
              }
            });
          });
        });
      });
    });
    this.setState({schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, eventsMap, isSchemaChanged: true});
    this.injectEvents(schema);
  };

  saveFormData = (formData) => {
    //this function gets called from form bulder only when the form data is valid
    
    // Check for personalization tokens if restriction is enabled
    if (this.props.restrictPersonalization) {
      const hasTokens = checkForPersonalizationTokens(formData);
      if (hasTokens) {
        const message = this.props.intl.formatMessage(messages.personalizationTokensErrorMessage);
        CapNotification.error({message, key: 'personalizationTokensError'});
        return;
      }
    }
    
    const obj = this.getTransformedData(formData);
    const content = getContent(obj);
    const {
      definition: {
        mode: definitionMode,
      },
    } = obj || {};
    const label = this.props.location.pathname.indexOf('image') >= 0 ? 'image' : 'text';
    this.props.actions.createTemplate(obj, (response) => {
    const timeTaken = GA.timeTracker.stopTimer(TRACK_CREATE_MPUSH, {
      category: 'Creatives',
      action: TRACK_CREATE_MPUSH,
      label,
    });
    gtmPush('creativeDetails', {
      id: response.templateId,
      name: obj.name,
      channel: MOBILE_PUSH,
      timeTaken,
      content,
      mode: CREATE,
      imageAdded: definitionMode === 'image',
    });

    this.discardValues();
    const message = this.props.intl.formatMessage(messages.messageCreateSuccess);
    CapNotification.success({message, key: 'createMpushSuccess'});
    this.props.actions.clearCreateResponse();
    this.props.getFormLibraryData({validity: true});
    });
  };
  deleteSecondaryCtaIos = (callback) => {
    const schema = cloneDeep(this.state.schema);
    const inputFields = get(schema, `containers[0].panes[${this.state.currentTab - 1}].sections[0].childSections[0].childSections[0].inputFields`);
    forEach(inputFields, (inputField, fieldIndex) => {
      if (inputField) {
        forEach(inputField.cols, (col) => {
          if (col.id === "add-sec-cta-ios") {
            inputFields.splice(fieldIndex + 1, inputFields.length);
          }
        });
      }
    });
    this.setState({schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, isSchemaChanged: true}, callback);
    this.injectEvents(schema);
  };
  deletePrimaryCTA = (event) => {
    const id = event.currentTarget.id;
    const schema = cloneDeep(this.state.schema);
    // const eventsMap = cloneDeep(this.state.eventsMap);
    const selectedDeeplink = this.state.formData[this.state.currentTab - 1][`${id.replace('delete', 'select')}`];
    const formData = cloneDeep(this.state.formData);
    const self = this;
    forEach(schema.containers, (container) => {
      forEach(container.panes, (pane) => {
        forEach(pane.sections, (section) => {
          forEach(section.childSections, (childeSection) => {
            forEach(childeSection.childSections, (formChild) => {
              const child = formChild;
              if (child.type === 'multicols') {
                forEach(child.inputFields, (inputField, fieldIndex) => {
                  if (inputField) {
                    forEach(inputField.cols, (col) => {
                      if (col.id === id) {
                        child.inputFields.splice(fieldIndex, 1);
                        if (child.inputFields[fieldIndex] && child.inputFields[fieldIndex].id === "cta-external-link") {
                          child.inputFields.splice(fieldIndex, 1);
                        }
                        if (child.inputFields[fieldIndex] && child.inputFields[fieldIndex].id === "cta-deeplink-select-section") {
                          const deeplinks = this.props.Templates.selectedWeChatAccount && this.props.Templates.selectedWeChatAccount.configs && !!this.props.Templates.selectedWeChatAccount.configs.deeplink ? this.props.Templates.selectedWeChatAccount.configs.deeplink : '[]';
                          const configkeys = this.props.Templates.selectedWeChatAccount ? filter(JSON.parse(deeplinks), (dl) => dl.link === selectedDeeplink) : [];
                          if (configkeys.length) {
                            const options = configkeys[0].keys;
                            child.inputFields = child.inputFields.slice(0, fieldIndex).concat(child.inputFields.slice( fieldIndex + options.length + 1, child.inputFields.length));
                            delete formData[self.state.currentTab - 1][`${id.replace('delete', 'select')}`];
                            delete formData[self.state.currentTab - 1][`${id.replace('-delete', '')}`];
                          } else {
                            child.inputFields.splice(fieldIndex, 1);
                          }
                        }
                        child.inputFields.splice(fieldIndex, 0, {
                          cols: [
                            {
                              id: `${this.state.currentTab === 1 ? "add-pri-cta" : "add-pri-cta-ios"}`,
                              metaType: "label",
                              value: this.props.intl.formatMessage(messages.addPrimaryCTA),
                              primitive: true,
                              dynamicTab: false,
                              type: "div",
                              style: {
                                backgroundColor: 'white',
                                textAlign: 'left',
                                color: '#2673D7',

                                cursor: 'pointer',
                              },
                              offset: 0,
                              onlyDisplay: true,
                              colStyle: {
                                flex: 1,
                              },
                              submitAction: "addPrimaryCta",
                              supportedEvents: ["addPrimaryCta"],
                            },
                          ],
                        });
                      }
                    });
                  }
                });
              }
            });
          });
        });
      });
    });
    this.setState({schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, formData, isSchemaChanged: true});
    this.injectEvents(schema);
  };

  deleteSecondaryCTA = (event) => {
    const id = event.currentTarget.id;
    if (id === "secondary-cta-0-delete") {
      const secCta2 = document.getElementById("secondary-cta-1-delete");
      if (secCta2) {
        const modalContent = {title: this.props.intl.formatMessage(messages.alertMessage), body: this.props.intl.formatMessage(messages.deleteSecondCTAFirst), type: 'info', show: true, onCancel: this.onModalCancel};
        this.setState({modalContent, showModal: true});
        return;
      }
    }
    const schema = cloneDeep(this.state.schema);
    // const eventsMap = cloneDeep(this.state.eventsMap);
    const selectedDeeplink = this.state.formData[this.state.currentTab - 1][`cta-deeplink-${id.replace('delete', 'select')}`];
    const formData = cloneDeep(this.state.formData);
    const device = this.state.currentTab === 1 ? 'android' : 'ios';
    forEach(schema.containers, (container) => {
      forEach(container.panes, (pane) => {
        forEach(pane.sections, (section) => {
          forEach(section.childSections, (childeSection) => {
            forEach(childeSection.childSections, (formChild) => {
              const child = formChild;
              if (child.type === 'multicols') {
                forEach(child.inputFields, (inputField, fieldIndex) => {
                  if (inputField) {
                    forEach(inputField.cols, (col) => {
                      if (col.id === id) {
                        if (device === 'ios') {
                          child.inputFields.splice(fieldIndex, 3);
                        } else {
                          child.inputFields.splice(fieldIndex, 2);
                        }
                        if (child.inputFields[fieldIndex] && child.inputFields[fieldIndex].id === "cta-external-link") {
                          child.inputFields.splice(fieldIndex, 1);
                        }
                        if (child.inputFields[fieldIndex] && child.inputFields[fieldIndex].id === "cta-deeplink-select-section") {
                          const ck = this.props.Templates.selectedWeChatAccount.configs ? !!this.props.Templates.selectedWeChatAccount.configs.deeplink : false;
                          const deeplinks = ck ? this.props.Templates.selectedWeChatAccount.configs.deeplink : '[]';
                          const configkeys = this.props.Templates.selectedWeChatAccount ? filter(JSON.parse(deeplinks), (dl) => dl.link === selectedDeeplink) : [];
                          if (configkeys.length) {
                            const options = configkeys[0].keys;
                            child.inputFields = child.inputFields.slice(0, fieldIndex).concat(child.inputFields.slice( fieldIndex + options.length + 1, child.inputFields.length));
                          } else {
                            child.inputFields.splice(fieldIndex, 1);
                          }
                        }
                        if (device === 'ios') {
                          child.inputFields[fieldIndex] = {
                            cols: [
                              {
                                id: "add-sec-cta-ios",
                                metaType: "label",
                                value: this.props.intl.formatMessage(messages.addSecondaryCTA),
                                primitive: true,
                                dynamicTab: false,
                                type: "div",
                                style: {
                                  backgroundColor: 'white',
                                  textAlign: 'left',
                                  color: '#2673D7',

                                  cursor: 'pointer',
                                },
                                offset: 0,
                                onlyDisplay: true,
                                colStyle: {
                                  flex: 1,
                                },
                                submitAction: "addSecondaryCtaIos",
                                supportedEvents: ["addSecondaryCtaIos"],
                              },
                            ],
                          };
                        } else {
                          if (child.inputFields[fieldIndex] && child.inputFields[fieldIndex].cols[0] && child.inputFields[fieldIndex].cols[0].id === "add-sec-cta") {
                            child.inputFields[fieldIndex] = {
                              cols: [
                                {
                                  id: "add-sec-cta",
                                  metaType: "label",
                                  value: this.props.intl.formatMessage(messages.addSecondaryCTA),
                                  primitive: true,
                                  dynamicTab: false,
                                  type: "div",
                                  style: {
                                    backgroundColor: 'white',
                                    textAlign: 'left',
                                    color: '#2673D7',

                                    cursor: 'pointer',
                                  },
                                  offset: 0,
                                  onlyDisplay: true,
                                  colStyle: {
                                    flex: 1,
                                  },
                                  submitAction: "addSecondaryCta",
                                  supportedEvents: ['addSecondaryCta'],
                                  fieldsLimit: 2,
                                  fieldsCount: 0,
                                },
                              ],
                            };
                          }
                          if (id === "secondary-cta-1-delete" || child.inputFields[fieldIndex].cols[0].id === "cta-label" || child.inputFields[fieldIndex].cols[0].id === "secondary-cta-1-space") {
                            let nextFieldIndex = fieldIndex;
                            if (id === "secondary-cta-1-delete" || child.inputFields[fieldIndex].cols[0].id === "secondary-cta-1-space") {
                              nextFieldIndex = child.inputFields.length;
                            }
                            child.inputFields[nextFieldIndex] = {
                              cols: [
                                {
                                  id: "add-sec-cta",
                                  metaType: "label",
                                  value: this.props.intl.formatMessage(messages.addAnotherCTA),
                                  primitive: true,
                                  dynamicTab: false,
                                  type: "div",
                                  style: {
                                    backgroundColor: 'white',
                                    textAlign: 'left',
                                    color: '#2673D7',

                                    cursor: 'pointer',
                                  },
                                  offset: 0,
                                  onlyDisplay: true,
                                  colStyle: {
                                    flex: 1,
                                  },
                                  submitAction: "addSecondaryCta",
                                  supportedEvents: ['addSecondaryCta'],
                                  fieldsLimit: 2,
                                  fieldsCount: 1,
                                },
                              ],
                            };
                          }
                        }
                      }
                    });
                  }
                });
              }
            });
          });
        });
      });
    });
    this.setState({schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, formData, isSchemaChanged: true});
    this.injectEvents(schema);
  };
  handleOnTagsContextChange = (data) => {
    const context = (data || '').toLowerCase() === 'all' ? 'default' : (data || '').toLowerCase();
    if (this.lastFetchedTagContextRef === context) {
      return;
    }
    this.lastFetchedTagContextRef = context;
    const query = {
      layout: 'mobilepush',
      type: 'TAG',
      context,
      embedded: this.props.location.query.type === 'embedded' ? this.props.location.query.type : 'full',
    };
    this.props.globalActions.fetchSchemaForEntity(query);
  };
  handleClose = () => {
    const formData = cloneDeep(this.state.formData);
    formData[this.state.currentTab - 1]['add-sec-cta-ios'] = false;
    this.setState({showIosCtaTable: false, formData});
  }

  // Get template content for TestAndPreviewSlidebox
  // MobilePush uses formData[0] for Android and formData[1] for iOS
  getTemplateContent = () => {
    if (!this.state.formData || this.state.formData.length < 2) {
      return {
        androidContent: {},
        iosContent: {},
      };
    }
    const androidData = this.state.formData[0] || {};
    const iosData = this.state.formData[1] || {};

    // Extract actions (buttons) - format similar to TemplatePreview
    const getActions = (data) => {
      const actions = [];
      // Primary CTA
      if (data['cta-deeplink-label']) {
        actions.push({
          label: data['cta-deeplink-label'],
          url: data['cta-deeplink-select'] || data['cta-deeplink-text'] || '',
        });
      }
      // Secondary CTA
      if (data['secondary-cta-0-label']) {
        actions.push({
          label: data['secondary-cta-0-label'],
          url: data[`cta-deeplink-secondary-cta-0-select`] || data[`cta-deeplink-secondary-cta-0-text`] || '',
        });
      }
      if (data['secondary-cta-1-label']) {
        actions.push({
          label: data['secondary-cta-1-label'],
          url: data[`cta-deeplink-secondary-cta-1-select`] || data[`cta-deeplink-secondary-cta-1-text`] || '',
        });
      }
      return actions;
    };

    return {
      androidContent: {
        header: androidData['message-title'] || '',
        bodyText: androidData['message-editor'] || '',
        bodyImage: androidData.image || '',
        actions: getActions(androidData),
        carouselData: [], // MobilePush carousel support can be added later if needed
      },
      iosContent: {
        header: iosData['message-title2'] || '',
        bodyText: iosData['message-editor2'] || '',
        bodyImage: iosData['image-upload-ios'] || '',
        actions: getActions(iosData),
        carouselData: [], // MobilePush carousel support can be added later if needed
      },
    };
  }

  handleTestAndPreview = () => {
    if (this.props.handleTestAndPreview) {
      this.props.handleTestAndPreview();
    }
  }
  render() {
    let loading = this.props.Create.createTemplateInProgress ? this.props.Create.createTemplateInProgress : false;
    if (this.props.Create.assetUploading) {
      loading = true;
    }
    let tags = this.props.metaEntities && this.props.metaEntities.tags ? this.props.metaEntities.tags.standard : [];
    if (this.props.supportedTags) {
      tags = this.props.supportedTags; // if get default tags is not present and supported tags is present use that inlbrary mode
    }
    return (
      <div className="creatives-mobilepush-create">
        <CapSpin spinning={loading}>
          <CapRow>
            <CapColumn>
              <FormBuilder
                channel={MOBILE_PUSH}
                key={"form builder"}
                showLiquidErrorInFooter={this.props.showLiquidErrorInFooter}
                schema={this.state.schema}
                onSubmit={this.saveFormData}
                onChange={this.onFormDataChange}
                currentTab={this.state.currentTab}
                parent={this}
                formData={cloneDeep(this.state.formData)}
                location={this.props.location}
                tags={tags}
                injectedTags={this.props.injectedTags ? this.props.injectedTags : {}}
                onFormValidityChange={this.setFormValidity}
                usingTabContainer
                checkValidation={this.state.checkValidation}
                iosCtasData={this.state.iosCtasData}
                tabKey={this.state.tabKey}
                tabCount={2}
                showModal={this.state.showModal}
                isSchemaChanged={this.state.isSchemaChanged}
                modal={this.state.modalContent}
                handleCancelModal={this.handleCancelModal}
                iframeParent={parent}
                router={this.props.router}
                onContextChange={this.handleOnTagsContextChange}
                setModalContent={this.setModalContent}
                startValidation={this.state.startValidation}
                stopValidation={this.stopValidation}
                selectedOfferDetails={this.props.selectedOfferDetails}
                onPreviewContentClicked={this.props.onPreviewContentClicked}
                onTestContentClicked={this.props.onTestContentClicked}
                templateData={this.props.templateData}
                hideTestAndPreviewBtn={this.props.hideTestAndPreviewBtn}
                isFullMode={this.props.isFullMode}
                eventContextTags={this.props?.eventContextTags}
                waitEventContextTags={this.props?.waitEventContextTags}
                messageDetails={this.props?.messageDetails}
                restrictPersonalization={this.props.restrictPersonalization}
              />
            </CapColumn>
            {this.props.iosCtasData && this.state.showIosCtaTable &&
              <CapSlideBox
                size="size-l"
                header={<CapHeader
                  title={<FormattedMessage {...messages.selectActionButton} />}
                  prefix={
                    <PrefixWrapper>
                      <CapIcons.BackIcon onClick={this.handleClose} />
                    </PrefixWrapper>
                      }

                    />}
                content={<CapTable
                  rowSelection={{
                    type: 'radio',
                    onSelect: (record) => {
                      this.setState({templateCta: record, showIosCtaTable: false}, () => this.selectCtaIos(record));
                    },
                  }}
                  dataSource={this.props.iosCtasData} columns={[
                    {
                      title: this.props.intl.formatMessage(messages.nameAndDescription),
                      dataIndex: "name",
                      key: "name",
                      width: 200,
                      render: (text, record) => (
                        <div>
                          <div>{record.name}</div>
                          <div>{record.description}</div>
                        </div>),
                    },
                    {
                      title: this.props.intl.formatMessage(messages.button1),
                      dataIndex: "description",
                      key: "button1",
                      width: 100,
                      render: (text, record) => (
                        <div>
                          {record.ctaTemplateDetails[0] && record.ctaTemplateDetails[0].buttonText}
                        </div>),
                    },
                    {
                      title: this.props.intl.formatMessage(messages.button2),
                      dataIndex: "description",
                      key: "button2",
                      width: 100,
                      render: (text, record) => (
                        <div>
                          {record.ctaTemplateDetails[1] ? record.ctaTemplateDetails[1].buttonText : ''}
                        </div>
                    ),
                    },
                  ]}
                />}
                show={this.state.showIosCtaTable}
                handleClose={this.handleClose}
              />
            }

          </CapRow>
        </CapSpin>
        <TestAndPreviewSlidebox
          show={this.props.showTestAndPreviewSlidebox || false}
          onClose={this.props.handleCloseTestAndPreview}
          formData={this.state.formData} // Pass actual formData for payload building
          content={this.getTemplateContent()} // Also pass content for preview
          currentChannel={MOBILE_PUSH}
          accountId={this.props.Templates?.selectedWeChatAccount?.id || null} // Pass selected account ID for test message payload
        />
      </div>
    );
  }
}

Create.propTypes = {
  actions: PropTypes.object.isRequired,
  isFullMode: PropTypes.bool,
  Create: PropTypes.object,
  router: PropTypes.object,
  location: PropTypes.object,
  route: PropTypes.object,
  globalActions: PropTypes.object,
  metaEntities: PropTypes.object,
  params: PropTypes.object,
  Templates: PropTypes.object,
  intl: intlShape.isRequired,
  supportedTags: PropTypes.array,
  getDefaultTags: PropTypes.string,
  iosCtasData: PropTypes.array,
  injectedTags: PropTypes.object,
  defaultData: PropTypes.object,
  showTemplateName: PropTypes.func,
  isGetFormData: PropTypes.bool,
  onValidationFail: PropTypes.func,
  getFormLibraryData: PropTypes.func,
  onPreviewContentClicked: PropTypes.func,
  onTestContentClicked: PropTypes.func,
  eventContextTags: PropTypes.array,
  waitEventContextTags: PropTypes.object,
  getLiquidTags: PropTypes.func,
  showLiquidErrorInFooter: PropTypes.func,
  showTestAndPreviewSlidebox: PropTypes.bool,
  handleTestAndPreview: PropTypes.func,
  handleCloseTestAndPreview: PropTypes.func,
  restrictPersonalization: PropTypes.bool,
  isAnonymousType: PropTypes.bool,
  onPersonalizationTokensChange: PropTypes.func,
};

const mapStateToProps = createStructuredSelector({
  Create: makeSelectCreate(),
  createResponse: makeSelectCreateResponse(),
  metaEntities: makeSelectMetaEntities(),
  Templates: makeSelectTemplates(),
  iosCtasData: makeSelectIosCta(),
  injectedTags: setInjectedTags(),
});

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(actions, dispatch),
    globalActions: bindActionCreators(globalActions, dispatch),
  };
}

const withReducer = injectReducer({ key: 'mobileCreate', reducer: v2MobilePushCreateReducer });
const withSaga = injectSaga({ key: 'mobilePushDuplicateTemplate', saga: v2MobilePushWatchDuplicateTemplateSaga});

export default withCreatives({
  WrappedComponent: Create,
  mapStateToProps,
  mapDispatchToProps,
  userAuth: false,
  sagas: [withSaga],
  reducers: [withReducer],
});
