import React, { useState, useEffect } from 'react';
import { bindActionCreators } from 'redux';
import { injectIntl, intlShape, FormattedMessage  } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import style from './style';
import withStyles from '../../../hoc/withStyles';
import './_lineCreate.scss';

import CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapNotification from '@capillarytech/cap-ui-library/CapNotification';
import CapSpin from '@capillarytech/cap-ui-library/CapSpin';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapColumn from '@capillarytech/cap-ui-library/CapColumn';
import CapRadioCard from '@capillarytech/cap-ui-library/CapRadioCard';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
import CapHeader from '@capillarytech/cap-ui-library/CapHeader';
// GA
import { GA } from '@capillarytech/cap-ui-utils';
import { CREATE, EDIT, TRACK_CREATE_LINE, TRACK_EDIT_LINE } from '../../App/constants';

import LineWrapper from './Wrapper';
import messages from './messages';
import { TEXT, IMAGE, IMAGE_MAP, IMAGE_CAROUSEL, MAX_LINE_WRAPPER_LIMIT, MAX_LINE_WRAPPER_LIMIT_FULL_MODE, DEFAULT_VIDEO_URI, VIDEO, TEMPLATE  } from './constants';
import { FONT_COLOR_05 } from '@capillarytech/cap-ui-library/styled/variables';

import { makeSelectMetaEntities, setInjectedTags } from '../../Cap/selectors';
import { makeSelectTemplates } from '../../Templates/selectors';
import TemplatePreview from '../../../v2Components/TemplatePreview';
import {makeSelectCreateLine, makeSelectLine } from './selectors';
import * as compActions from './actions';
import * as templateActionsConfig from '../../Templates/actions';
import withCreatives from '../../../hoc/withCreatives';
import { gtmPush } from '../../../utils/gtmTrackers';
import { LINE } from '../../CreativesContainer/constants';
import * as commonUtil from '../../../utils/common';

const { stopTimer } = GA.timeTracker;

