/*
 *
 * Create
 *
 */

import PropTypes from 'prop-types';

import React from 'react';
import { CapRow, CapColumn, CapSpin, CapNotification } from '@capillarytech/cap-ui-library';
import { intlShape } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import _ from 'lodash';
import { bindActionCreators } from 'redux';
import { makeSelectCreate, makeSelectCreateResponse } from './selectors';
import { makeSelectMetaEntities, isLoadingMetaEntities, setInjectedTags } from '../../Cap/selectors';
import './_smsCreate.scss';
import FormBuilder from '../../../v2Components/FormBuilder';
import * as actions from './actions';
import messages from './messages';
import * as charCount from '../../../utils/smsCharCount';
import {checkUnicode, updateCharCount} from '../../../utils/smsCharCountV2';
import {getMessageObject} from '../../../utils/messageUtils';
import { gtmPush } from '../../../utils/gtmTrackers';
import * as creativesContainerActions from '../../CreativesContainer/actions';
import {SMS} from '../../CreativesContainer/constants';
// import callNativeEvent from '../../../legacy/callNativeEvent';
import {showError} from '../commonMethods';
import withCreatives from '../../../hoc/withCreatives';
import { GA } from '@capillarytech/cap-ui-utils';
import { CREATE, TRACK_CREATE_SMS } from '../../App/constants';
import injectReducer from '../../../utils/injectReducer';
import v2SmsCreateReducer from './reducer';
import * as globalActions from '../../Cap/actions';
import TestAndPreviewSlidebox from '../../../v2Components/TestAndPreviewSlidebox';

