/* eslint-disable no-restricted-syntax */
/* eslint-disable no-undef */
import React, { useState, useEffect } from 'react';
import { createStructuredSelector } from 'reselect';
import { bindActionCreators } from 'redux';
import { FormattedMessage } from 'react-intl';
import { get, cloneDeep, isEmpty, isObject } from 'lodash';
import styled from 'styled-components';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapColumn from '@capillarytech/cap-ui-library/CapColumn';
import CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapHeader from '@capillarytech/cap-ui-library/CapHeader';
import CapInput from '@capillarytech/cap-ui-library/CapInput';
import CapLabel from '@capillarytech/cap-ui-library/CapLabel';
import CapHeading from '@capillarytech/cap-ui-library/CapHeading';
import CapSpin from '@capillarytech/cap-ui-library/CapSpin';
import CapNotification from '@capillarytech/cap-ui-library/CapNotification';
import CapError from '@capillarytech/cap-ui-library/CapError';
import CapCheckbox from '@capillarytech/cap-ui-library/CapCheckbox';
import CapInfoNote from '@capillarytech/cap-ui-library/CapInfoNote';
import injectSaga from '../../../utils/injectSaga';
import injectReducer from '../../../utils/injectReducer';
import {
  CAP_SPACE_16,
  CAP_SPACE_12,
  CAP_SPACE_24,
  CAP_SPACE_32,
  CAP_SPACE_04,
  CAP_WHITE,
  CAP_G10,
} from '@capillarytech/cap-ui-library/styled/variables';
import { makeSelectTemplateDetailsResponse } from '../../Sms/Edit/selectors';
import { makeSelectMetaEntities, selectLiquidStateDetails, setInjectedTags } from '../../Cap/selectors';
import * as smsEditActions from '../../Sms/Edit/actions';
import * as globalActions from '../../Cap/actions';
import messages from './messages';
import TagList from '../../TagList';
import formBuilderMessages from '../../../v2Components/FormBuilder/messages';
import UnifiedPreview from '../../../v2Components/CommonTestAndPreview/UnifiedPreview';
import TestAndPreviewSlidebox from '../../../v2Components/TestAndPreviewSlidebox';
import withCreatives from '../../../hoc/withCreatives';
import {
  CHARLIMIT,
  SMS_TRAI_VAR,
  TAG,
  EMBEDDED,
  DEFAULT,
  FULL,
  ALL,
  LIBRARY,
} from './constants';
import { SMS } from '../../CreativesContainer/constants';
import v2EditSmsReducer from '../../Sms/Edit/reducer';
import { v2SmsEditSagas } from '../../Sms/Edit/sagas';
import ErrorInfoNote from '../../../v2Components/ErrorInfoNote';
import { validateLiquidTemplateContent } from '../../../utils/commonUtils';
import { validateTags } from '../../../utils/tagValidations';
import globalMessages from '../../Cap/messages';
import { ANDROID } from '../../../v2Components/CommonTestAndPreview/constants';

let varMap = {};
let traiData = {};
const { TextArea } = CapInput;
const { CapLabelInline } = CapLabel;

