/*
 *
 * Ebill
 *
 */

import PropTypes from 'prop-types';

import React from 'react';
import { bindActionCreators } from 'redux';
import { Spin, Row, Col, Breadcrumb } from 'antd';
import Helmet from 'react-helmet';
import { intlShape } from 'react-intl';
import _ from 'lodash';
import { createStructuredSelector } from 'reselect';
import * as actions from './actions';
import FormBuilder from '../../v2Components/FormBuilder';
import { makeSelectMetaEntities, makeSelectAuthenticated, setInjectedTags } from '../Cap/selectors';
import { makeSelectTemplates } from '../Templates/selectors';
import {getMessageObject} from '../../utils/messageUtils';
import makeSelectEbill from './selectors';
import messages from './messages';
import EmailPreview from '../../v2Components/EmailPreview';
import './_ebill.scss';
import withCreatives from '../../hoc/withCreatives';
import injectReducer from '../../utils/injectReducer';
import v2EbillReducer from './reducer';
import * as globalActions from '../Cap/actions';

const BreadcrumbItem = Breadcrumb.Item;

export class Ebill extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.state = {
      formData: {},
      tabCount: 1,
      currentTab: 1,
      isEdit: false,
      loading: false,
      isFormValid: true,
      injectedTags: {},
      checkValidation: false,
      tabKey: '',
      showEbillPreview: false,
      device: 'desktop',
      schema: {},
      // schema: {
      //   standalone: {
      //     sections: [
      //       {
      //         type: "multicols",
      //         inputFields: [
      //           {
      //             cols: [
      //               {
      //                 id: "template-name",
      //                 placeholder: "Enter template name",
      //                 type: "input",
      //                 metaType: "text",
      //                 datatype: "string",
      //                 required: true,
      //                 style: {
      //                   fontSize: "20px",
      //                   fontFamily: "proxima-nova,sans-serif",
      //                   fontStyle: "normal",
      //                   fontWeight: 600,
      //                 },
      //                 styling: "semantic",
      //                 order: 1,
      //                 width: 9,
      //                 customComponent: false,
      //                 standalone: true,
      //                 onlyDisplay: false,
      //                 errorMessage: "Template name cannot be empty.",
      //                 supportedEvents: [
      //                   "onChange",
      //                 ],
      //               },
      //               // {
      //               //   id: "template-version",
      //               //   type: "select",  //Resembles component to be used
      //               //   options: [],
      //               //   metaType: "text",
      //               //   datatype: "string",
      //               //   required: true,
      //               //   fluid: true,
      //               //   style: {
      //               //     fontSize: '14px',
      //               //     fontFamily: 'open-sans',
      //               //     fontStyle: 'normal',
      //               //     marginBottom: '16px',
      //               //   },
      //               //   styling: "semantic",
      //               //   order: 1,
      //               //   width: 5,
      //               //   customComponent: false,
      //               //   standalone: true,
      //               //   supportedEvents: [
      //               //     'onSelect',
      //               //     'addVersion',
      //               //   ],
      //               // },
      //               {
      //                 id: "preview-button",
      //                 width: 3,
      //                 offset: 8,
      //                 metaType: "submit-button",
      //                 colStyle: {
      //                   textAlign: "right",
      //                   paddingRight: "12px",
      //                 },
      //                 type: "button",
      //                 buttonType: "cancel",
      //                 value: "Preview",
      //                 customComponent: false,
      //                 standalone: true,
      //                 styling: "semantic",
      //                 order: 3,
      //                 fluid: false,
      //                 submitAction: "previewTemplate",
      //                 onlyDisplay: true,
      //                 supportedEvents: [
      //                   "previewTemplate",
      //                 ],
      //               },
      //               {
      //                 id: "cancel-button",
      //                 width: 2,
      //                 metaType: "submit-button",
      //                 colStyle: {
      //                   textAlign: "right",
      //                   width: "9%",
      //                 },
      //                 type: "button",
      //                 buttonType: "cancel",
      //                 value: "Cancel",
      //                 customComponent: false,
      //                 standalone: true,
      //                 styling: "semantic",
      //                 order: 3,
      //                 fluid: false,
      //                 onlyDisplay: true,
      //                 submitAction: "cancelTemplate",
      //                 supportedEvents: [
      //                   "cancelTemplate",
      //                 ],
      //               },
      //               {
      //                 id: "save-button",
      //                 width: 2,
      //                 metaType: "submit-button",
      //                 colStyle: {
      //                   textAlign: "right",
      //                   width: "7%",
      //                 },
      //                 type: "button",
      //                 buttonType: "primary",
      //                 value: "Save",
      //                 customComponent: false,
      //                 styling: "semantic",
      //                 order: 3,
      //                 fluid: false,
      //                 standalone: true,
      //                 onlyDisplay: true,
      //                 submitAction: "saveFormData",
      //                 supportedEvents: [
      //                   "saveFormData",
      //                 ],
      //               },
      //             ],
      //           },
      //         ],
      //         actionFields: [],
      //       },
      //     ],
      //   },
      //   containers: [
      //     {
      //       panes: [
      //         {
      //           sections: [
      //             {
      //               type: "parent",
      //               width: 24,
      //               rowStyle: {
      //                 height: "calc(100vh - 142px)",
      //               },
      //               childSections: [
      //                 {
      //                   colStyle: {
      //                     paddingBottom: "16px",
      //                     height: "100%",
      //                   },
      //                   width: 24,
      //                   type: "parent",
      //                   childSections: [
      //                     {
      //                       type: "multicols",
      //                       inputFields: [
      //                         {
      //                           cols: [
      //                             {
      //                               id: "ebill-editor",
      //                               style: {
      //                                 background: '#efefef',
      //                                 resize: 'none',
      //                                 float: 'left',
      //                                 border: '1px solid #efefef',
      //                                 width: "100%",
      //                                 height: '100%',
      //                               },
      //                               type: "textarea",
      //                               metaType: "text",
      //                               datatype: "string",
      //                               required: true,
      //                               errorMessage: "Template content has unsupported/missing tags!",
      //                               fluid: false,
      //                               styling: "semantic",
      //                               onlyDisplay: false,
      //                               width: 24,
      //                               // autosize: true,
      //                               // autosizeParams: {
      //                               //   maxRows: 18,
      //                               //   minRows: 3,
      //                               // },
      //                               order: 2,
      //                               customComponent: true,
      //                               supportedEvents: [
      //                                 "onChange",
      //                               ],
      //                             },
      //                           ],
      //                         },