export class Create extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.state = {
      loadingStatus: 0,
      formData: {},
      tabCount: 1,
      currentTab: 1,
      schema: {},
      loading: false,
      isFormValid: true,
      injectedTags: {},
      tabKey: '',
      showModal: false,
      modalContent: {title: "Alert", body: "Do you really want to delete this version?", type: 'confirm', id: 'sms-version-modal'},
      showTestAndPreviewSlidebox: false,
      isTestAndPreviewMode: false,
      pendingGetFormData: false,
    };
    this.saveFormData = this.saveFormData.bind(this);
    this.onFormDataChange = this.onFormDataChange.bind(this);
    this.onTemplateNameChange = this.onTemplateNameChange.bind(this);
    this.onTemplateContentChange = this.onTemplateContentChange.bind(this);
    this.handleFrameTasks = this.handleFrameTasks.bind(this);
    this.getFormData = this.getFormData.bind(this);
    this.validateContent = this.validateContent.bind(this);
    this.onTagSelect = this.onTagSelect.bind(this);
    this.insertAtCursor = this.insertAtCursor.bind(this);
    this.addVersion = this.addVersion.bind(this);
    this.onTabChange = this.onTabChange.bind(this);
    this.resetSchema = this.resetSchema.bind(this);
    this.resetState = this.resetState.bind(this);
    this.discardValues = this.discardValues.bind(this);
    this.cloneColLabel = this.cloneColLabel.bind(this);
    this.cloneMultiCol = this.cloneMultiCol.bind(this);
    this.cloneParent = this.cloneParent.bind(this);
    this.markFinalVersion = this.markFinalVersion.bind(this);
    this.deleteVersion = this.deleteVersion.bind(this);
    this.duplicateVersion = this.duplicateVersion.bind(this);
    this.renameVersion = this.renameVersion.bind(this);
    this.onVersionNameChange = this.onVersionNameChange.bind(this);
    this.startTemplateCreation = this.startTemplateCreation.bind(this);
    this.startLoading = this.startLoading.bind(this);
    this.removeStandAlone = this.removeStandAlone.bind(this);
    this.validateFormData = this.validateFormData.bind(this);
    this.getCurrentWindow = this.getCurrentWindow.bind(this);
    this.moveToTemplates = this.moveToTemplates.bind(this);
    this.cancelTemplate = this.cancelTemplate.bind(this);
    this.injectEvents = this.injectEvents.bind(this);
    this.injectSections = this.injectSections.bind(this);
    this.injectContainer = this.injectContainer.bind(this);
    this.injectParentSection = this.injectParentSection.bind(this);
    this.injectColLabelSection = this.injectColLabelSection.bind(this);
    this.injectMultiColSection = this.injectMultiColSection.bind(this);
    this.getMappedEvent = this.getMappedEvent.bind(this);
    this.setFormValidity = this.setFormValidity.bind(this);
    this.showNext = this.showNext.bind(this);
    this.injectMessages = this.injectMessages.bind(this);
    this.smsCount = React.createRef();
    this.componentRefs = {
      'sms-count': this.smsCount,
    };
    this.showError = showError.bind(this);
  }

  componentWillMount() {
    if (this.props.route.name === 'view') {
      this.setState({loading: false});
      // this.removeStandAlone();
    }
  }

  componentDidMount() {
    const query = {
      layout: 'SMS',
      type: 'LAYOUT',
      version: 'v2', //gets initial schema when v2 is specified
    };
    this.props.globalActions.fetchSchemaForEntity(query);
    const type = this.props.location.query.type;
    // const module = this.props.location.query.module;
    const name = this.props.route.name;
    window.addEventListener("message", this.handleFrameTasks);
    if (type === 'embedded') {
      const response = {
        action: 'startTemplateCreation',
        window: name === 'view' ? 'view' : 'create',
      };
      // if (name !== "view" && module.toLowerCase() === "timeline") {
      //   return;
      // }
      parent.postMessage(JSON.stringify(response), '*');
    }
    //For testing embedded mode data injection
    // let that = this;
    // setTimeout( function() {
    //   that.startTemplateCreation(
    //     {
    //       edit: true,
    //       content: 'asasasasasas 12122',
    //       tags: {},
    //     }
    //   );
    // }, 5000);
  }

  componentWillReceiveProps(nextProps) {
    // Only trigger on actual Done click (isGetFormData false -> true). Prevents auto-submit after user fixes brace error.
    if (!nextProps.isFullMode && nextProps.isGetFormData && !this.props.isGetFormData) {
      this.setState({ startValidation: true, pendingGetFormData: true });
    } else if (nextProps.isGetFormData && this.props.isFullMode && !this.props.Create.createTemplateInProgress) {
      this.startValidation();
    }
    if (nextProps.Create.createTemplateError && !_.isEqual(nextProps.Create.createTemplateError, this.props.Create.createTemplateError)) {
      const message = (nextProps.Create.createTemplateErrorMessage && nextProps.Create.createTemplateErrorMessage !== '') ? nextProps.Create.createTemplateErrorMessage : this.props.intl.formatMessage(messages.somethingWentWrong);
      CapNotification.error({key: 'createTemplateError', message });
      this.stopValidation();
    }
    if (nextProps.metaEntities && nextProps.metaEntities.layouts && nextProps.metaEntities.layouts.length > 0 && _.isEmpty(this.state.schema)) {
      this.injectEvents(nextProps.metaEntities.layouts[0].definition);
      if (this.props.location.query.module !== 'library' || (this.props.location.query.module === 'library' && this.props.getDefaultTags)) {
        const query = {
          layout: 'SMS',
          type: 'TAG',
          context: this.props.location.query.type === 'embedded' ? this.props.location.query.module : 'default',
          embedded: this.props.location.query.type === 'embedded' ? this.props.location.query.type : 'full',
        };
        if (this.props.getDefaultTags) {
          query.context = this.props.getDefaultTags;
        }
        this.props.globalActions.fetchSchemaForEntity(query);
        if (this.props.location.query.type === 'embedded') {
          this.showNext();
        }
      }
    }
  }

  componentWillUnmount() {
    if (this.pendingGetFormDataTimeout) {
      clearTimeout(this.pendingGetFormDataTimeout);
    }
    if (this.props.setIsLoadingContent) {
      this.props.setIsLoadingContent(true); // setting isLoading of CreativesContainer so that slidebox foot can be hidden till content is loaded
    }
    window.removeEventListener("message", this.handleFrameTasks);
  }

  onTemplateNameChange() {

  }

  onTemplateContentChange() {
    const content = _.get(this.state, `formData[0]['sms-editor']`);
    const unicodeEnabled = _.get(this.state, `formData[0]['unicode-validity']`);
    const smsDetails = updateCharCount(content || "", unicodeEnabled || false);
    if (this.smsCount.current) {
      this.smsCount.current.innerText = `${smsDetails.parts}${this.props.intl.formatMessage(messages.sms)} (${smsDetails.chars_used} ${this.props.intl.formatMessage(messages.characters)})`;
    }
  }

  onVersionNameChange( ) {

  }

  onFormDataChange(formData, tabCount, currentTab) {
    this.setState({formData, tabCount}, this.onTemplateContentChange);
    if (currentTab) {
      this.setState({currentTab});
    }
    // Clear footer validation errors on input change so they refresh on next validation
    if (this.props.showLiquidErrorInFooter) {
      this.props.showLiquidErrorInFooter({ STANDARD_ERROR_MSG: [], LIQUID_ERROR_MSG: [] });
    }
  }

  onTagSelect(data, currentTab) {
    const editorId = currentTab > 1 ? `sms-editor${currentTab}` : 'sms-editor';
    this.insertAtCursor(document.getElementById(editorId), `{{${data}}}`, currentTab);
    document.getElementById(editorId).focus();
  }

  onTabChange(data) {
    this.setState({currentTab: data});
  }

  onCreateTemplateComplete = (editResponse) => {
    const timeTaken = GA.timeTracker.stopTimer(TRACK_CREATE_SMS, {
      category: 'Creatives',
      action: TRACK_CREATE_SMS,
    });
    const {
      formData,
    } = this.state;
    if (editResponse.templateId) {
      gtmPush('creativeDetails', {
        id: editResponse.templateId,
        name: formData?.['template-name'],
        channel: SMS,
        timeTaken,
        content: formData?.base?.['sms-editor'],
        mode: CREATE,
      });
      this.resetSchema();
      this.setState({
        formData: {},
        tabCount: 1,
        currentTab: 1,
        editData: {},
      });
      const message = this.props.intl.formatMessage(messages.smsTemplateCreatedSuccess);
      CapNotification.success({key: 'createMessageSuccess', message});
      const module = this.props.location.query.module ? this.props.location.query.module : 'default';
      const type = this.props.location.query.type;
      if (this.props.isFullMode) {
        this.props.getFormSubscriptionData({ value: editResponse.templateId, validity: true});
      } else {
        this.props.router.push({
          pathname: `/sms/`,
          query: type === 'embedded' ? {type: 'embedded', module} : {module},
        });
      }
    }
  }

  getFormData(e, value) {
    const formData = _.cloneDeep(this.state.formData);
    let baseData = {};
    let versionIdx;
    _.forEach(formData, (val, idx) => {
      if (val.base && idx !== 'base') {
        baseData = val;
        versionIdx = idx;
      }
    });
    baseData['sms-editor'] = baseData[`sms-editor${versionIdx > 0 ? versionIdx : ''}`];
    if (versionIdx !== "0") {
      delete baseData[`sms-editor${versionIdx > 0 ? versionIdx : ''}`];
    }
    const result = {};
    result.base = baseData;
    if (this.state.isValid) {
      const msgObj = charCount.updateCharCount(baseData['sms-editor']);
      result.base.msg_count = msgObj.msgCount;
    }
    const response = {
      action: "getFormData",
      value: result,
      postAction: value || 'next',
      validity: this.state.isFormValid,
      type: 'SMS',
    };
    this.setState({checkValidation: true}, this.showError);

    if (e) {
      e.source.postMessage(JSON.stringify(response), e.origin);
    }
    return response;
  }

  getCurrentWindow(e) {
    const response = {
      action: e.action,
      value: 'edit',
      direction: e.value,
    };
    parent.postMessage(JSON.stringify(response), '*');
  }

  getMappedEvent(id, event) {
    const map = {
      "template-name": {
        onChange: this.onTemplateNameChange,
      },
      "discard-button": {
        discardValues: this.discardValues,
      },
      "cancel-button": {
        cancelTemplate: this.cancelTemplate,
      },
      "save-button": {
        saveFormData: this.validateAndSaveFormData,
      },
      "test-and-preview-button": {
        onClick: this.handleTestAndPreview,
      },
      "sms-editor": {
        onChange: this.onTemplateContentChange,
      },
      "tagList": {
        onTagSelect: this.onTagSelect,
      },
      "unicode-validity": {
        onChange: this.onTemplateNameChange,
      },
      "add-version-button": {
        addVersion: this.addVersion,
      },
      "tab-header": {
        onChange: this.onVersionNameChange,
      },
      "tab-options-popover": {
        onTabOptionSelect: this.onTabOptionSelect,
      },
      "mark-final-version-label": {
        markFinalVersion: this.markFinalVersion,
      },
      "duplicate-version-label": {
        duplicateVersion: this.duplicateVersion,
      },
      "rename-version-label": {
        renameVersion: this.renameVersion,
      },
      "delete-version-label": {
        deleteVersion: this.deleteVersion,
      },
      "pane": {
        onTabChange: this.onTabChange,
      },
    };
    return map[id][event];
  }

  setFormValidity(isFormValid, errorData) {
    this.setState({ isFormValid, errorData }, () => {
      if (this.state.pendingGetFormData && !isFormValid) {
        this.setState({ pendingGetFormData: false, startValidation: false });
        // Reset parent's Done state so next Done click is a fresh attempt
        if (this.props.onValidationFail) {
          this.props.onValidationFail();
        }
        return;
      }
      // In library mode with SMS, submit only when FormBuilder calls onSubmit (after liquid validation).
      if (this.state.pendingGetFormData && this.props.getFormSubscriptionData && this.props.isFullMode) {
        if (this.pendingGetFormDataTimeout) {
          clearTimeout(this.pendingGetFormDataTimeout);
          this.pendingGetFormDataTimeout = null;
        }
        this.props.getFormSubscriptionData(this.getFormData());
        this.setState({ pendingGetFormData: false, startValidation: false });
      }
    });
  }

  injectMessages(elem) {
    const temp = elem;
    if (temp.value && messages[temp.value]) {
      temp.value = this.props.intl.formatMessage(messages[temp.value]);
    }
    if (temp.label && messages[temp.label]) {
      temp.label = this.props.intl.formatMessage(messages[temp.label]);
    }
    if (temp.errorMessage && messages[temp.errorMessage]) {
      temp.errorMessage = this.props.intl.formatMessage(messages[temp.errorMessage]);
    }
    if (temp.placeholder && messages[temp.placeholder]) {
      temp.placeholder = this.props.intl.formatMessage(messages[temp.placeholder]);
    }
    return temp;
  }

  showNext() {
    const response = {
      action: "showNext",
      value: true,
    };
    parent.postMessage(JSON.stringify(response), '*');
  }

  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});
    // 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: `/sms/`,
    //   query: type === 'embedded' ? {type: 'embedded', module} : {module},
    // });
  }

  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: `/sms/`,
      query: type === 'embedded' ? {type: 'embedded', module} : {module},
    });
  }

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

    this.setState({schema, loadingStatus: this.state.loadingStatus + 1}, () => {
      const type = this.props.location.query.type;
      if (type === 'embedded') {
        this.removeStandAlone();
      }
    });
    return schema;
  }

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

  injectMultiColSection(section) {
    _.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;
        }
        temp.injectedEvents = {};
        _.forEach(col.supportedEvents, (event) => {
          temp.injectedEvents[event] = this.getMappedEvent(col.id, event);
        });

        if (temp.type === 'icon') {
          return true;
        }
        if (temp.value && messages[temp.value]) {
          temp.value = this.props.intl.formatMessage(messages[temp.value]);
        }
        if (temp.label && messages[temp.label]) {
          temp.label = this.props.intl.formatMessage(messages[temp.label]);
        }
        if (temp.errorMessage && messages[temp.errorMessage]) {
          temp.errorMessage = this.props.intl.formatMessage(messages[temp.errorMessage]);
        }
        if (temp.placeholder && messages[temp.placeholder]) {
          temp.placeholder = this.props.intl.formatMessage(messages[temp.placeholder]);
        }
        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);
        });

        if (temp.type === 'icon') {
          return true;
        }
        if (temp.value && messages[temp.value]) {
          temp.value = this.props.intl.formatMessage(messages[temp.value]);
        }
        if (temp.label && messages[temp.label]) {
          temp.label = this.props.intl.formatMessage(messages[temp.label]);
        }
        if (temp.errorMessage && messages[temp.errorMessage]) {
          temp.errorMessage = this.props.intl.formatMessage(messages[temp.errorMessage]);
        }
        if (temp.placeholder && messages[temp.placeholder]) {
          temp.placeholder = this.props.intl.formatMessage(messages[temp.placeholder]);
        }
        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);
      });

      if (temp.type === 'icon') {
        return true;
      }
      if (temp.value && messages[temp.value]) {
        temp.value = this.props.intl.formatMessage(messages[temp.value]);
      }
      if (temp.label && messages[temp.label]) {
        temp.label = this.props.intl.formatMessage(messages[temp.label]);
      }
      if (temp.errorMessage && messages[temp.errorMessage]) {
        temp.errorMessage = this.props.intl.formatMessage(messages[temp.errorMessage]);
      }
      if (temp.placeholder && messages[temp.placeholder]) {
        temp.placeholder = this.props.intl.formatMessage(messages[temp.placeholder]);
      }
      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);
      });

      if (temp.type === 'icon') {
        return true;
      }
      if (temp.value && messages[temp.value]) {
        temp.value = this.props.intl.formatMessage(messages[temp.value]);
      }
      if (temp.label && messages[temp.label]) {
        temp.label = this.props.intl.formatMessage(messages[temp.label]);
      }
      if (temp.errorMessage && messages[temp.errorMessage]) {
        temp.errorMessage = this.props.intl.formatMessage(messages[temp.errorMessage]);
      }
      if (temp.placeholder && messages[temp.placeholder]) {
        temp.placeholder = this.props.intl.formatMessage(messages[temp.placeholder]);
      }
      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;
  }

  cloneColLabel(sectionObj, tabIndex) {
    const section = _.cloneDeep(sectionObj);
    const inputFields = _.forEach(section.inputFields, (inputField) => {
      const inputF = inputField;
      inputF.id = `${inputField.id}${tabIndex}`;
      inputF.paneIndex = tabIndex;
      return inputF;
    });
    section.inputFields = inputFields;

    return section;
  }

  cloneMultiCol(sectionObj, tabIndex) {
    const section = _.cloneDeep(sectionObj);
    const inputFields = _.forEach(section.inputFields, (inputField) => {
      const inputF = inputField;
      const cols = _.forEach(inputF.cols, (col) => {
        const colTemp = col;
        colTemp.id = `${col.id}${tabIndex}`;
        colTemp.paneIndex = tabIndex;
        return colTemp;
      });
      inputF.cols = cols;
      return inputF;
    });
    section.inputFields = inputFields;

    return section;
  }

  cloneParent(section, tabIndex) {
    const parentsect = section;
    const childSectionsBeforeCloning = parentsect.childSections.slice();
    const childSections = [];
    _.forEach(childSectionsBeforeCloning, (childSection) => {
      let sect = {};
      if (childSection.type === 'col-label') {
        sect = this.cloneColLabel(childSection, tabIndex);
      } else if (childSection.type === 'multicols') {
        sect = this.cloneMultiCol(childSection, tabIndex);
      } else if (childSection.type === 'parent') {
        sect = this.cloneParent(childSection, tabIndex);
      }

      childSections.push(sect);
      return true;
    });

    parentsect.childSections = childSections;

    return _.cloneDeep(parentsect);
  }

  deleteVersion() {
    if (this.state.tabCount === 1) {
      return;
    }
    const schema = _.cloneDeep(this.state.schema);
    schema.containers[0].panes.splice(this.state.tabCount - 1, 1);
    schema.containers[0].tabBarExtraContent.sections[0].actionFields[0].cols[0].disabled = false;
    this.setState({schema, tabCount: this.state.tabCount - 1});
  }

  renameVersion() {

  }

  markFinalVersion() {
    const message = getMessageObject('success', this.props.intl.formatMessage(messages.templateMarkedSuccessfully), true);
    this.props.globalActions.addMessageToQueue(message);
  }

  duplicateVersion() {
    this.addVersion(this.state.tabCount);
  }

  addVersion(data, addNow) {
    let tabIndex = data + 1;
    const schema = _.cloneDeep(this.state.schema);
    const containers = schema.containers.slice();
    const panes = containers[0].panes.slice();
    if (addNow && data === 1) {
      for (let idx = 1; idx < addNow; idx += 1) {
        const sections = [];
        const firstPane = _.cloneDeep(panes[0]);
        tabIndex = idx + 1;
        _.forEach(firstPane.sections, (section) => { // eslint-disable-line no-loop-func
          let sect = _.cloneDeep(section);
          if (sect.type === 'col-label') {
            sect = this.cloneColLabel(sect, tabIndex);
          } else if (sect.type === 'multicols') {
            sect = this.cloneMultiCol(sect, tabIndex);
          } else if (sect.type === 'parent') {
            sect = this.cloneParent(sect, tabIndex);
          }
          sections.push(sect);
          return true;
        });
        firstPane.sections = sections;
        schema.containers[0].panes.push(firstPane);

        if (tabIndex === 5) {
          schema.containers[0].tabBarExtraContent.sections[0].actionFields[0].cols[0].disabled = true;
        }
      }
      if (schema) {
        this.setState({schema});
      }
    } else if (!addNow) {
      const sections = [];
      const firstPane = _.cloneDeep(panes[0]);
      _.forEach(firstPane.sections, (section) => {
        let sect = _.cloneDeep(section);
        if (sect.type === 'col-label') {
          sect = this.cloneColLabel(sect, tabIndex);
        } else if (sect.type === 'multicols') {
          sect = this.cloneMultiCol(sect, tabIndex);
        } else if (sect.type === 'parent') {
          sect = this.cloneParent(sect, tabIndex);
        }
        sections.push(sect);
        return true;
      });
      firstPane.sections = sections;
      schema.containers[0].panes.push(firstPane);

      if (tabIndex === 5) {
        schema.containers[0].tabBarExtraContent.sections[0].actionFields[0].cols[0].disabled = true;
      }
      if (schema) {
        this.setState({schema});
      }
    }
  }

  validateFormData(formData) {
    const tabCount = this.state.tabCount;
    let isValid = true;
    for (let cnt = 0; cnt < tabCount; cnt += 1) {
      const index = cnt + 1;
      if (formData[cnt]) {
        const text = formData[cnt][`sms-editor${index > 1 ? index : ''}`];
        if (text.indexOf('{{optout}}') === -1) {
          isValid = false;
        }
      }
    }
    if (isValid) {
      return true;
    }
    const message = getMessageObject('error', this.props.intl.formatMessage(messages.templateNotValid), true);
    this.props.globalActions.addMessageToQueue(message);

    return false;
  }

  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;
    if (formData.base) {
      formData.base[field.id] = myField.value;
    }
    this.setState({formData}, () => this.onTemplateContentChange());
  }

  startTemplateCreation(data) {
    if (data.edit) {
      const ifUnicode = checkUnicode(data.content ? data.content : '');

      const content = data.content;
      const id = _.uniqueId();
      const tempData = {
        'sms-editor': content,
        'unicode-validity': false,
        'base': true,
        'tabKey': id,
      };
      const formData = {};
      formData[0] = tempData;
      formData.base = tempData;
      this.setState({formData, loading: false, injectedTags: data.tags, tabKey: id}, () => {
        this.setState({tabKey: ''});
      });
    } else {
      this.setState({injectedTags: 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;
        case "getFormData":
          this.getFormData(e, type.value);
          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;
      }
    }
  }

  handleOnTagsContextChange = (data) => {
    const query = {
      layout: 'SMS',
      type: 'TAG',
      context: (data && data.toLowerCase() === 'all') ? 'default' : (data && data.toLowerCase()),
      embedded: this.props.location.query.type === 'embedded' ? this.props.location.query.type : 'full',
    };
    this.props.globalActions.fetchSchemaForEntity(query);
  }

  removeStandAlone() {
    const schema = _.cloneDeep(this.state.schema);
    const childSections = _.get(schema, 'standalone.sections[0].childSections');
    childSections.splice(2, 1);
    const fields = _.get(childSections, '[1].childSections[0].childSections');//removing template name section
    fields.splice(0, 1);
    _.set(childSections, '[1].childSections[0].childSections', fields);
    _.set(schema, 'standalone.sections[0].childSections', childSections);
    this.setState({ schema, loadingStatus: this.state.loadingStatus + 1 });
  }

  validateContent = (e) => {
    const response = {
      action: "validateContent",
      value: this.state.isFormValid,
    };
    // if (content.indexOf('{{optout}}') === -1) {
    //   const message = getMessageObject('error', 'Template data is not valid', true);
    //   this.props.globalActions.addMessageToQueue(message);
    //   response.value = 'invalid';
    // }

    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.props.metaEntities.layouts[0].definition });
  }

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

  validateAndSaveFormData = () => {
    this.setState({startValidation: true});
  }
  stopValidation = () => {
    this.setState({startValidation: false});
  }

  getTemplateContent = () => {
    // Get SMS content from formData
    if (!this.state.formData || !Array.isArray(this.state.formData) || this.state.formData.length === 0) {
      return '';
    }
    const currentTabData = this.state.formData[this.state.currentTab - 1];
    if (!currentTabData) {
      return '';
    }
    
    // PRIORITY 1: Check direct path first (most common for SMS)
    // This handles: formData[0]['sms-editor']
    if (currentTabData['sms-editor']) {
      return currentTabData['sms-editor'];
    }
    
    // PRIORITY 2: Check activeTab structure (for versioned templates)
    // This handles: formData[0][activeTab]['sms-editor']
    const activeTab = currentTabData?.activeTab || 'base';
    if (currentTabData[activeTab]?.['sms-editor']) {
      return currentTabData[activeTab]['sms-editor'];
    }
    
    // PRIORITY 3: Check base explicitly (fallback)
    // This handles: formData[0]['base']['sms-editor']
    if (currentTabData['base']?.['sms-editor']) {
      return currentTabData['base']['sms-editor'];
    }
    
    return '';
  }

  handleTestAndPreview = () => {
    // If parent is managing state (props exist), call parent handler
    // Otherwise, manage local state
    if (this.props.handleTestAndPreview) {
      this.props.handleTestAndPreview();
    } else {
      this.setState({
        showTestAndPreviewSlidebox: true,
        isTestAndPreviewMode: true,
      });
    }
  }

  handleCloseTestAndPreview = () => {
    // If parent is managing state (props exist), call parent handler
    // Otherwise, manage local state
    if (this.props.handleCloseTestAndPreview) {
      this.props.handleCloseTestAndPreview();
    } else {
      this.setState({
        showTestAndPreviewSlidebox: false,
        isTestAndPreviewMode: false,
      });
    }
  }

  saveFormData() {
    // In library mode: FormBuilder calls onSubmit only after liquid validation succeeds.
    // Submit to parent here so the slidebox can close with valid data.
    if (!this.props.isFullMode) {
      if (this.state.pendingGetFormData && this.props.getFormSubscriptionData) {
        this.props.getFormSubscriptionData(this.getFormData());
        this.setState({ pendingGetFormData: false, startValidation: false });
      }
      return;
    }
    //Logic to save in db etc
    const formData = _.cloneDeep(this.state.formData);
    const obj = {};
    obj.versions = {
      base: {},
      history: [],
    };
    obj.type = SMS;
    for (let index = 0; index < this.state.tabCount; index += 1 ) {
      obj.versions.history.push(formData[index]);
      // if (formData[index])
    }
    obj.name = formData['template-name'];
    obj.versions.base = formData.base;

    this.props.actions.createTemplate(obj, this.onCreateTemplateComplete);
  }
  isSmsLoading = () => {
    //let {isLoading} = this.props;
    let isLoading = this.props.isLoadingMetaEntities || this.state.loading || (this.props.Create && "createTemplateInProgress" in this.props.Create && this.props.Create.createTemplateInProgress);
    const {isFullMode} = this.props;
    if (!isLoading) {
      isLoading = isFullMode ? this.state.loadingStatus < 1 : this.state.loadingStatus < 2;
    }
    // if (isLoading && this.state.loadingStatus >= 2) {
    //   this.props.creativesContainerActions.hideCreativesContanerLoader();
    // }
    if (!isLoading && this.props.setIsLoadingContent) {
      this.props.setIsLoadingContent(isLoading);
    }
    return isLoading;
  }
  stopValidation = () => {
    this.setState({startValidation: false});
  }
  startValidation = () => {
    this.setState({startValidation: true}, this.showError);
  }
  render() {
    const schema = this.state.schema;
    const spinning = this.isSmsLoading();
    let tags = this.props.metaEntities && this.props.metaEntities.tags && this.props.metaEntities.tags.standard ? this.props.metaEntities.tags.standard : [];

    if (this.props.location.query.type === 'embedded' && this.props.location.query.module === 'library' && !this.props.getDefaultTags) {
      tags = this.props.supportedTags; // if get default tags is not present and supported tags is present use that inlbrary mode
    }
    return (
      <div className="sms-create-container">
        <CapSpin spinning={spinning}>
          {/*<\CapRow style={{marginBottom: '16px', marginLeft: '-40px'}}>
            <CapColumn offset={1}>
              <Breadcrumb>
                <Breadcrumb.Item>Campaigns</Breadcrumb.Item>
                <Breadcrumb.Item>Creatives</Breadcrumb.Item>
                <Breadcrumb.Item>SMS</Breadcrumb.Item>
              </Breadcrumb>
            </CapColumn>
          </CapRow>*/}
          <CapRow>
            <CapColumn>
              <FormBuilder
                showLiquidErrorInFooter={this.props.showLiquidErrorInFooter}
                isFullMode={this.props.isFullMode}
                schema={schema}
                refs={this.componentRefs}
                onSubmit={this.saveFormData}
                onChange={this.onFormDataChange}
                currentTab={this.state.currentTab}
                showModal={this.state.showModal}
                modal={this.state.modalContent}
                parent={this}
                iframeParent={parent}
                formData={_.cloneDeep(this.state.formData)}
                location={this.props.location}
                tabKey={this.state.tabKey}
                tags={tags}
                tagModule={this.props.getDefaultTags}
                injectedTags={this.props.injectedTags ? this.props.injectedTags : {}}
                onFormValidityChange={this.setFormValidity}
                usingTabContainer
                checkValidation={this.state.checkValidation}
                onContextChange={this.handleOnTagsContextChange}
                handleCancelModal={this.handleCancelModal}
                router={this.props.router}
                startValidation={this.state.startValidation}
                stopValidation={this.stopValidation}
                selectedOfferDetails={this.props.selectedOfferDetails}
                onTestContentClicked={this.props.onTestContentClicked}
                onPreviewContentClicked={this.props.onPreviewContentClicked}
                eventContextTags={this.props?.eventContextTags}
                waitEventContextTags={this.props?.waitEventContextTags}
              />
            </CapColumn>
          </CapRow>
        </CapSpin>
        <TestAndPreviewSlidebox
          show={this.props.showTestAndPreviewSlidebox !== undefined 
            ? this.props.showTestAndPreviewSlidebox 
            : this.state.showTestAndPreviewSlidebox}
          onClose={this.props.handleCloseTestAndPreview || this.handleCloseTestAndPreview}
          formData={this.state.formData}
          content={this.getTemplateContent()}
          currentChannel={SMS}
        />
      </div>
    );
  }
}