export const LineContainer = ({
    isFullMode,
    globalActions,
    metaEntities,
    injectedTags = {},
    getDefaultTags,
    location,
    supportedTags,
    actions,
    Line,
    className,
    params,
    onCreateComplete,
    intl: { formatMessage },
    getFormSubscriptionData,
    templateData,
    lineData,
    isCreateFlow,
    templateActions,
    Templates,
    createNew,
    onShowTemplates,
    handleClose,
    selectedOfferDetails
}) => {
    const paramObj = params || {};
    const initialWrapperContent = [{ type: TEXT, isError: true, isInit: true }];
    const [lineWrapperContents, updateLineWrapperContent] = useState(initialWrapperContent);
    const [isEditFlow, checkEditFlow] = useState(false);
    const [isEditLoading, updateEditLoading] = useState(false);
    const [accountSelectFlow, updateAccountSelectFlow] = useState(false);
    const [uploadedAssetList, updateUploadedAssetList] = useState({});
    const [selectedAccount, updateSelectedAccount] = useState('');

    const hasJPLocaleHideFeatureEnabled = commonUtil?.hasJPLocaleHideFeatureEnabled();

    useEffect(() => {
        if  (!isFullMode) {
            templateActions.getWeCrmAccounts('Line');
            updateAccountSelectFlow(true);
            const queryParams = {"sortBy":"Most Recent","page":1,"perPage":25};
            templateActions.getAllTemplates('Line', queryParams);
        }
        return () => actions.clearAsset();
    }, []);

    const onAccountSelect = (account) => {
        const { value } = account.target;
        templateActions.setChannelAccount(LINE, Templates.weCrmAccounts.find((item) => item.name === value));
        updateSelectedAccount(value);
        updateAccountSelectFlow(false);
        createNew();
    }

    useEffect(() => {
        const { id } = paramObj;
        if (id) {
            updateEditLoading(true);
            actions.getTemplateDetails(id, updateEditLoading);
            checkEditFlow(true);
        }
    }, [paramObj.id]);

    useEffect(() => {
        if (params && params.id) {
            const type = get(Line, 'templateDetails.mode');
            const messageContent = get(Line, `templateDetails.versions.base.content.messages.0.text`);
            const originalContentUrl = get(Line, `templateDetails.versions.base.content.messages.0.originalContentUrl`);
            const previewImageUrl = get(Line, `templateDetails.versions.base.content.messages.0.previewImageUrl`);
            const stickerUrl = get(Line, `templateDetails.versions.base.content.messages.0.stickerUrl`);
            const animatedStickerUrl = get(Line, `templateDetails.versions.base.content.messages.0.animatedStickerUrl`);
            const stickerId = get(Line, `templateDetails.versions.base.content.messages.0.stickerId`);
            const packageId = get(Line, `templateDetails.versions.base.content.messages.0.packageId`);
            const messageTitle = get(Line, 'templateDetails.name');
            const baseUrl = get(Line, `templateDetails.versions.base.content.messages.0.baseUrl`);
            const baseSize = get(Line, `templateDetails.versions.base.content.messages.0.baseSize`);
            const altText = get(Line, `templateDetails.versions.base.content.messages.0.altText`);
            const selectedTemplate = get(Line, 'templateDetails.selectedTemplate');
            const assetType = get(Line, 'templateDetails.assetType');
            const actionLinks = get(Line, 'templateDetails.actionLinks');
            const templateType = get(Line, `templateDetails.versions.base.content.messages.0.type`);
            let template = "";
            if (templateType === "flex") {
                template = get(Line, `templateDetails.versions.base.content.messages.0.contents`);         
            } else {
                template = get(Line, `templateDetails.versions.base.content.messages.0.template`);
              }
            const video = get(Line, `templateDetails.versions.base.content.messages.0.video`);
            const videoName = get(Line, `templateDetails.versions.base.content.messages.0.videoName`);
            const videoDuration = get(Line, `templateDetails.versions.base.content.messages.0.videoDuration`);
            const lineContent = {
                type,
                messageContent,
                originalContentUrl,
                previewImageUrl,
                messageTitle,
                selectedSticker: {
                    stickerUrl,
                    animatedStickerUrl,
                    stickerId: `${stickerId}`,
                    packageId: `${packageId}`,
                },
                selectedTemplate,
                assetType,
                baseUrl,
                actionLinks,
                baseSize,
                template,
                altText,
                video,
                videoName,
                videoDuration,
            };
            updateLineWrapperContent([lineContent]);
        }
    }, [Line?.templateDetails]);

    useEffect(() => {
        if (templateData && templateData.versions) {
            const lineMessages = get(templateData, 'versions.base.content.messages', [{}]);
            const lineContent = [];
            lineMessages.forEach(({
                type = 'text',
                text,
                originalContentUrl,
                previewImageUrl,
                stickerUrl,
                animatedStickerUrl,
                selectedSticker,
                stickerId,
                packageId,
                baseUrl,
                baseSize,
                actionLinks,
                assetType,
                selectedTemplate,
                template,
                contents,
                altText,
                video,
                videoName,
                videoDuration,
            }) => {
                const obj = {
                    type,
                    messageContent: text,
                    originalContentUrl,
                    previewImageUrl,
                    selectedSticker,
                    baseUrl,
                    baseSize,
                    actionLinks,
                    assetType,
                    selectedTemplate,
                    template,
                    contents,
                    altText,
                    video,
                    videoName,
                    videoDuration,
                };
                if (stickerUrl) {
                    obj.selectedSticker = {
                        stickerUrl,
                        animatedStickerUrl,
                        stickerId: `${stickerId}`,
                        packageId: `${packageId}`,
                    };
                }
                if (video) {
                    obj.type = 'video';
                }
                lineContent.push(obj);
            });
            updateLineWrapperContent(lineContent);

        }
    }, [templateData]);

    const deleteUploadedImgList = (selectedIndex) => {
        const newUploadedAssetList = { ...uploadedAssetList };
        delete newUploadedAssetList[selectedIndex];
        updateUploadedAssetList(newUploadedAssetList);
    }

    const addLineWrappers = () => {
        updateLineWrapperContent([...lineWrapperContents, ...initialWrapperContent])
    }

    const deleteWrapper = index => {
        const selectedIndex = lineWrapperContents.findIndex((el, i) => i === index);
        if (selectedIndex > -1) {
            // change uploaded img sequence
            const newUploadedAssetList = { ...uploadedAssetList };
            delete newUploadedAssetList[index];
            updateUploadedAssetList(newUploadedAssetList);

            const newLineWrapperContents = [...lineWrapperContents];
            newLineWrapperContents.splice(selectedIndex, 1);
            updateLineWrapperContent(newLineWrapperContents);
        }
    }

    const shiftUp = index => {
        const selectedIndex = lineWrapperContents.findIndex((el, i) => i === index);
        const selectedElement = lineWrapperContents.find((el, i) => i === index);
        if (selectedIndex > -1) {
            // change uploaded img sequence
            const newUploadedAssetList = { ...uploadedAssetList };
            const selectedUploadedAsset = uploadedAssetList[index];
            const newPositionUploadedAsset = uploadedAssetList[index - 1];
            newUploadedAssetList[index - 1] = selectedUploadedAsset;
            newUploadedAssetList[index] = newPositionUploadedAsset;
            updateUploadedAssetList(newUploadedAssetList);

            const newLineWrapperContents = [...lineWrapperContents];
            newLineWrapperContents.splice(selectedIndex, 1);
            newLineWrapperContents.splice(selectedIndex - 1, 0, selectedElement);
            updateLineWrapperContent(newLineWrapperContents);
        }
    }

    const shiftDown = index => {
        const selectedIndex = lineWrapperContents.findIndex((el, i) => i === index);
        const selectedElement = lineWrapperContents.find((el, i) => i === index);
        if (selectedIndex > -1) {
            // change uploaded img sequence
            const newUploadedAssetList = { ...uploadedAssetList };
            const selectedUploadedAsset = uploadedAssetList[index];
            const newPositionUploadedAsset = uploadedAssetList[index + 1];
            newUploadedAssetList[index + 1] = selectedUploadedAsset;
            newUploadedAssetList[index] = newPositionUploadedAsset;
            updateUploadedAssetList(newUploadedAssetList);

            const newLineWrapperContents = [...lineWrapperContents];
            newLineWrapperContents.splice(selectedIndex, 1);
            newLineWrapperContents.splice(selectedIndex + 1, 0, selectedElement);
            updateLineWrapperContent(newLineWrapperContents);
        }
    }

    const updateMessageState = (obj) => {
        const { index: selectedIndex, ...rest } = obj;
        const newLineWrapperContents = [...lineWrapperContents];
        newLineWrapperContents.splice(selectedIndex, 1, rest);
        updateLineWrapperContent(newLineWrapperContents);
    }

    const isDoneDisabled = () => {
        if (!lineWrapperContents.length) {
            return true;
        }
        let isDisabled = false;
        lineWrapperContents.forEach(({isError}) => {
            isDisabled = isDisabled || isError;
        });
        return isDisabled;
    }

    const getLineWrappers = () => {
        return lineWrapperContents.map((lineWrapperContent, index) => {
            let tags =
            metaEntities && metaEntities.tags
                ? metaEntities.tags.standard
                : [];
            if (supportedTags) {
                tags = supportedTags;
            }
            return (
                <LineWrapper
                    id={`${lineWrapperContent.type}__${index}`}
                    globalActions={globalActions}
                    tags={tags}
                    injectedTags={injectedTags}
                    getDefaultTags={getDefaultTags}
                    isFullMode={isFullMode}
                    location={location}
                    actions={actions}
                    Line={Line}
                    index={index}
                    deleteWrapper={deleteWrapper}
                    updateMessageState={updateMessageState}
                    content={lineWrapperContent}
                    selectedType={lineWrapperContent.type}
                    shiftUp={shiftUp}
                    shiftDown={shiftDown}
                    lineWrappers={lineWrapperContents.length}
                    Templates={Templates}
                    getAllTemplates={templateActions.getAllTemplates}
                    uploadedAssetList={uploadedAssetList}
                    deleteUploadedImgList={deleteUploadedImgList}
                    updateUploadedAssetList={updateUploadedAssetList}
                    selectedOfferDetails={selectedOfferDetails}
                />
            );
        });
    }

    const createCallback = (errorMessage) => {
        if (!errorMessage) {
            CapNotification.success({
                message: formatMessage(messages.lineCreateNotification),
            });
            actions.clearEditResponse();
        } else {
            CapNotification.error({
                message: errorMessage,
            });
        }
    }

    const editCallback = (errorMessage) => {
        if (!errorMessage) {
            CapNotification.success({
                message: formatMessage(messages.lineEditNotification),
            });
            actions.clearEditResponse();
        } else {
            CapNotification.error({
                message: errorMessage,
            });
        }
    }

    const formatFSPayload = (lineWrapperContents) => {
        const [ {
            messageTitle,
            messageContent: content,
            type,
        } = {}] = lineWrapperContents;
        return {
            name: messageTitle,
            content,
            imageAdded: [IMAGE, IMAGE_MAP, IMAGE_CAROUSEL, TEMPLATE].includes(type),
            videoAdded: type === VIDEO
        }
    }
    const formatSubmitPayload = (lineWrapperContents) => {
        const [ {
            messageTitle,
            messageContent,
            type,
            messageType,
            previewImageUrl,
            originalContentUrl,
            selectedSticker,
            baseUrl,
            baseSize,
            selectedTemplate,
            assetType,
            actionLinks,
            template,
            altText,
            videoSrc,
            videoName,
            actionLabel,
            actionUrl,
            videoHeight,
            videoWidth,
        } = {}] = lineWrapperContents;
        let messageData = { type };
        //for type template and not flow
        if (messageType && messageContent) messageData[messageType] = messageContent;
        if (previewImageUrl) {
            messageData.previewImageUrl = previewImageUrl;
        }
        if (originalContentUrl) {
            messageData.originalContentUrl = originalContentUrl;
        }
        if (selectedSticker) {
            messageData.stickerUrl = selectedSticker.stickerUrl;
            messageData.animatedStickerUrl = selectedSticker.animatedStickerUrl;
            messageData.packageId = `${selectedSticker.packageId}`;
            messageData.stickerId = `${selectedSticker.stickerId}`;
        }
        if (baseUrl) {
            messageData.baseUrl = baseUrl;
            messageData.altText = altText;
        }
        if (baseSize) {
            messageData.baseSize = baseSize;
        }

        if (template) {
            messageData.type = "flex";
            messageData.altText = altText;
            messageData.contents = {};
            const imageContents = (template?.columns || []).map((item) => {
                return {
                type: 'bubble',
                hero: {
                    type: 'image',
                    url: item.imageUrl,
                    size: 'full',
                    aspectRatio: item.aspectRatio,
                    aspectMode: 'cover',
                },
                footer: {
                    type: 'box',
                    layout: 'vertical',
                    spacing: 'xs',
                    contents: [{
                        type: 'button',
                        style: 'link',
                        height: 'sm',
                        action: item.action,
                    }],
                },
            };
        });
        messageData.contents.contents = imageContents;
        messageData.contents.type = "carousel";
        }
        if (videoSrc) {
            delete messageData.previewImageUrl;
            messageData.type = 'imagemap';
            messageData.altText = altText;
            messageData.baseSize = {
                height: videoHeight,
                width: videoWidth,
            };
            messageData.actions = [{
                type: 'uri',
                linkUri: actionUrl || DEFAULT_VIDEO_URI,
                area: {
                    height: 1,
                    width: 1,
                    x: 0,
                    y: 0,
                },
            }];
            messageData.baseUrl = previewImageUrl.replace('/1040', '');
            messageData.video = {
                area: {
                    x: 0,
                    y: 0,
                    height: videoHeight,
                    width: videoWidth,
                },
                originalContentUrl: videoSrc,
                previewImageUrl,
            };
            if (actionLabel) {
                messageData.video.externalLink = {
                    label: actionLabel,
                    linkUri: actionUrl,
                };
            }
            messageData.videoName = videoName;
        }
        return {
            versions: {
                    base: {
                    content: {
                        to: "{{line_id}}",
                        messages: [messageData]
                    }
                }
            },
            type: "LINE",
            name: messageTitle,
            definition: {
                "mode": type,
                selectedTemplate,
                actionLinks,
                assetType
            }
        };
    }

    const formatNonStandalonePayload = (lineWrapperContents) => {
        const lineContents = lineWrapperContents.map(({
            messageContent,
            type,
            messageType,
            previewImageUrl,
            originalContentUrl,
            selectedSticker,
            baseUrl,
            baseSize,
            selectedTemplate,
            assetType,
            actionLinks,
            template,
            altText,
            videoSrc,
            videoName,
            actionLabel,
            actionUrl,
            videoHeight,
            videoWidth,
        }) => {
            let messageData = { type };
            messageData[messageType] = messageContent;
            if (previewImageUrl) {
                messageData.previewImageUrl = previewImageUrl;
            }
            if (originalContentUrl) {
                messageData.originalContentUrl = originalContentUrl;
            }
            if (selectedSticker) {
                messageData.stickerUrl = selectedSticker.stickerUrl;
                messageData.animatedStickerUrl = selectedSticker.animatedStickerUrl;
                messageData.stickerId = `${selectedSticker.stickerId}`;
                messageData.packageId = `${selectedSticker.packageId}`;
            }
            if (baseUrl) {
                messageData.baseUrl = baseUrl;
                messageData.altText = altText;
                messageData.baseSize = baseSize;
                messageData.selectedTemplate = selectedTemplate;
                messageData.assetType = assetType;
                messageData.actionLinks = actionLinks;
            }
            if (template) {
                let contentsLocal = {};
                    const imageContents = (template?.columns || []).map((item) => {
                        return {
                        type: 'bubble',
                        hero: {
                            type: 'image',
                            url: item.imageUrl,
                            size: 'full',
                            aspectRatio: item.aspectRatio,
                            aspectMode: 'cover',
                        },
                        footer: {
                            type: 'box',
                            layout: 'vertical',
                            spacing: 'xs',
                            contents: [{
                                type: 'button',
                                style: 'link',
                                height: 'sm',
                                action: item.action,
                            }],
                        },
                    };
                });
                contentsLocal.contents = imageContents;
                contentsLocal.type = "carousel";
                messageData.contents = contentsLocal;
                messageData.altText = altText;
            }
            if (videoSrc) {
                delete messageData.previewImageUrl;
                messageData.type = 'imagemap';
                messageData.altText = altText;
                messageData.baseSize = {
                    height: videoHeight,
                    width: videoWidth,
                };
                messageData.actions = [{
                    type: 'uri',
                    linkUri: actionUrl || DEFAULT_VIDEO_URI,
                    area: {
                        height: 1,
                        width: 1,
                        x: 0,
                        y: 0,
                    },
                }];
                messageData.baseUrl = previewImageUrl.replace('/1040', '');
                messageData.video = {
                    area: {
                        x: 0,
                        y: 0,
                        height: videoHeight,
                        width: videoWidth,
                    },
                    originalContentUrl: videoSrc,
                    previewImageUrl,
                };
                if (actionLabel) {
                    messageData.video.externalLink = {
                        label: actionLabel,
                        linkUri: actionUrl,
                    };
                }
                messageData.videoName = videoName;
            }
            return messageData;
        });
        return ({
            versions: {
                base: {
                    content: {
                        messages: lineContents,
                        to: "{{line_id}}",
                    },
                },
            },
        });
    }

    const getLineType = lineWrapperContents => get(lineWrapperContents, '0.type', TEXT);

    const onCreateLine = () => {
        actions.createTemplate(
            formatSubmitPayload(lineWrapperContents),
            (resp, errorMessage) => {
              createCallback(errorMessage);
              if (!errorMessage) {
                // stop timer for create line
                const timeTaken = stopTimer(TRACK_CREATE_LINE, {
                    category: 'Creatives',
                    action: TRACK_CREATE_LINE,
                    label: getLineType(lineWrapperContents),
                });
                gtmPush('creativeDetails', Object.assign({
                    id: resp.templateId,
                    channel: LINE,
                    mode: CREATE,
                    timeTaken,
                }, formatFSPayload(lineWrapperContents)));
                onCreateComplete();
              }
            }
        );
    }

    const getPreviewSection = () => {
        const accountName = get(lineData, 'selectedLineAccount.name', '');
        const templateContent = lineWrapperContents.map(({ messageContent, type, previewImageUrl, selectedSticker, baseUrl, template, videoSrc, actionUrl }) => {
        //template.type is image_carousel, for flex only contents will be there
        const isNewLineFormat = template && isEmpty(template.columns) && !isEmpty(template.contents);
        let imageCarousel = [];
        if (isNewLineFormat) {
            imageCarousel = get(template, 'contents', [{}]).map(({
                hero: { url = ''} = {},
                footer: { contents: [{ action: { label = '' } = {} }] = [{}] } = {},
            }) => ({
                imageUrl: url,
                actionLabel: label,
            }));
        } else {
            imageCarousel = get(template, 'columns', [{}]).map(({ imageUrl, action: { label: actionLabel } = {} }) => ({ imageUrl, actionLabel }) );
        }
        return {
            messageContent,
            previewImageUrl,
            selectedSticker,
            type,
            baseUrl,
            video: videoSrc,
            actionUrl,
            imageCarousel,
        };
        });
        return (
            <TemplatePreview
                channel="LINE"
                content={templateContent}
                LineAccountName={accountName[0]}
                hasJPLocaleHideFeatureEnabled={hasJPLocaleHideFeatureEnabled}
            />
        )
    }

    const onEditLine = () => {
        actions.editTemplate(
            {
                ...formatSubmitPayload(lineWrapperContents),
                _id: params.id,
            },
            (resp, errorMessage) => {
                editCallback(errorMessage);
                if (!errorMessage) {
                    // stop timer for edit line
                    const timeTaken = stopTimer(TRACK_EDIT_LINE, {
                        category: 'Creatives',
                        action: TRACK_EDIT_LINE,
                        label: getLineType(lineWrapperContents),
                    });
                    gtmPush('creativeDetails', Object.assign({
                        id: resp.templateId._id,
                        channel: LINE,
                        mode: EDIT,
                        timeTaken,
                    }, formatFSPayload(lineWrapperContents)));
                   
                    onCreateComplete();
                }
          });
    }

    const onDoneCallback = () => {
        if (isFullMode) {
            if (isEditFlow) {
                return onEditLine;
            }
            return onCreateLine;
        }
        return () => getFormSubscriptionData({
            value: formatNonStandalonePayload(lineWrapperContents),
            _id: params && params.id,
            validity: true,
            type: 'LINE',
        });
    }

    const isLoading = isEditLoading;

    if (isCreateFlow && !isFullMode && accountSelectFlow) {
        const {
            weCrmAccounts,
            fetchingWeCrmAccounts,
        } = Templates;
        if (isEmpty(weCrmAccounts) && !fetchingWeCrmAccounts) {
            return <FormattedMessage {...messages.noAccountsPresentLine} />;
        }
        const accountOptions = (weCrmAccounts || [{}]).map(({
            name = '',
            uuid,
        }) => ({
            key: uuid,
            value: name,
            title: name,
            icon: <CapIcon.CapIconAvatar text={name[0]} width="auto" height="2rem"/>,
        }));
        const accountHeader = formatMessage(messages.lineAccount);
        return (
            <CapSpin spinning={fetchingWeCrmAccounts}>
                <CapHeader
                    title={accountHeader}
                    description={formatMessage(messages.chooseAccount)}
                    size="regular"
                    className="select-account-header"
                />
                <CapRadioCard
                    className="select-account"
                    onChange={onAccountSelect}
                    panes={accountOptions}
                    cardHeight="48px"
                    cardWidth="276px"
                    size="small"
                    defaultValue={selectedAccount}
                    selected={selectedAccount}
                />
            </CapSpin>
        )
    }

    const getAccountSection = () => {
        const accountName = get(lineData, 'selectedLineAccount.name', '');
        if (createNew && !isFullMode) {
            return (
                <>
                    <span>{accountName}</span>
                    <CapButton
                        onClick={onShowTemplates}
                        type="link"
                        style={{ fontWeight: 500, color: FONT_COLOR_05 }}
                    >
                        <FormattedMessage {...messages.changeAccount} />
                    </CapButton>
                </>
            )
        }
        return null;
    }

    return (
        <div className={className}>
            <CapSpin spinning={isLoading}>
                <CapRow>
                    <CapColumn span={14} style={{ zIndex: 1 }}>
                        <CapHeader
                            title={formatMessage(messages.lineAccountLabel)}
                            size="regular"
                        />
                        {getAccountSection()}
                        <CapHeader
                            title={formatMessage(messages.lineCreativeTitle)}
                            description={formatMessage(messages.lineCreativeDescription)}
                        />
                        {getLineWrappers()}
                        {
                            !isFullMode
                            ? (
                            <CapButton
                                onClick={addLineWrappers}
                                disabled={lineWrapperContents.length === (isFullMode ? MAX_LINE_WRAPPER_LIMIT_FULL_MODE : MAX_LINE_WRAPPER_LIMIT)}
                                type="flat"
                                isAddBtn
                                className="add-msg"
                            >
                                <FormattedMessage {...messages.addMessageButtonLabel} />
                            </CapButton>
                            )
                            : null
                        }
                    </CapColumn>
                    <CapColumn span={6}>
                        <CapRow>
                            <CapColumn span={23} offset={6}>
                                {getPreviewSection()}
                            </CapColumn>
                        </CapRow>
                    </CapColumn>
                </CapRow>
                <div className="action-section">
                    <CapButton
                        onClick={onDoneCallback()}
                        disabled={isDoneDisabled()}
                        className="create-msg"
                    >
                        <FormattedMessage {...messages.doneButtonLabel} />
                    </CapButton>
                    {
                        !isFullMode
                        ? (
                            <CapButton
                                onClick={handleClose}
                                className="cancel-msg"
                                type="secondary"
                            >
                                <FormattedMessage {...messages.cancelButtonLabel} />
                            </CapButton>
                        )
                        : null
                    }
                </div>
            </CapSpin>
        </div>
    )
}

const mapStateToProps = createStructuredSelector({
  Line: makeSelectCreateLine(),
  lineData: makeSelectLine(),
  Templates: makeSelectTemplates(),
  metaEntities: makeSelectMetaEntities(),
  injectedTags: setInjectedTags(),
});

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(compActions, dispatch),
    templateActions: bindActionCreators(templateActionsConfig, dispatch),
  };
}

export default withCreatives({
  WrappedComponent: injectIntl(withStyles(LineContainer, style)),
  mapStateToProps,
  mapDispatchToProps,
  userAuth: true,
});