      //                       ],
      //                       actionFields: [],
      //                     },
      //                     // {
      //                     //   type: "multicols",
      //                     //   inputFields: [
      //                     //     {
      //                     //       cols: [
      //                     //         {
      //                     //           offset: 19,
      //                     //           id: "tagList",
      //                     //           label: "Tags",
      //                     //           type: "tag-list",
      //                     //           metaType: "List",
      //                     //           datatype: "select",
      //                     //           required: true,
      //                     //           fluid: true,
      //                     //           onlyDisplay: true,
      //                     //           styling: "semantic",
      //                     //           order: 1,
      //                     //           customComponent: true,
      //                     //           supportedEvents: [
      //                     //             "onTagSelect",
      //                     //           ],
      //                     //         },
      //                     //       ],
      //                     //     },
      //                     //   ],
      //                     //   actionFields: [],
      //                     // },
      //                   ],
      //                 },
      //               ],
      //             },
      //           ],
      //         },
      //       ],
      //       type: "tabs",
      //       defaultPanes: 1,
      //       additionalPanes: 0,
      //       id: "pane",
      //       tabBarExtraContent: {
      //         sections: [
      //           {
      //             type: "multicols",
      //             actionFields: [
      //               {
      //                 cols: [
      //                   // {
      //                   //   id: "add-version-button",
      //                   //   metaType: "submit-button",
      //                   //   type: "button",
      //                   //   buttonType: "cancel",
      //                   //   icon: "plus-circle-o",
      //                   //   value: "New Version",
      //                   //   customComponent: false,
      //                   //   onlyDisplay: true,
      //                   //   styling: "semantic",
      //                   //   order: 3,
      //                   //   fluid: false,
      //                   //   submitAction: "addVersion",
      //                   //   supportedEvents: [
      //                   //     "addVersion",
      //                   //   ],
      //                   // },
      //                   {
      //                     offset: 6,
      //                     id: "tagList",
      //                     label: "Tags",
      //                     type: "tag-list",
      //                     metaType: "List",
      //                     datatype: "select",
      //                     required: true,
      //                     fluid: true,
      //                     onlyDisplay: true,
      //                     styling: "semantic",
      //                     order: 1,
      //                     customComponent: true,
      //                     supportedEvents: [
      //                       "onTagSelect",
      //                     ],
      //                   },
      //                 ],
      //               },
      //             ],
      //             inputFields: [],
      //           },
      //         ],
      //       },
      //       tabContent: {
      //         sections: [
      //           {
      //             type: "multicols",
      //             inputFields: [
      //               {
      //                 rowStyle: {
      //                   display: "flex",
      //                   flex: 1,
      //                 },
      //                 cols: [
      //                   {
      //                     id: "base-version-icon",
      //                     metaType: "display",
      //                     type: "icon",
      //                     onlyDisplay: true,
      //                     primitive: false,
      //                     value: "chat",
      //                     customComponent: false,
      //                     order: 3,
      //                     fluid: false,
      //                     style: {
      //                       color: "#2E89DF",
      //                     },
      //                   },
      //                   {
      //                     id: "tab-header",
      //                     metaType: "label",
      //                     value: "English",
      //                     primitive: true,
      //                     dynamicTab: false,
      //                     type: "div",
      //                     width: 5,
      //                     offset: 0,
      //                     onlyDisplay: true,
      //                     colStyle: {
      //                       flex: 1,
      //                     },
      //                     supportedEvents: [
      //                       "onChange",
      //                     ],
      //                   },
      //                   {
      //                     id: "tab-options-popover",
      //                     metaType: "display",
      //                     colStyle: {
      //                       flex: 0,
      //                       display: 'none',
      //                     },
      //                     type: "popover",
      //                     customComponent: false,
      //                     styling: "semantic",
      //                     order: 3,
      //                     fluid: false,
      //                     onlyDisplay: true,
      //                     submitAction: "onTabOptionSelect",
      //                     supportedEvents: [
      //                       "onTabOptionSelect",
      //                     ],
      //                     content: {
      //                       sections: [
      //                         {
      //                           type: "multicols",
      //                           inputFields: [
      //                             {
      //                               cols: [
      //                                 {
      //                                   id: "mark-final-version-label",
      //                                   metaType: "label",
      //                                   type: "div",
      //                                   primitive: true,
      //                                   value: "Mark as Final",
      //                                   onlyDisplay: true,
      //                                   customComponent: false,
      //                                   order: 3,
      //                                   fluid: false,
      //                                   className: "version-popover",
      //                                   submitAction: "markFinalVersion",
      //                                   supportedEvents: [
      //                                     "markFinalVersion",
      //                                   ],
      //                                 },
      //                               ],
      //                             },
      //                             {
      //                               cols: [
      //                                 {
      //                                   id: "duplicate-version-label",
      //                                   metaType: "label",
      //                                   type: "div",
      //                                   primitive: true,
      //                                   value: "Duplicate",
      //                                   onlyDisplay: true,
      //                                   customComponent: false,
      //                                   order: 3,
      //                                   fluid: false,
      //                                   className: "version-popover",
      //                                   submitAction: "duplicateVersion",
      //                                   supportedEvents: [
      //                                     "duplicateVersion",
      //                                   ],
      //                                 },
      //                               ],
      //                             },
      //                             {
      //                               cols: [
      //                                 {
      //                                   id: "rename-version-label",
      //                                   metaType: "label",
      //                                   type: "div",
      //                                   primitive: true,
      //                                   value: "Rename",
      //                                   onlyDisplay: true,
      //                                   customComponent: false,
      //                                   order: 3,
      //                                   fluid: false,
      //                                   className: "version-popover",
      //                                   submitAction: "renameVersion",
      //                                   supportedEvents: [
      //                                     "renameVersion",
      //                                   ],
      //                                 },
      //                               ],
      //                             },
      //                             {
      //                               cols: [
      //                                 {
      //                                   id: "delete-version-label",
      //                                   metaType: "label",
      //                                   type: "div",
      //                                   primitive: true,
      //                                   value: "Delete",
      //                                   onlyDisplay: true,
      //                                   customComponent: false,
      //                                   order: 3,
      //                                   fluid: false,
      //                                   className: "version-popover",
      //                                   submitAction: "deleteVersion",
      //                                   supportedEvents: [
      //                                     "deleteVersion",
      //                                   ],
      //                                 },
      //                               ],
      //                             },
      //                           ],
      //                           actionFields: [],
      //                         },
      //                       ],
      //                     },
      //                     value: {
      //                       sections: [
      //                         {
      //                           type: "multicols",
      //                           inputFields: [
      //                             {
      //                               cols: [
      //                                 {
      //                                   id: "tab-option-icon",
      //                                   metaType: "display",
      //                                   type: "icon",
      //                                   onlyDisplay: true,
      //                                   primitive: false,
      //                                   value: "",
      //                                   customComponent: false,
      //                                   order: 3,
      //                                   fluid: false,
      //                                 },
      //                               ],
      //                             },
      //                           ],
      //                           actionFields: [],
      //                         },
      //                       ],
      //                     },
      //                     trigger: "click",
      //                     placement: "bottomRight",
      //                   },
      //                 ],
      //               },
      //             ],
      //             actionFields: [],
      //           },
      //         ],
      //       },
      //       label: "Version",
      //       onlyDisplay: true,
      //       supportedEvents: [
      //         "onTabChange",
      //       ],
      //     },
      //   ],
      //   channel: "EBILL",
      // },
    };

    this.map = {
      "template-name": {
        onChange: this.onTemplateNameChange,
      },
      "template-version": {
        onSelect: this.handleVersionSelect,
        addVersion: this.addVersion,
      },
      "preview-button": {
        previewTemplate: this.toggleEmailPreview,
      },
      "cancel-button": {
        cancelTemplate: this.cancelTemplate,
      },
      "save-button": {
        saveFormData: this.saveFormData,
      },
      "ebill-editor": {
        onChange: this.onTemplateContentChange,
      },
      "tagList": {
        onTagSelect: this.onTagSelect,
      },
      "add-language-button": {
        addLanguage: this.addLanguage,
      },
      "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,
      },
      "delete-language-label": {
        deleteLanguage: this.deleteLanguage,
      },
    };
    this.isTagLoaded = false;
  }

  componentWillMount() {
    if (this.props.params.id) {
      this.props.actions.getTemplateDetails(this.props.params.id, 'ebill');
      this.setState({isEdit: true});
    }

    if (!_.isEmpty(this.props.Templates.edmTemplate) && this.props.Templates.edmTemplate.versions.base.is_drag_drop) {
      this.props.actions.getCmsData('edm', this.props.Templates.edmTemplate.versions.base.drag_drop_id);
    }
  }

  componentDidMount() {
    const query = {
      layout: 'EBILL',
      type: 'LAYOUT',
    };
    this.props.globalActions.fetchSchemaForEntity(query);
    
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.metaEntities && nextProps.metaEntities.layouts && nextProps.metaEntities.layouts.length > 0 && _.isEmpty(this.state.schema)) {
      this.injectEvents(nextProps.metaEntities.layouts[0].definition);
      
      const query = {
        layout: 'EBILL',
        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',
      };
      this.props.globalActions.fetchSchemaForEntity(query);
    }

    if (this.state.isEdit && !_.isEmpty(nextProps.Ebill.templateDetails) && !_.isEqual(nextProps.Ebill.templateDetails, this.props.Ebill.templateDetails)) {
      this.setEditState(nextProps.Ebill.templateDetails);
    }

    if (nextProps.Ebill.createResponse && nextProps.Ebill.createResponse.templateId) {
      let message;
      if (this.state.isEdit) {
        message = getMessageObject('success', this.props.intl.formatMessage(messages.ebillEditSuccess), true);
      } else {
        message = getMessageObject('success', this.props.intl.formatMessage(messages.ebillCreateSuccess), true);
      }
      this.props.globalActions.addMessageToQueue(message);
      this.props.actions.clearCRUDResponse();
      const module = this.props.location.query.module ? this.props.location.query.module : 'default';
      const type = this.props.location.query.type;
      this.props.router.push({
        pathname: `/ebill`,
        query: type === 'embedded' ? {type: 'embedded', module} : {module},
      });
    }

    if (nextProps.Ebill.createTemplateError && !_.isEqual(nextProps.Ebill.createTemplateError, this.props.Ebill.createTemplateError)) {
      const message = getMessageObject('error', (nextProps.Ebill.createTemplateErrorMessage && nextProps.Ebill.createTemplateErrorMessage !== '') ? nextProps.Ebill.createTemplateErrorMessage : this.props.intl.formatMessage(messages.somethingWentWrong), true);
      this.props.globalActions.addMessageToQueue(message);
    }

    
    if (nextProps.Ebill.cmsData !== '' && !_.isEqual(nextProps.Ebill.cmsData, this.props.Ebill.cmsData)) {
      const formData = _.cloneDeep(this.state.formData);
      formData[this.state.currentTab - 1][`ebill-editor${this.state.currentTab > 1 ? this.state.currentTab : ''}`] = nextProps.Ebill.cmsData.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/\\&quot;/g, "\"");
      
      this.setState({formData});
    }

    if (nextProps.Templates.selectedEmailLayout && nextProps.Templates.selectedEmailLayout !== '' && this.state.formData[this.state.currentTab - 1] && this.state.formData[this.state.currentTab - 1][`ebill-editor${this.state.currentTab > 1 ? this.state.currentTab : ''}`] !== '') {
      const formData = _.cloneDeep(this.state.formData);
      formData[this.state.currentTab - 1][`ebill-editor${this.state.currentTab > 1 ? this.state.currentTab : ''}`] = nextProps.Templates.selectedEmailLayout;
      
      this.setState({formData});
    }

    if (nextProps.Templates.selectedEmailLayout && !_.isEqual(nextProps.Templates.selectedEmailLayout, this.props.Templates.selectedEmailLayout) && !_.isEmpty(this.state.schema)) {
      this.setState({ content: (this.props.Templates.selectedEmailLayout ? this.props.Templates.selectedEmailLayout : '')}, () => {
        // this.injectEvents(this.state.schema);
      });
    }
  }

  componentWillUnmount() {
    this.props.actions.clearStoreValues();
  }

  onTagSelect = (data, currentTab, value) => {
    
    if (this.state.isDragDrop) {
      const msg = {
        action: "InsertToCursor",
        content: `{{${data}}}`,
      };
      const msgString = JSON.stringify(msg);
      const win = document.getElementById(`edmeditor${this.state.currentTab > 1 ? this.state.currentTab : ''}`).contentWindow;
      win.postMessage(msgString, '*');
    } else if (this.state.editorInstanse) {
      this.state.editorInstanse.insertHtml(`{{${data}}}`);
    }
  };

  onTabChange = (data, formData) => {
    
    this.setState({currentTab: data, formData});
  };

  onFormDataChange = (formData, tabCount, currentTab) => {
    
    const tmpFormData = _.cloneDeep(formData);
    if (this.props.Templates.selectedEmailLayout !== '' && tmpFormData['0']['ebill-editor'] === '') {
      tmpFormData['0']['ebill-editor'] = this.props.Templates.selectedEmailLayout;
      tmpFormData.base['ebill-editor'] = this.props.Templates.selectedEmailLayout;
    }
    this.setState({formData: tmpFormData, tabCount});
    if (currentTab) {
      this.setState({currentTab});
    }
  };

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

  onTemplateNameChange = (name) => {
    
  };

  onTemplateContentChange = (content) => {
    
  };

  setEditState = (data) => {
    const that = this;
    const tabCount = data.versions.history.length;
    const formData = {};
    formData['template-name'] = data.name;
    const type = this.props.location.query.type;
    let ifBase = false;
    for (let count = 0; count < tabCount; count += 1) {
      formData[count] = _.cloneDeep(data.versions.history[count]);
      if (data.versions && data.versions.history && data.versions.history[count] && data.versions.history[count].base) {
        if (!formData[count]) {
          formData[count] = {};
        }
        formData[count].base = true;
        ifBase = true;
      }
      if (type === 'embedded' || count > 0) {
        setTimeout( () => {
          
          if (type === 'embedded') {
            that.removeStandAlone();
          } else {
            that.addVersion(count, tabCount);
          }
        }, 0 );
      }
    }
    if (!ifBase) {
      if (!formData[0]) {
        formData[0] = {};
      }
      formData[0].base = true;
    }
    formData.base = data.versions.base;
    
    this.setState({tabCount, formData, editData: data, currentTab: 1}, () => {
    });
  };

  getMappedEvent = (id, event) => {
    
    return this.map[id][event];
  };

  setFormValidity = (isFormValid) => {
    this.setState({isFormValid});
  };

  changePreviewDevice = (device) => {
    this.setState({ device });
  };

  toggleEmailPreview = () => {
    this.setState({ showEbillPreview: !this.state.showEbillPreview });
  };

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

  saveFormData = (formData) => {
    //Logic to save in db etc
    // const isValidated = this.validateFormData(formData);
    // 
    // if (!isValidated) {
    //   return;
    // }
    
    const obj = {};
    obj.versions = {
      base: {},
      history: [],
    };
    if (this.state.isEdit) {
      obj._id = this.props.Ebill.templateDetails._id;
    }
    obj.type = 'EBILL';
    _.forEach(formData, (data, index) => {
      if (!isNaN(index) && data) {
        obj.versions.history.push(data);
      }
    });
    obj.name = formData['template-name'];
    obj.versions.base = formData.base;
    
    _.forEach(obj.versions.history, (index, version) => {
      
    });
    
    this.props.actions.createTemplate(obj);
  };

  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.templateDataNotValid), true);
    this.props.globalActions.addMessageToQueue(message);
    
    return false;
  };

  handleOnTagsContextChange = (data) => {
    
    const query = {
      layout: 'EBILL',
      type: 'TAG',
      context: (data || '').toLowerCase() === 'all' ? 'default' : (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);
    delete schema.standalone;
    schema.standalone = {};
    schema.standalone.sections = [];
    _.forEach(schema.containers, (container) => {
      const temp = container;
      if (temp.type === 'tabs') {
        temp.tabBarExtraContent = {};
        temp.tabBarExtraContent.sections = [];
        const basePane = _.cloneDeep(temp.panes[0]);
        temp.tabContent = {};
        temp.tabContent.sections = [];
        temp.panes = [];
        temp.panes.push(basePane);
      }
    });
    this.setState({ schema });
  };

  resetState = () => {
    this.setState({
      formData: {},
      tabCount: 1,
      currentTab: 1,
    });
  };

  resetSchema = () => {

  };

  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});
  };

  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;
  }


  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}, () => {
      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);
  }

  render() {
    const previewHeader = (<h3>{this.props.intl.formatMessage(messages.ebillPreview)}</h3>);
    const spinning = false;
    const schema = this.state.schema;
    return (
      <div className="ebill-container">
        <Helmet
          title="Ebill"
        />
        <Spin spinning={spinning}>
          {this.props.location.query.type !== 'embedded' && <Row>
            <Col span={24}>
              {this.props.location.query.type !== "embedded" &&
                <Breadcrumb>
                  <BreadcrumbItem>{this.props.intl.formatMessage(messages.campaigns)}</BreadcrumbItem>
                  <BreadcrumbItem>{this.props.intl.formatMessage(messages.creatives)}</BreadcrumbItem>
                  <BreadcrumbItem>{this.props.intl.formatMessage(messages.ebill)}</BreadcrumbItem>
                </Breadcrumb>
              }
            </Col>
          </Row>}
          <Row>
            <Col>
              <FormBuilder
                schema={schema}
                onSubmit={this.saveFormData}
                onChange={this.onFormDataChange}
                currentTab={this.state.currentTab}
                parent={this}
                formData={_.cloneDeep(this.state.formData)}
                location={this.props.location}
                tabKey={this.state.tabKey}
                tags={this.props.metaEntities && this.props.metaEntities.tags ? this.props.metaEntities.tags.standard : []}
                injectedTags={this.props.injectedTags ? this.props.injectedTags : {}}
                onFormValidityChange={this.setFormValidity}
                handleCancelModal={this.handleCancelModal}
                usingTabContainer
                checkValidation={this.state.checkValidation}
                onContextChange={this.handleOnTagsContextChange}
                tabCount={this.state.tabCount}
                // isNewVersionFlow
                modal={this.state.modalContent}
                showModal={this.state.showModal}
                isEdit={this.state.isEdit}
                iframeParent={parent}
                router={this.props.router}
                // baseLanguage={this.props.Global.currentOrgDetails.basic_details.base_language}
                // supportedLanguages={this.props.Global.currentOrgDetails.basic_details.supported_languages}
                // isSchemaChanged={this.state.isSchemaChanged}
              />
            </Col>
          </Row>
        </Spin>
        {/* <div style={{display: 'inline-block', verticalAlign: 'top', width: '100%', height: '450px', borderLeft: '1px solid #b7b7b7'}}>
          <div style={{width: "100%", height: '100%'}}>
            <textarea style={{background: '#efefef', resize: 'none', float: 'left', border: '1px solid #efefef', width: "100%", height: '100%'}} value={this.props.Templates.selectedEmailLayout}>
            </textarea>
          </div>
        </div> */}
        {this.state.formData[this.state.currentTab - 1] && <EmailPreview
          header={previewHeader}
          content={this.state.formData[this.state.currentTab - 1][`ebill-editor${this.state.currentTab > 1 ? this.state.currentTab : ''}`]}
          show={this.state.showEbillPreview}
          device={this.state.device}
          handleClose={this.toggleEmailPreview}
          changePreviewDevice={this.changePreviewDevice}
        />}
      </div>
    );
  }
}

Ebill.propTypes = {
  Ebill: PropTypes.object.isRequired,
  actions: PropTypes.object.isRequired,
  params: PropTypes.object,
  router: PropTypes.object,
  Templates: PropTypes.object,
  globalActions: PropTypes.object,
  location: PropTypes.object,
  intl: intlShape.isRequired,
  metaEntities: PropTypes.object,
  // Global: PropTypes.object,
  injectedTags: PropTypes.object,
};

const mapStateToProps = createStructuredSelector({
  Ebill: makeSelectEbill(),
  Templates: makeSelectTemplates(),
  metaEntities: makeSelectMetaEntities(),
  Global: makeSelectAuthenticated(),
  injectedTags: setInjectedTags(),
});

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

const withReducer = injectReducer({ key: 'ebill', reducer: v2EbillReducer });


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