Create.propTypes = {
  actions: PropTypes.object.isRequired,
  Create: PropTypes.object,
  router: PropTypes.object,
  location: PropTypes.object,
  route: PropTypes.object,
  globalActions: PropTypes.object,
  metaEntities: PropTypes.object,
  intl: intlShape.isRequired,
  supportedTags: PropTypes.array,
  getDefaultTags: PropTypes.string,
  injectedTags: PropTypes.object,
  setIsLoadingContent: PropTypes.bool,
  isFullMode: PropTypes.bool,
  getFormSubscriptionData: PropTypes.func,
  isLoadingMetaEntities: PropTypes.bool,
  selectedOfferDetails: PropTypes.array,
  eventContextTags: PropTypes.array,
  waitEventContextTags: PropTypes.object,
  showTestAndPreviewSlidebox: PropTypes.bool,
  handleTestAndPreview: PropTypes.func,
  handleCloseTestAndPreview: PropTypes.func,
  isTestAndPreviewMode: PropTypes.bool,
};

const mapStateToProps = createStructuredSelector({
  Create: makeSelectCreate(),
  createResponse: makeSelectCreateResponse(),
  metaEntities: makeSelectMetaEntities(),
  isLoadingMetaEntities: isLoadingMetaEntities(),
  injectedTags: setInjectedTags(),
});

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

const withReducer = injectReducer({ key: 'create', reducer: v2SmsCreateReducer });

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