export const SmsTraiEdit = (props) => {
  const {
    intl,
    handleClose,
    params,
    actions,
    templateDetails,
    globalActions,
    location,
    getDefaultTags,
    supportedTags,
    metaEntities,
    injectedTags,
    onCreateComplete,
    isFullMode,
    getFormSubscriptionData,
    templateData = {},
    selectedOfferDetails,
    eventContextTags,
    waitEventContextTags,
    fetchingLiquidTags,
    getLiquidTags,
    showLiquidErrorInFooter,
  } = props || {};

  const { formatMessage } = intl;
  const [loading, updateLoading] = useState(true);
  const [tempMsgArray, updateTempMsgArray] = useState([]);
  const [updatedSmsEditor, setUpdatedSmsEditor] = useState([]);
  const [tags, updateTags] = useState([]);
  const [textAreaId, updateTextAreaId] = useState();
  const [isValidationError, updateIsValidationError] = useState(false);
  const [totalMessageLength, setTotalMessageLength] = useState(0);
  const [isUnicodeAllowed, updateIsUnicodeAllowed] = useState(true);
  const [showMsgLengthNote, updateshowMsgLengthNote] = useState(false);
  const [liquidErrorMessages, setLiquidErrorMessages] = useState({});
  const [isLiquidValidationError, setIsLiquidValidationError] = useState(false);
  /** After user closes the validation panel, keep it hidden until Save is clicked again (even if ErrorInfoNote remounts). */
  const [liquidErrorPanelDismissed, setLiquidErrorPanelDismissed] = useState(false);
  const [showTestAndPreviewSlidebox, setShowTestAndPreviewSlidebox] = useState(false);
  const SMSTraiFooter = styled.div`
    background-color: ${CAP_WHITE};
    padding: ${CAP_SPACE_32} ${CAP_SPACE_24};
    position: fixed;
    bottom: 2rem;
    margin-left: -2rem;
    /* Prevent global creatives tabpane min-height from stretching footer validation tabs */
    .error-info-note__tabs {
      .ant-tabs-tabpane {
        min-height: auto;
      }
    }
    .ant-btn {
      margin-right: ${CAP_SPACE_16};
    }
    }
`;
  const TraiEditTemplateDetails = styled.div`
    margin-bottom: ${CAP_SPACE_16};
    .cap-label-span {
      margin-right: ${CAP_SPACE_12};
    }
  `;

  useEffect(() => {
    //fetching tags
    const { type, module } = location.query || {};
    const isEmbedded = type === EMBEDDED;
    const query = {
      layout: SMS,
      type: TAG,
      context: isEmbedded ? module : DEFAULT,
      embedded: isEmbedded ? type : FULL,
    };
    if (getDefaultTags) {
      query.context = getDefaultTags;
    }
    globalActions.fetchSchemaForEntity(query);
    //fetching template data in fullmode
    const { id } = params || {};
    if (id) {
      actions.getTemplateDetails(id);
    }
    //cleanup code
    return () => {
      actions.resetEditTemplate();
      varMap = {};
    };
  }, []);

  //computing placeholder array for mapping values and rendering dynamic form
  useEffect(() => {
    traiData = isFullMode ? templateDetails : templateData;
    if (traiData && !isEmpty(traiData)) {
      let msg = get(traiData, `versions.base.sms-editor`, '');
      const templateMessageArray = [];
      //converting sms-editor string to an array split at '{#var#}'
      //split and push string before '{#var#}[0 to index]', push '{#var#}',
      //split and repeat for remaining string[index+7  to length]
      while (msg.length !== 0) {
        const index = msg.search(SMS_TRAI_VAR);
        if (index !== -1) {
          templateMessageArray.push(msg.substring(0, index));
          templateMessageArray.push(SMS_TRAI_VAR);
          msg = msg.substring(index + 7, msg.length);
        } else {
          templateMessageArray.push(msg);
          break;
        }
      }
      const filteredTemplateMessageArray = templateMessageArray.filter((i) => i === 0 || i);
      updateTempMsgArray(filteredTemplateMessageArray);
      //stop spinner
      updateLoading(false);
    }
  }, [templateDetails || templateData]);

  //compute/get varMapped and updated-sms-editor
  useEffect(() => {
    if (tempMsgArray.length !== 0) {
      const traiBase = traiData?.versions?.base || {};
      const {
        'var-mapped': varMapped = {},
        'updated-sms-editor': traiSmsEditor = '',
        'unicode-validity': unicodeValidity = true,
      } = traiBase;
      //if varMap and updated-sms-editor is already present on non first edits,use those values
      if (!isEmpty(varMapped)) {
        varMap = cloneDeep(varMapped);
        if (isFullMode) {
          setUpdatedSmsEditor(traiSmsEditor);
        } else {
          computeUpdatedSmsEditor();
        }
      } else {
        //computing and setting varMap for first edit
        let varCount = 1;
        let horizontalSpaceCount = 0;
        for (let i = 0; i < tempMsgArray.length; i += 1) {
          if (tempMsgArray[i] === SMS_TRAI_VAR) {
            const nextElem =
              tempMsgArray[i === tempMsgArray.length - 1 ? -1 : i + 1];
            if (nextElem?.replace(/[^\S\r\n]/gm, '') === '') {
              horizontalSpaceCount += 1;
            }
            if (tempMsgArray[i] !== nextElem && nextElem?.replace(/[^\S\r\n]/gm, '') !== '') {
              varMap[`${tempMsgArray[i]}_${(i - varCount - horizontalSpaceCount) + 1}`] = {
                data: '',
                count: varCount,
              };
              varCount = 1;
              horizontalSpaceCount = 0;
            } else {
              varCount += 1;
            }
          }
        }
        setUpdatedSmsEditor(tempMsgArray);
      }
      updateIsUnicodeAllowed(unicodeValidity);
      // calcaulate message length here
      calculateTotalMessageLength();
    }
  }, [tempMsgArray]);

  useEffect(() => {
    const previewCountElem = document.getElementsByClassName(
      'character-count-col',
    );
    if (previewCountElem.length === 1) {
      previewCountElem[0].style.visibility = 'hidden';
    }
  }, []);

  const computeUpdatedSmsEditor = () => {
    const arr = [...tempMsgArray];
    const varMapKeys = Object.keys(varMap)?.map((key) => Number(key.slice(8)))?.sort((a, b) => a - b) || [];
    for (const key in varMap) {
      if (varMap[key].data !== '') {
        const _id = Number(key.slice(8)); //Eg: -> extracting index 1 from keys like {#var# } _1
        const loopIndex =
          varMapKeys[varMapKeys?.indexOf(_id) + 1] || arr.length;
        for (let i = _id; i < loopIndex; i += 1) {
          if (i === _id) {
            arr[i] = varMap[key].data; //data for first #var# of the textbox
          } else if (arr[i] === SMS_TRAI_VAR) {
            arr[i] = ''; //'' for remaining #var# of a textbox
          }
        }
      }
    }
    setUpdatedSmsEditor(arr);
  };

  //Saving on done start
  const onUpdateTemplateComplete = (editResponse, errorMsg) => {
    if (editResponse?.templateId) {
      CapNotification.success({
        message: formatMessage(messages.smsEditNotification),
      });
      actions.clearEditResponse();
      onCreateComplete();
    } else if (errorMsg) {
      CapNotification.error({
        message: errorMsg,
      });
    }
  };

  const onSubmitWrapper = () => {
    setIsLiquidValidationError(false);
    setLiquidErrorMessages({});
    setLiquidErrorPanelDismissed(false);
    // Liquid validation (extractTags) only in library mode
    if (isFullMode) {
      onDoneCallback();
      return;
    }
    const content = updatedSmsEditor.join('');
    const syncValidation = validateTags({
      content,
      tagsParam: tags,
      location,
      isFullMode,
    });
    if (!syncValidation?.valid) {
      const standardErrors = [];
      if (syncValidation?.isBraceError) {
        standardErrors.push(formatMessage(globalMessages.unbalanacedCurlyBraces));
      }
      if (syncValidation?.missingTags?.length) {
        standardErrors.push(
          formatMessage(formBuilderMessages.missingTagsValidationError, {
            missingTags: syncValidation.missingTags.join(', '),
          })
        );
      }
      setLiquidErrorMessages({
        STANDARD_ERROR_MSG: standardErrors,
        LIQUID_ERROR_MSG: [],
      });
      setIsLiquidValidationError(true);
      return;
    }
    const onError = ({ standardErrors, liquidErrors }) => {
      setLiquidErrorMessages({
        STANDARD_ERROR_MSG: standardErrors,
        LIQUID_ERROR_MSG: liquidErrors,
      });
      setIsLiquidValidationError(true);
    };

    const onSuccess = () => {
      setIsLiquidValidationError(false);
      setLiquidErrorMessages({});
      onDoneCallback();
    };

    // When liquid is enabled and isFullMode is true, skip liquid validation and proceed directly
    if (isFullMode) {
      onSuccess();
      return;
    }

    validateLiquidTemplateContent(content, {
      getLiquidTags,
      formatMessage: intl.formatMessage,
      messages: formBuilderMessages,
      onError,
      onSuccess,
    });
  };

  const onDoneCallback = () => {
    if (updatedSmsEditor.includes(SMS_TRAI_VAR) && !isFullMode) {
      //during save textbox should not be empty
      updateIsValidationError(true);
    } else {
      //start spinner
      updateLoading(true);
      const traiVersions = traiData.versions || {};
      traiVersions.base = {
        ...traiVersions.base,
        'var-mapped': varMap,
        'updated-sms-editor': updatedSmsEditor,
        'unicode-validity': isUnicodeAllowed,
      };
      traiVersions.history = [traiVersions.base];
      if (isFullMode) {
        actions.editTemplate(traiData, onUpdateTemplateComplete);
      } else {
        getFormSubscriptionData({
          value: traiData.versions,
          _id: params && params.id,
          validity: true,
          type: SMS,
        });
      }
    }
  };
  //Saving on done end

  // tag code start
  useEffect(() => {
    let tag =
      metaEntities && metaEntities.tags ? metaEntities.tags.standard : [];
    const { type, module } = location.query || {};
    if (type === EMBEDDED && module === LIBRARY && !getDefaultTags) {
      tag = supportedTags;
    }
    updateTags(tag);
  }, [metaEntities]);

  const handleOnTagsContextChange = (data) => {
    const { type } = location.query || {};
    const isEmbedded = type === EMBEDDED;
    const query = {
      layout: SMS,
      type: TAG,
      context:
        (data || '').toLowerCase() === ALL
          ? DEFAULT
          : (data || '').toLowerCase(),
      embedded: isEmbedded ? type : FULL,
    };
    globalActions.fetchSchemaForEntity(query);
  };

  const onTagSelect = (data) => {
    if (textAreaId >= 0 && varMap && updatedSmsEditor) {
      const arr = [...updatedSmsEditor];
      const varMapKeys = Object.keys(varMap)?.map((key) => Number(key.slice(8)))?.sort((a, b) => a - b) || [];
      const loopIndex = varMapKeys[varMapKeys?.indexOf(textAreaId) + 1] || arr.length;
      //when trying to insert tag in empty textarea,{#var#} is replaced with "" and then tag is added
      for (let i = textAreaId; i < loopIndex; i += 1) {
        if (arr[i] === SMS_TRAI_VAR) {
          arr[i] = '';
        }
      }
      const messageData = `${arr[textAreaId]}{{${data}}}`;
      arr[textAreaId] = messageData;
      varMap[`${SMS_TRAI_VAR}_${textAreaId}`].data = messageData;
      setUpdatedSmsEditor(arr);
    }
  };
  //setting the id of currently selected text area, is used onTagSelect
  const setTextAreaId = (event) => {
    updateTextAreaId(Number(event.target.id));
  };
  // tag code end

  // on change event of Text Area
  const textAreaValueChange = ({ target: { value, id } }) => {
    const _id = Number(id);
    const arr = [...updatedSmsEditor];
    const varMapKeys = Object.keys(varMap)?.map((key) => Number(key.slice(8)))?.sort((a, b) => a - b) || [];
    const loopIndex = varMapKeys[varMapKeys?.indexOf(_id) + 1] || arr.length;

    //assign entered value to varMap
    varMap[`${SMS_TRAI_VAR}_${_id}`].data = value;
    //based on entered value update updatedSmsEditor
    if (value === '') {
      for (let i = _id; i < loopIndex; i += 1) {
        if (i === _id || arr[i] === '') {
          arr[i] = SMS_TRAI_VAR;
        }
      }
    } else {
      for (let i = _id; i < loopIndex; i += 1) {
        if (i === _id) {
          arr[i] = varMap[`${SMS_TRAI_VAR}_${_id}`].data;
        } else if (arr[i] === SMS_TRAI_VAR) {
          arr[i] = '';
        }
      }
    }
    setUpdatedSmsEditor(arr);
    calculateTotalMessageLength();
  };

  const textAreaValue = (idValue) => {
    if (idValue >= 0 && updatedSmsEditor) {
      if (
        updatedSmsEditor[idValue] &&
        updatedSmsEditor[idValue] !== SMS_TRAI_VAR
      ) {
        return updatedSmsEditor[idValue];
      }
      return '';
    }
    return '';
  };

  const capHeading = (index, varCount) => {
    if ((index, varCount)) {
      return (
        <CapHeading
          key={`label${index}`}
          type="h6"
          style={{ margin: `${CAP_SPACE_04} 0`, float: 'right' }}
        >
          {formatMessage(messages.textAreaCounts, {
            varCounts: varCount,
            var: SMS_TRAI_VAR,
            charCounts: varCount * CHARLIMIT,
          })}
        </CapHeading>
      );
    }
    return <></>;
  };

  const renderedContent = () => {
    const renderArray = [];
    if (tempMsgArray?.length !== 0) {
      let varCount = 0;
      tempMsgArray.forEach((elem, index) => {
        let prevElem = '';
        prevElem =
          tempMsgArray[[index === 0 ? -1 : index - 1]];
        if (elem.includes(SMS_TRAI_VAR)) {
          varCount += 1;
          if (prevElem !== SMS_TRAI_VAR && prevElem?.replace(/[^\S\r\n]/gm, '') !== '') {
            renderArray.push(
              <TextArea
                id={index}
                key={`${elem}${index}`}
                placeholder={props.intl.formatMessage(
                  messages.inputplaceHolderText,
                )}
                autosize={{ minRows: 1, maxRows: 3 }}
                onChange={textAreaValueChange}
                value={textAreaValue(index)}
                onFocus={setTextAreaId}
                errorMessage={
                  isValidationError &&
                  updatedSmsEditor[index] === SMS_TRAI_VAR &&
                  formatMessage(messages.textAreaError)
                }
              />,
            );
          }
          if (index === tempMsgArray.length - 1) {
            renderArray.push(capHeading(index, varCount));
            varCount = 0;
          }
        } else if (varCount > 0 && elem.replace(/[^\S\r\n]/gm, '') !== '') {
          renderArray.push(
            capHeading(index, varCount),
            <CapHeading
              key={`${elem}${index}`}
              style={{ margin: `${CAP_SPACE_16} 0`, clear: 'both' }}
            >
              {elem}
            </CapHeading>,
          );
          varCount = 0;
        } else if (elem.replace(/[^\S\r\n]/gm, '') !== '') {
          renderArray.push(
            <CapHeading
              key={`${elem}${index}`}
              style={{ margin: `${CAP_SPACE_16} 0` }}
            >
              {elem}
            </CapHeading>,
          );
        }
      });
    }
    return renderArray;
  };

  const smsLengthForVar = () => (
    <CapHeading type="h5" style={{ marginTop: CAP_SPACE_04, float: 'right' }}>
      {formatMessage(messages.totalCharacters, {
        smsCount: Math.ceil(totalMessageLength / 160),
        number: totalMessageLength,
      })}
    </CapHeading>
  );

  // to compute the length of the message
  //40 characters is blocked per'{#var#}' if textbox is empty otherwise it will be textbox length
  // and the remaining string length is added to it
  const calculateTotalMessageLength = () => {
    const msgLenWithoutVar = tempMsgArray
      ?.filter((i) => i !== SMS_TRAI_VAR)
      .join('');
    const varLen = calculateLenForTextBox();
    const totalMsgLen = msgLenWithoutVar?.length + varLen;
    setTotalMessageLength(totalMsgLen);
  };

  const calculateLenForTextBox = () => {
    let countVarChar = 0;
    Object.keys(varMap).forEach((i) => {
      if (varMap[i].data) {
        countVarChar += varMap[i].data?.length;
        if (!showMsgLengthNote && varMap[i].data?.length > varMap[i].count * CHARLIMIT) {
          updateshowMsgLengthNote(true);
        }
      } else {
        countVarChar += varMap[i].count * CHARLIMIT;
      }
    });
    return countVarChar;
  };

  const disablehandler = () => {
    if (traiData && !isEmpty(traiData)) {
      const msg = get(traiData, `versions.base.sms-editor`, '');
      const index = msg.search(SMS_TRAI_VAR);
      if (index === -1) {
        return true;
      }
      return false;
    }
    return true;
  };

  const unicodeHandler = ({ target: { checked } }) => {
    updateIsUnicodeAllowed(checked);
  };

  // Get template content for test and preview
  const getTemplateContent = () => {
    if (!updatedSmsEditor || updatedSmsEditor.length === 0) {
      return '';
    }
    return updatedSmsEditor.join('');
  };

  // Build formData for TestAndPreviewSlidebox - templateConfigs with templateId and template for DLT test
  const getFormDataForTestAndPreview = () => {
    const smsBase = get(traiData, 'versions.base') || get(templateDetails, 'versions.base') || get(templateData, 'versions.base');
    if (!smsBase || !smsBase.template_id) {
      return {};
    }
    const templateRaw = smsBase['updated-sms-editor'] || smsBase['sms-editor'] || '';
    const template = Array.isArray(templateRaw) ? templateRaw.join('') : templateRaw;
    return {
      templateConfigs: {
        templateId: smsBase.template_id, template, traiDltEnabled: true, registeredSenderIds: get(traiData, `versions.base.header`, []),
      },
    };
  };

  // Handle test and preview button click
  const handleTestAndPreview = () => {
    setShowTestAndPreviewSlidebox(true);
  };

  // Handle close test and preview slidebox
  const handleCloseTestAndPreview = () => {
    setShowTestAndPreviewSlidebox(false);
  };

  return (
    <>
      <CapSpin spinning={loading || fetchingLiquidTags} tip={fetchingLiquidTags && formatMessage(formBuilderMessages.liquidSpinText)}>
        <CapRow typeof='flex' align='top' noWrap fullWidth>
          <CapRow type='flex' vertical fullWidth>
            {traiData && !isEmpty(traiData) && (
              <TraiEditTemplateDetails>
                <CapLabelInline type="label1">
                  {formatMessage(messages.templateLabel)}
                </CapLabelInline>
                <CapLabelInline type="label2">
                  {get(traiData, `versions.base.template_name`, '')}
                </CapLabelInline>

                <CapLabelInline type="label1">
                  {formatMessage(messages.traiEditSeperator)}
                </CapLabelInline>

                <CapLabelInline type="label1">
                  {formatMessage(messages.senderIdlabel)}
                </CapLabelInline>
                <CapLabelInline type="label2">
                  {[...get(traiData, `versions.base.header`, [])].join(', ')}
                </CapLabelInline>
              </TraiEditTemplateDetails>
            )}
            <CapColumn span={24}>
              <CapRow useLegacy>
                <CapHeader
                  title={formatMessage(messages.traiEditTitle)}
                  size="regular"
                  suffix={(
                    <TagList
                      label={formatMessage(messages.addLabels)}
                      onTagSelect={onTagSelect}
                      location={location}
                      tags={tags || []}
                      onContextChange={handleOnTagsContextChange}
                      injectedTags={injectedTags || {}}
                      hidePopover={disablehandler()}
                      selectedOfferDetails={selectedOfferDetails}
                      eventContextTags={eventContextTags}
                      waitEventContextTags={waitEventContextTags}
                    />
                  )}
                />
              </CapRow>

              <CapRow
                useLegacy
                style={{
                  backgroundColor: CAP_G10,
                  padding: CAP_SPACE_16,
                }}
              >
                {renderedContent()}
              </CapRow>
              <CapRow useLegacy>
                {smsLengthForVar()}
              </CapRow>
              <CapCheckbox onChange={unicodeHandler} checked={isUnicodeAllowed} disabled={disablehandler()} style={{ marginTop: '1rem' }}>
                {formatMessage(messages.unicodeLabel)}
              </CapCheckbox>
              {showMsgLengthNote && <CapInfoNote message={<FormattedMessage {...messages.msgLengthNote} values={{ var: '{#var#}' }} />} />}
              <div style={{ marginBottom: '100px' }} />
            </CapColumn>
          </CapRow>
          <CapColumn span={8} offset={1}>
            <UnifiedPreview
              channel={SMS}
              content={updatedSmsEditor.join('')}
              device={ANDROID}
              showDeviceToggle={false}
              showHeader={false}
              formatMessage={formatMessage}
              senderId={isUnicodeAllowed ? 'Unicode' : 'ASCII'}
            />
          </CapColumn>
        </CapRow>
        <SMSTraiFooter>
          {isLiquidValidationError && !liquidErrorPanelDismissed && (
            <ErrorInfoNote
              errorMessages={liquidErrorMessages}
              intl={intl}
              onClose={() => {
                setLiquidErrorPanelDismissed(true);
                if (typeof showLiquidErrorInFooter === 'function') {
                  showLiquidErrorInFooter({
                    STANDARD_ERROR_MSG: [],
                    LIQUID_ERROR_MSG: [],
                  });
                }
              }}
            />
          )}
          <CapButton
            onClick={handleTestAndPreview}
            type="secondary"
            className="create-msg create-dlt-msg"
          >
            <FormattedMessage {...messages.testAndPreviewButtonLabel} />
          </CapButton>
          <CapButton
            onClick={onSubmitWrapper}
            className="create-msg"
          >
            <FormattedMessage {...messages.saveButtonLabel} />
          </CapButton>
        </SMSTraiFooter>
        <TestAndPreviewSlidebox
          show={showTestAndPreviewSlidebox}
          onClose={handleCloseTestAndPreview}
          formData={getFormDataForTestAndPreview()}
          content={getTemplateContent()}
          currentChannel={SMS}
        />
      </CapSpin>
    </>
  );
};

const mapStateToProps = createStructuredSelector({
  templateDetails: makeSelectTemplateDetailsResponse(),
  metaEntities: makeSelectMetaEntities(),
  injectedTags: setInjectedTags(),
  fetchingLiquidTags: selectLiquidStateDetails(),
});

const mapDispatchToProps = (dispatch) => ({
  actions: bindActionCreators(smsEditActions, dispatch),
  globalActions: bindActionCreators(globalActions, dispatch),
});

const withSaga = injectSaga({ key: 'edit', saga: v2SmsEditSagas });
const withReducer = injectReducer({ key: 'edit', reducer: v2EditSmsReducer });

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