/**
*
* TemplatePreview
*
*/

import PropTypes from 'prop-types';

import React from 'react';
import _ from 'lodash';
import { injectIntl, FormattedMessage, intlShape } from 'react-intl';
// import styled from 'styled-components';
import { CapColumn, CapRow, CapHeading, CapIcon, CapButton, CapImage, CapLabel, CapDivider, CapTooltip } from '@capillarytech/cap-ui-library';
import {
  CAP_COLOR_03,
  CAP_WHITE,
  FONT_COLOR_01,
  CAP_G06,
  CAP_G15,
  CAP_PURPLE01,
  CAP_G16,
  CAP_SPACE_08,
  CAP_SPACE_04,
} from '@capillarytech/cap-ui-library/styled/variables';
import isEmpty from 'lodash/isEmpty';
import './_templatePreview.scss';
import {updateCharCount} from '../../utils/smsCharCountV2';
import messages from './messages';
import {
  WECHAT,
  WHATSAPP,
  RCS,
  ZALO,
  INAPP,
  MOBILE_PUSH
} from '../../v2Containers/CreativesContainer/constants';
import { VIBER, FACEBOOK } from '../../v2Containers/App/constants';
import Carousel from '../Carousel';
import whatsappMobileAndroid from './assets/images/whatsapp_mobile_android.svg';
import inAppMobileDeviceAndroid from '../../assets/Android.png';
import inAppMobileDeviceIos from '../../assets/iOS.png';
import whatsappImageEmptyPreview from './assets/images/empty_image_preview.svg';
import whatsappVideoEmptyPreview from './assets/images/empty_video_preview.svg';
import videoPlay from '../../assets/videoPlay.svg';
import zaloMessage from '../../v2Containers/Zalo/messages';
import { handlePreviewInNewTab } from '../../utils/common';
import { TEMPLATE, IMAGE_CAROUSEL, IMAGE, STICKER, TEXT, IMAGE_MAP, VIDEO } from '../../v2Containers/Line/Container/constants';
import CapFacebookPreview from '../../v2Containers/CapFacebookPreview';
import WhatsappStatusContainer from '../WhatsappStatusContainer';
import { getWhatsappQuickReply, getWhatsappCarouselButtonView } from '../../v2Containers/Whatsapp/utils';
import { QUICK_REPLY, WHATSAPP_CATEGORIES, PHONE_NUMBER, TEMPLATE_VARIABLE_REGEX } from '../../v2Containers/Whatsapp/constants';
import { RCS_BUTTON_TYPES, LEFT, HORIZONTAL, VERTICAL, RIGHT} from '../../v2Containers/Rcs/constants';
import { ANDROID, INAPP_MESSAGE_LAYOUT_TYPES } from '../../v2Containers/InApp/constants';
import { CAROUSEL } from '../../v2Containers/MobilePushNew/constants';

const wechatBodyNew = require('./assets/images/wechat_mobile_android.svg');
const smsMobileAndroid = require('./assets/images/sms_mobile_android.svg');
const smsMobileIos = require('./assets/images/sms_mobile_ios.svg');
const lineMobileAndroidDefaultImg = require('../../assets/Line_Preview_English.svg');
const lineMobileAndroidJapaneseImg = require('../../assets/Line_Preview_Japanese.svg');
const viberMobileAndroid = require('./assets/images/viberMobile.svg');

const lineImgPlaceholder = require('../../assets/line-image-placeholder.svg');
const lineStickerPlaceholder = require('../../assets/smiley-placeholder.svg');
const lineVideoPlaceholder = require('../../assets/rich-video-placeholder.svg');
const androidPushMessagePhone = require('./assets/images/Android_With_date_and_time.svg');
const iPhonePushMessagePhone = require('./assets/images/iOS_With_date_and_time.svg');

const { CapLabelInline } = CapLabel;

export class TemplatePreview extends React.Component { // eslint-disable-line react/prefer-stateless-function
  onPreviewContentClicked = (channel) => {
    const IOSContent = (this.props.templateDataRaw && this.props.templateDataRaw.versions.base.IOS) ||
      ((this.props.device === 'iphone' || this.props.device === 'ios') && this.props.content);
    const ANDROIDContent = (this.props.templateDataRaw && this.props.templateDataRaw.versions.base.ANDROID) ||
      (this.props.device === 'android' && this.props.content);
    const mobilePushPreviewContent = [];
    if (this.props.channel === 'MOBILEPUSH') {
      const previewObj = {
        channel: this.props.channel,
        accountId: this.props.templateDataRaw && this.props.templateDataRaw.definition.accountId,
        messageSubject: this.props.templateDataRaw && this.props.templateDataRaw.name,
        id: 'message_content_id_1',
      };
      if (IOSContent) {
        previewObj.iosContent = {
          title: IOSContent.title || IOSContent.header,
          message: IOSContent.message || IOSContent.bodyText,
          deviceType: "IOS",
          expandableDetails: IOSContent.expandableDetails ||
            {
              style: "BIG_PICTURE",
              image: this.props.content.bodyImage,
              message: this.props.content.bodyText,
            },
        };
      }
      if (ANDROIDContent) {
        previewObj.androidContent = {
          title: ANDROIDContent.title || ANDROIDContent.header,
          message: ANDROIDContent.message || ANDROIDContent.bodyText,
          deviceType: "ANDROID",
          expandableDetails: ANDROIDContent.expandableDetails ||
            {
              style: "BIG_PICTURE",
              image: this.props.content.bodyImage,
              message: this.props.content.bodyText,
            },
        };
      }
      mobilePushPreviewContent.push(previewObj);
    }
    const previewContent = this.props.channel === 'MOBILEPUSH' ? mobilePushPreviewContent : this.props.content;
    const params = {
      content: previewContent,
      channel,
    };
    this.props.onPreviewContentClicked(params);
  };

  onTestContentClicked = (channel) => {
    let mobilePushPreviewContent = {};
    const IOSContent = (this.props.templateDataRaw && this.props.templateDataRaw.versions.base.IOS) ||
      ((this.props.device === 'iphone' || this.props.device === 'ios') && this.props.content);
    const ANDROIDContent = (this.props.templateDataRaw && this.props.templateDataRaw.versions.base.ANDROID) ||
      (this.props.device === 'android' && this.props.content);
    if (this.props.channel === 'MOBILEPUSH') {
      mobilePushPreviewContent = {
        channel: this.props.channel,
        accountId: this.props.templateDataRaw && this.props.templateDataRaw.definition.accountId,
        messageSubject: this.props.templateDataRaw && this.props.templateDataRaw.name,
        id: 'message_content_id_1',
      };
      if (ANDROIDContent) {
        mobilePushPreviewContent.androidContent = {
          title: ANDROIDContent.title || ANDROIDContent.header,
          message: ANDROIDContent.message || ANDROIDContent.bodyText,
          deviceType: "ANDROID",
          expandableDetails: ANDROIDContent.expandableDetails ||
            {
              style: "BIG_PICTURE",
              image: this.props.content.bodyImage,
              message: this.props.content.bodyText,
            },
        };
      }
      if (IOSContent) {
        mobilePushPreviewContent.iosContent = {
          title: IOSContent.title || IOSContent.header,
          message: IOSContent.message || IOSContent.bodyText,
          deviceType: "IOS",
          expandableDetails: IOSContent.expandableDetails ||
            {
              style: "BIG_PICTURE",
              image: this.props.content.bodyImage,
              message: this.props.content.bodyText,
            },
        };
      }
    }
    const previewContent = this.props.channel === 'MOBILEPUSH' ? mobilePushPreviewContent : this.props.content;
    const params = {
      content: previewContent,
      channel,
    };
    this.props.onTestContentClicked(params);
  };

  renderMobilePushCarousel = (content) => {
    if (!content?.carouselData || content?.carouselData?.length === 0) {
      return null;
    }

    return (
      <CapRow type="flex" vertical noWrap className="msg-container-carousel mobile-push-carousel-container">
        <CapRow className="scroll-container mobile-push-scroll-container">
          {content?.carouselData?.map((item, idx) => (
            <CapColumn
              key={`carousel-card-${idx}`}
              className="mobile-push-carousel-card message-pop align-left message-pop-carousel"
            >
              {item?.mediaType?.toLowerCase() === IMAGE && (item?.imageUrl || item?.url) && (
                <CapImage
                  src={item?.imageUrl || item?.url}
                  alt="carousel-img"
                  className="carousel-image"
                />
              )}
              {item?.mediaType?.toLowerCase() === VIDEO && item?.videoPreviewImg && (
                <CapRow className="video-preview">
                  <CapImage
                    src={item?.videoPreviewImg || item?.url}
                    alt="carousel-video-preview"
                    className="carousel-video-preview"
                  />
                  <CapRow className="icon-position">
                    <CapImage className="video-icon" src={videoPlay} />
                  </CapRow>
                </CapRow>
              )}
              <CapRow useLegacy className="carousel-content">
                <CapLabel className="carousel-title">
                  {item?.title || item?.header || ""}
                </CapLabel>
                <CapLabel className="carousel-message">
                  {item?.message || item?.bodyText || ""}
                </CapLabel>
              </CapRow>
            </CapColumn>
          ))}
        </CapRow>
      </CapRow>
    );
  };

  render() {
    const {
      channel,
      showTestAndPreviewIcon,
      module,
      viberBrandName,
      viberAccountName,
      whatsappAccountName,
      whatsappContentLen,
      inAppAccountName,
      intl,
      templateData,
      rcsIosPreview,
      rcsType,
      rcsOrientation,
      hideTestAndPreviewBtn,
      hasJPLocaleHideFeatureEnabled,
      templateLayoutType,
      device,
    } = this.props;
    let content = channel && channel.toLowerCase() === 'sms' ? [this.props.content] : this.props.content;
    const { formatMessage } = intl;
    const { rcsPreviewContent, inAppPreviewContent, viberPreviewContent, isBeeFreeTemplate } = content || {};
    const { rcsImageSrc, rcsVideoSrc, rcsTitle, rcsDesc, rcsSuggestions } = rcsPreviewContent || {};
    const {
      videoParams,
      imageURL,
      buttonText: viberButtonText,
      messageContent: viberMessageContent,
    } = viberPreviewContent || {};
    let isHTMLContent = true;
    const {mediaPreview = {}, templateTitle = "", templateMsg = "", ctaData} = inAppPreviewContent || {};
    if(templateTitle !== undefined && ctaData !== undefined && templateMsg !== undefined) {
      isHTMLContent = false;
    }
    let smsDetails = {};
    // let smsText = '';
    if (this.props.content && this.props.charCounterEnabled) {
      smsDetails = updateCharCount(this.props.content, this.props.unicodeEnabled);
      content = [];
      for (let i = 0, limit = 0; i < smsDetails.parts; i += 1, limit += smsDetails.chars_sms) {
        content.push(smsDetails.char_list.slice(limit, smsDetails.chars_sms * (i + 1)));
      }
      if (document.getElementById("msg_count") && this.props.showCount) {
        document.getElementById("msg_count").val = smsDetails.parts;
      }
      //smsText = this.props.intl.formatMessage(messages.previewGenerationMessage);
      //
    }
    const type = this.props.location && this.props.location.query.type ? this.props.location.query.type : '';
    let iosActions = [];
    if ((channel || '').toLowerCase() === "mobilepush") {
      iosActions = _.map(content.actions || [], (action) => {
        if (action.label) {
          return (<CapRow className="actions" key={`action-${action.label}`}>
              <span className="action">{action.label.toUpperCase()}</span>
          </CapRow>);
        }
        return undefined;
      });
    }
    const disablePreviewAndTest = this.props.channel === 'MOBILEPUSH' ? !this.props.content.header : (this.props.channel === 'SMS' ? !this.props.content : false);
    const showTestAndPreview = showTestAndPreviewIcon &&
        channel !== WECHAT &&
        ['outbound', 'library'].includes(module) && !hideTestAndPreviewBtn;

    const renderLineMultiText = (content) => {
      let textCount = 0;
      return content.map((item) => {
        const { type, messageContent = '' } = item || {};
        if (type === 'text' && messageContent) {
          textCount += 1;
          return (
            <p style={{fontSize: 16, fontWeight: "bold", margin: 0}}>
              {this.props.intl.formatMessage(messages.textMessageLabel)}
              {textCount}: ({messageContent.length}/{1600} {this.props.intl.formatMessage(messages.textMessageCharacter)})
            </p>
          );
        }
        return null;
      });
    };
    const viberSectionStyle = {
      "padding": '3.5px 0 0',
      'border-radius': '8px',
      'background-color': CAP_G15,
      'width': '81%',
    };
    const whatsappSectionStyle = {
      'padding': `4px 0 ${CAP_SPACE_08}`,
      'border-radius': '6px',
      'background-color': CAP_WHITE,
      'width': '88%',
      'left': 0,
    };
    const carouselWhatsappSectionStyle = {
      'padding': `${CAP_SPACE_04} 0 ${CAP_SPACE_08}`,
      'border-radius': '0.428rem',
      'background-color': CAP_WHITE,
      'width': '10.4rem',
      'cursor': 'pointer',
      'flex-shrink': 0,
      'left': 0,
    };
    const getVideoContent = ({
      video,
      actionUrl,
      sectionStyle,
    }) => (
      <CapRow
        className="message-pop align-left"
        style={{
          ...sectionStyle,
          minHeight: 184,
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          backgroundColor: !video ? 'transparent' : CAP_G06,
          marginTop: 0,
          padding: 0,
        }}
        key={video}
      >
        {
          video
            ? (
              <>
                <video style={{ opacity: 0.5, width: '100%' }}>
                  <source src={video} type="video/mp4" />
                </video>
                <CapRow
                  style={{
                    position: 'absolute',
                    display: 'flex',
                    flexDirection: 'column',
                  }}
                >
                  <CapButton
                    className="preview-video-btn"
                    type="link"
                  >
                  <CapIcon type="play"/>
                    <FormattedMessage {...messages.playVideo} />
                  </CapButton>
                  {
                    actionUrl
                      ? (
                        <CapButton
                          className="preview-video-btn"
                          type="link"
                        >
                      <CapIcon type="reply" style={{ fontSize: 18 }}/>
                          <FormattedMessage {...messages.showDetails} />
                        </CapButton>
                      )
                      : null
                  }
                </CapRow>
              </>
            )
            : (
              <CapImage
                src={lineVideoPlaceholder}
                alt="brand-name"
                rest={{
                  style: {
                    width: 126,
                    marginBottom: 5,
                  },
                }}
              />
            )
        }
      </CapRow>
    );

    const renderWhatsappCtaPreview = () => {
      const renderArray = [];
      const { ctaData = [] } = content || {};
      if (ctaData?.length) {
        renderArray.push(<CapDivider className="whatsapp-divider" />);
        ctaData.forEach((i) => {
          const { ctaType, type, text } = i || {};
          if (text) {
            renderArray.push(
              <CapLabel type="label21" className="whatsapp-cta-preview">
                {type !== WHATSAPP_CATEGORIES.authentication && <CapIcon
                    type={
                      (ctaType || type) === PHONE_NUMBER ? 'call' : 'launch'
                    }
                    size="xs"
                />}
                {text}
              </CapLabel>,
            );
          }
        });
      }
      return renderArray;
    };

    const renderQuickReplyPreview = () => {
      const { quickReplyData = [] } = content || {};
      return getWhatsappQuickReply(
        {
          buttons: quickReplyData,
          buttonType: QUICK_REPLY,
        },
        true
      );
    };

    const renderUrlPreview = (metaTags) => {
      const renderArray = [];
      if (!isEmpty(metaTags)) {
        const { image = '', title = '', description = '', url = '' } = metaTags || {};
        if (image) {
          renderArray.push(
            <CapImage
              src={image}
              alt={formatMessage(messages.previewUrlMetaImage)}
              className="url-preview-image"
            />
          );
        }
        if (title) {
          renderArray.push(
            <CapLabel type="label8">{title}</CapLabel>
          );
        }
        if (description) {
          renderArray.push(
            <CapLabel className="url-preview-description">{description}</CapLabel>
          );
        }
        if (url) {
          renderArray.push(
            <CapLabel className="url-preview">{url}</CapLabel>
          );
        }
      }
      return renderArray;
    };

    const handlePreview = () => {
      const {templatePreviewUrl = ''} = templateData;
      handlePreviewInNewTab(templatePreviewUrl);
    };

    const   getPreviewImage = () => {
    if (this.props.device === ANDROID) {
      return inAppMobileDeviceAndroid;
    } else {
      return inAppMobileDeviceIos;
    }
  };

    const whatsappUpdatedAccountName = whatsappAccountName || templateData?.versions?.base?.content?.whatsapp?.accountName || '';
    const whatsappUpdatedLen = whatsappContentLen !== undefined ? whatsappContentLen : content?.charCount;

    const renderRcsSuggestionsPreview = () => {
      const renderArray = [];
      (rcsSuggestions || []).forEach((suggestion) => {
        renderArray.push(<CapDivider className="whatsapp-divider" />);
        if (suggestion.type === RCS_BUTTON_TYPES.QUICK_REPLY) {
          renderArray.push(
            <CapLabel type="label21" className="rcs-cta-preview">
              <CapIcon
                type='small-link'
                size="xs"
              />
              {suggestion.text}
            </CapLabel>
          );
        } else if (suggestion.type === RCS_BUTTON_TYPES.CTA) {
          renderArray.push(
            <CapLabel type="label21" className="rcs-cta-preview">
              <CapIcon type="launch" size="xs" />
              {suggestion.text}
            </CapLabel>,
          );
        } else if (suggestion.type === RCS_BUTTON_TYPES.PHONE_NUMBER) {
          renderArray.push(
            <CapLabel type="label21" className="rcs-cta-preview">
              <CapIcon type="call" size="xs" />
              {suggestion.text}
            </CapLabel>,
          );
        }
      });
      return renderArray;
    };

    const renderTextPreviewContent = () => (
      <>
         {rcsTitle && (
      <>
        <CapLabel
          type="label5"
          className="message-pop-item align-left rcs-content"
          fontWeight="bold"
        >
          {rcsTitle}
        </CapLabel>
        <CapDivider className="whatsapp-divider" />
      </>
    )}
        {rcsDesc && (
          <CapLabel
            type="label5"
            className="message-pop-item align-left rcs-desc rcs-content"
          >
            {rcsDesc}
          </CapLabel>
        )}
        {renderRcsSuggestionsPreview()}
      </>
    );

    const renderMediaPreviewContent = () => (
      <>
        {rcsImageSrc && (
          <CapImage
            src={rcsImageSrc}
            className="rcs-image"
            alt={formatMessage(messages.previewGenerated)}
          />
        )}
        {rcsVideoSrc && (
          <div className="video-preview">
            <CapImage
              src={rcsVideoSrc}
              className="rcs-image"
              alt={formatMessage(messages.previewGenerated)}
            />
            <div className="icon-position">
              <CapImage
                className="video-icon"
                src={videoPlay}
              />
            </div>
          </div>
        )}   
      </>
    );

    const renderRcsPreviewContent = () => {
      if (rcsOrientation === HORIZONTAL) {
        return rcsType === RIGHT ? (
          <div className="msg-container sms">
            <div className="message-pop sms horizontal">
              <CapColumn className="rcs-preview-text" span={12}>{renderTextPreviewContent()}</CapColumn>
              <CapColumn span={12}>{renderMediaPreviewContent()}</CapColumn>
            </div>
          </div>

        ) : (
          <div className="msg-container sms">
            <div className="message-pop sms horizontal">
              <CapColumn span={12}>{renderMediaPreviewContent()}</CapColumn>
              <CapColumn className="rcs-preview-text" span={12}>{renderTextPreviewContent()}</CapColumn>
            </div>
          </div>
        );
      }
    
      return (
        <div className="msg-container sms">
          <div className="message-pop sms">
            {renderMediaPreviewContent()}
            {renderTextPreviewContent()}
          </div>
        </div>
      );
    };

    return (
      <CapRow>
        {this.props.showCount &&
          channel &&
          channel.toLowerCase() !== FACEBOOK && (
          <CapColumn span={16}>
            {channel && channel.toLowerCase() === "sms" && (
              <CapHeading type="h3">
                <FormattedMessage
                  {...messages.charactersTotal}
                  values={{
                    smsCount: smsDetails.parts,
                    charCount: smsDetails.chars_used,
                  }}
                />
                {smsDetails.unicode && (
                  <FormattedMessage {...messages.smsFormatType} />
                )}
              </CapHeading>
            )}
            {smsDetails.optoutUrlPresent && (
              <CapHeading type="h6">
                <FormattedMessage
                  {...messages.optoutCharactersTotal}
                  values={{ optoutUrlLength: smsDetails.optouturlLength }}
                />
              </CapHeading>
            )}
            {channel?.toLowerCase() === WHATSAPP.toLowerCase() ? (
              <>
                <WhatsappStatusContainer template={templateData} />
                <CapHeading type="h3" className="margin-t-12">
                  <FormattedMessage
                    {...messages.whatsappMessageLength}
                    values={{ length: whatsappUpdatedLen }}
                  />
                </CapHeading>
              </>
            ) : null}
          </CapColumn>
        )}
        <CapColumn span={this.props.showCount ? 8 : 24}>
          <CapRow
            className={`preview-container ${
              type === "embedded" ? "embedded-preview" : ""
            }`}
          >
            {channel && channel.toLowerCase() === "sms" && (
              <CapRow>
                <CapRow useLegacy className="shell-v2 align-center" id="sms-preview">
                  <CapImage
                    className="preview-image sms"
                    src={smsMobileAndroid}
                    alt={this.props.intl.formatMessage(messages.previewGenerated)}
                  />
                  <CapRow className="msg-container sms">
                    <CapRow useLegacy className={"message-pop sms"}>
                      {content &&
                        content.length &&
                        content.map((msg, index) => (
                          <CapColumn
                            key={`"message-pop-content-${index}`}
                            className="message-pop-item align-left"
                            style={{ background: "#FFFFFF", color: "#091e42" }}
                          >
                            {msg}
                          </CapColumn>
                        ))}
                    </CapRow>
                  </CapRow>
                </CapRow>
                {!this.props.showCount && (
                  <CapRow type='flex' justify='center'>
                    <CapRow type='flex' align='middle' justify='center' className="character-count-col">
                      {(channel || "").toLowerCase() === "sms" && (
                        <CapHeading type="h3">
                          <FormattedMessage
                            {...messages.charactersTotal}
                            values={{
                              smsCount: smsDetails.parts,
                              charCount: smsDetails.chars_used,
                            }}
                          />
                          {smsDetails.unicode && (
                            <FormattedMessage {...messages.smsFormatType} />
                          )}
                        </CapHeading>
                      )}
                      {smsDetails.optoutUrlPresent && (
                        <CapHeading type="h6" className="optout-tag-heading">
                          <FormattedMessage
                            {...messages.optoutCharactersTotal}
                            values={{
                              optoutUrlLength: smsDetails.optouturlLength,
                            }}
                          />
                        </CapHeading>
                      )}
                    </CapRow>
                  </CapRow>
                )}
              </CapRow>
            )}
            {channel && channel.toLowerCase() === "wechat" ? (
              <CapRow className="shell-v2 align-center" id="sms-preview">
                <CapImage
                  className="preview-image"
                  src={
                    (channel || "").toLowerCase() === "wechat"
                      ? wechatBodyNew
                      : smsMobileAndroid
                  }
                  alt={this.props.intl.formatMessage(messages.previewGenerated)}
                />
                <CapRow className="msg-container wechat">
                  <CapRow
                    className="message-pop align-left"
                    style={{
                      background: `${
                        this.props.channel.toLowerCase() === "wechat"
                          ? "#ffffff"
                          : "#3F51B5"
                      }`,
                      color: `${
                        this.props.channel.toLowerCase() === "wechat"
                          ? "#333333"
                          : "#ffffff"
                      }`,
                    }}
                  >
                    {content}
                  </CapRow>
                </CapRow>
              </CapRow>
            ) : (
              ""
            )}
            {channel && channel.toUpperCase() === MOBILE_PUSH && (
              <CapRow type='flex' align='middle' className="shell-v2 align-center" id="mobilepush-preview">
                <CapImage
                  className="preview-image"
                  src={
                    this.props.device === "android"
                      ? androidPushMessagePhone
                      : iPhonePushMessagePhone
                  }
                  alt={this.props.intl.formatMessage(messages.previewGenerated)}
                />
                {(!!content.header ||
                  !!content.bodyText ||
                  !!content.bodyImage || !!content.bodyVideo?.videoSrc || !!content.bodyGif) && (
                  <CapRow
                    useLegacy
                    className={`${
                      this.props.device === "ios" ? "iphone" : this.props.device
                    }-push-message-Container`}
                  >
                    {this.props.device === "android" ? (
                      <CapRow type='flex' align='start' vertical className="message-pop align-left">
                        <CapRow type='flex' fullWidth className="app-header">
                          <CapRow type='flex' className="app-header-left">
                          <span className="app-icon">{""}</span>
                          <CapLabel className="title">{content.header}</CapLabel>
                          </CapRow>
                          <CapRow type='flex' className="app-header-right">
                            <span>2:29 PM</span>
                            <CapIcon type="chevron-down" size="sm" />
                          </CapRow>
                        </CapRow>
                        <CapLabel className="body-text">{content.bodyText}</CapLabel>
                        {(content.bodyImage || content?.bodyVideo?.videoSrc || content?.bodyGif) && (
                          <CapRow useLegacy className="body-image">
                            {(() => {
                              if (content?.bodyVideo?.videoSrc && !content?.bodyImage && !content?.bodyGif) {
                                return (
                                  <video 
                                    key={`android-video-${content.bodyVideo.videoSrc}`}
                                    controls 
                                    style={{ maxWidth: '100%', maxHeight: '120px', marginLeft: '24px' }}
                                    poster={content?.bodyVideo?.videoPreview || undefined}
                                  >
                                    <source src={content.bodyVideo.videoSrc} type="video/mp4" />
                                  </video>
                                );
                              } else if (content?.bodyGif) {
                                return (
                                  <img 
                                    src={content?.bodyGif} 
                                    alt="GIF preview" 
                                    style={{ maxWidth: '100%', maxHeight: '120px' }}
                                    key={`android-gif-${content?.bodyGif}`}
                                  />
                                );
                              } else {
                                return (
                                  <CapImage src={content?.bodyImage || content?.bodyVideo?.videoPreview} alt="" />
                                );
                              }
                            })()}
                          </CapRow>
                        )}
                        {(content?.actions || []).filter((action) => action?.label)
                          .length && content?.carouselData?.length === 0 ? (
                            <CapRow className="actions">
                              {_.map(
                                content?.actions || [],
                                (action) =>
                                  !!action?.label && (
                                    <span
                                      className="action"
                                      key={`action-${action?.label}`}
                                      title={action?.url || ''}
                                    >
                                      {action?.label?.toUpperCase()}
                                    </span>
                                  )
                              )}
                            </CapRow>
                          ) : null}
                        {channel && channel.toLowerCase() === "mobilepush" && this.renderMobilePushCarousel(content)}
                      </CapRow>
                    ) : (
                      <CapRow type='flex' align='start' vertical className="message-pop align-left">
                        <CapRow type='flex' fullWidth className="app-header">
                          <CapRow type='flex' className="app-header-left">
                          <span className="app-icon">{""}</span>
                          <CapLabel className="title">{content.header}</CapLabel>
                          </CapRow>
                          <CapRow type='flex' className="app-header-right">
                            <span>2:29 PM</span>
                            <CapIcon type="chevron-down" size="sm" />
                          </CapRow>
                        </CapRow>
                        <CapLabel className="body-text">{content.bodyText}</CapLabel>
                        {(content?.bodyImage || content?.bodyVideo?.videoSrc || content?.bodyGif) && (
                          <CapRow useLegacy className="body-image">
                            {(() => {
                              if (content?.bodyVideo?.videoSrc && !content?.bodyImage && !content?.bodyGif) {
                                return (
                                  <video 
                                    key={`ios-video-${content?.bodyVideo?.videoSrc}`}
                                    controls 
                                    style={{ maxWidth: '100%', maxHeight: '120px', marginLeft: '24px' }}
                                    poster={content?.bodyVideo?.videoPreview || undefined}
                                  >
                                    <source src={content?.bodyVideo?.videoSrc} type="video/mp4" />
                                  </video>
                                );
                              } else if (content?.bodyGif) {
                                return (
                                  <img 
                                    src={content?.bodyGif} 
                                    alt="GIF preview" 
                                    style={{ maxWidth: '100%', maxHeight: '120px' }}
                                    key={`ios-gif-${content?.bodyGif}`}
                                  />
                                );
                              } else {
                                return (
                                  <CapImage src={content?.bodyImage || content?.bodyVideo?.videoPreview} alt="" />
                                );
                              }
                            })()}
                          </CapRow>
                        )}
                        {(content?.actions || []).filter((action) => action?.label)
                          .length && content?.carouselData?.length === 0 ? (
                            <CapRow className="actions">
                              {_.map(
                                content?.actions || [],
                                (action) =>
                                  !!action?.label && (
                                    <span
                                      className="action"
                                      key={`action-${action?.label}`}
                                      title={action?.url || ''}
                                    >
                                      {action?.label?.toUpperCase()}
                                    </span>
                                  )
                              )}
                            </CapRow>
                          ) : null}
                        {channel && channel.toLowerCase() === "mobilepush" && this.renderMobilePushCarousel(content)}
                      </CapRow>
                    )}
                  </CapRow>
                )}
              </CapRow>
            )}
            {channel && channel.toLowerCase() === "line" ? (
              <div className="shell-v2 align-center" id="sms-preview">
                <CapImage
                  className="preview-image"
                  src={
                    hasJPLocaleHideFeatureEnabled
                      ? lineMobileAndroidJapaneseImg
                      : lineMobileAndroidDefaultImg
                  }
                  alt={this.props.intl.formatMessage(messages.previewGenerated)}
                />
                <div
                  className="msg-container line-preview"
                  style={{
                    maxHeight: 330,
                    overflow: "auto",
                    flexDirection: "column",
                    marginLeft: 40,
                    left: !this.props.showCount && "200px",
                  }}
                >
                  <div
                    className="sms-icon"
                    style={{
                      left: 0,
                      top: 8,
                      borderRadius: "50%",
                      width: 20,
                      height: 20,
                      background: CAP_COLOR_03,
                      paddingRight: 5,
                    }}
                  >
                    {this.props.LineAccountName}
                  </div>
                  <>
                    {content?.map((item) => {
                      const {
                        type,
                        messageContent,
                        previewImageUrl = lineImgPlaceholder,
                        baseUrl,
                        selectedSticker = {
                          stickerUrl: lineStickerPlaceholder,
                        },
                        imageCarousel = [lineImgPlaceholder],
                        video,
                        actionUrl,
                      } = item || {};
                      const sectionStyle = {
                        background: CAP_WHITE,
                        color: FONT_COLOR_01,
                        borderRadius: 8,
                        position: "static",
                        margin: "6px 0 20px 28px",
                        height: "auto",
                        minHeight: "auto",
                        overflow: "initial",
                        maxHeight: "initial",
                      };
                      if (type === TEXT) {
                        return (
                          <div
                            className="message-pop align-left"
                            style={sectionStyle}
                          >
                            <p style={{ marginBottom: 5 }}>
                              {messageContent || ""}
                            </p>
                          </div>
                        );
                      }
                      if (type === IMAGE && previewImageUrl) {
                        return (
                          <div
                            className="message-pop align-left"
                            style={{
                              ...sectionStyle,
                              minHeight: 184,
                              display: "flex",
                              justifyContent: "center",
                              alignItems: "center",
                            }}
                          >
                            <CapImage
                              src={previewImageUrl}
                              alt="brand-name"
                              className="line-image-preview"
                              rest={{
                                style: {
                                  maxWidth: "100%",
                                  marginBottom: 5,
                                },
                              }}
                            />
                          </div>
                        );
                      }
                      if (type === VIDEO) {
                        return getVideoContent({
                          video,
                          actionUrl,
                          sectionStyle,
                        });
                      }
                      if (type === IMAGE_MAP && baseUrl) {
                        if (video) {
                          return getVideoContent({
                            video,
                            actionUrl,
                            sectionStyle,
                          });
                        }
                        return (
                          <div
                            className="message-pop align-left"
                            style={{
                              ...sectionStyle,
                              minHeight: 184,
                              display: "flex",
                              justifyContent: "center",
                              alignItems: "center",
                            }}
                          >
                            <CapImage
                              src={
                                baseUrl ? `${baseUrl}/1040` : lineImgPlaceholder
                              }
                              alt="brand-name"
                              className="line-image-preview"
                              rest={{
                                style: {
                                  maxWidth: "100%",
                                  marginBottom: 5,
                                },
                              }}
                            />
                          </div>
                        );
                      }
                      if (type === STICKER && selectedSticker) {
                        return (
                          <div
                            className="message-pop align-left"
                            style={{
                              ...sectionStyle,
                              background: "transparent",
                              display: "flex",
                              justifyContent: "center",
                              alignItems: "center",
                            }}
                          >
                            <CapImage
                              src={selectedSticker.stickerUrl}
                              style={{ maxWidth: "100%", marginBottom: 5 }}
                              rest={{
                                style: {
                                  maxWidth: "100%",
                                  marginBottom: 5,
                                },
                                height: 70,
                                onMouseOut: (e) =>
                                  (e.currentTarget.src =
                                    selectedSticker.stickerUrl),
                                onMouseOver: (e) =>
                                  (e.currentTarget.src =
                                    selectedSticker.animatedStickerUrl ||
                                    selectedSticker.stickerUrl),
                              }}
                            />
                          </div>
                        );
                      }
                      if (
                        (type === IMAGE_CAROUSEL ||
                          type === TEMPLATE ||
                          type === "template") &&
                        imageCarousel
                      ) {
                        return (
                          <div
                            style={{
                              margin: "6px 0 20px 28px",
                            }}
                          >
                            <Carousel imageCarousel={imageCarousel} />
                          </div>
                        );
                      }
                      return null;
                    })}
                  </>
                </div>
                {renderLineMultiText(content)}
              </div>
            ) : (
              ""
            )}
            {channel && channel.toLowerCase() === VIBER ? (
              <div className="shell-v2 align-center" id="sms-preview">
                <CapImage
                  className="preview-image"
                  src={viberMobileAndroid}
                  alt={this.props.intl.formatMessage(messages.previewGenerated)}
                />
                <div style={{ position: "absolute", top: "12%", left: "36%" }}>
                  {viberBrandName}
                </div>
                <div
                  className="msg-container viber-preview"
                  style={{
                    maxHeight: 292,
                    marginLeft: 28,
                  }}
                >
                  <div
                    className="sms-icon"
                    style={{
                      width: 20,
                      height: 20,
                      margin: "0 4px 277px 0",
                      "border-radius": "4px",
                      "background-color": CAP_PURPLE01,
                      "font-size": "12px",
                      "font-weight": 900,
                      color: CAP_WHITE,
                    }}
                  >
                    {viberAccountName}
                  </div>
                  <div
                    className="message-pop align-left"
                    style={viberSectionStyle}
                  >
                    {/* Text Viber preview */}
                    <p
                      style={{
                        "font-size": "10px",
                        color: CAP_G16,
                        margin: "1.5px 6px 1px 7px",
                      }}
                    >
                      {viberMessageContent || ""}
                    </p>
                    {/* Image Viber preview */}
                    {imageURL && (
                      <CapImage
                        src={imageURL}
                        className="viber-image-preview"
                        alt="brand-name"
                        rest={{
                          style: {
                            maxWidth: "100%",
                            marginBottom: 5,
                          },
                        }}
                      />
                    )}
                    {/* Video Viber preview */}
                    {videoParams?.viberVideoSrc && (
                      <CapTooltip
                        title={formatMessage(messages.videoPreviewTooltip)}
                      >
                        <div className="video-preview">
                          <CapImage
                            src={videoParams?.viberVideoPreviewImg}
                            className="whatsapp-image"
                            alt={formatMessage(messages.previewGenerated)}
                            rest={{
                              style: {
                                maxWidth: "100%",
                                marginBottom: 5,
                              },
                            }}
                          />
                          <div className="icon-position">
                            <CapImage
                              className="video-icon"
                              src={videoPlay} />
                          </div>
                        </div>
                      </CapTooltip>
                    )}
                    {/* button viber preview */}
                    {viberButtonText && (
                      <CapLabel className="viber-button-base">
                        <p className="viber-button-card-text">
                          {viberButtonText || ""}
                        </p>
                      </CapLabel>
                    )}
                    <div className="empty-placeholder"></div>
                  </div>
                </div>
              </div>
            ) : (
              ""
            )}
            {channel?.toUpperCase() === WHATSAPP ? (
              <>
                <div className="shell-v2 align-center">
                  <CapImage
                    className="preview-image"
                    src={whatsappMobileAndroid}
                    alt={formatMessage(messages.previewGenerated)}
                  />
                  <CapLabel className="whatsapp-brand-name">
                    {whatsappUpdatedAccountName || ""}
                  </CapLabel>
                  <div className={`msg-container whatsapp-message-container ${content?.carouselData && 'msg-container-carousel'}`}>
                    <div
                      className={`message-pop align-left ${content?.carouselData && 'message-pop-carousel'}`}
                      style={whatsappSectionStyle}
                    >
                      <div className="whatsapp-content">
                        {content?.showUrlPreview
                          && renderUrlPreview(content?.metaTagsDetails)}
                        {content?.whatsappImageSrc && (
                          TEMPLATE_VARIABLE_REGEX.test(content.whatsappImageSrc) ? (
                            <CapRow className="whatsapp-image-url-placeholder">
                              <CapIcon type="picture" size="s" className="whatsapp-image-url-placeholder-icon" />
                              <CapLabelInline type="label2" className="whatsapp-image-url-placeholder-text">
                                {content.whatsappImageSrc}
                              </CapLabelInline>
                            </CapRow>
                          ) : (
                            <CapImage
                              src={content.whatsappImageSrc}
                              className="whatsapp-image"
                              alt={formatMessage(messages.previewGenerated)}
                              onError={(e) => { e.target.src = whatsappImageEmptyPreview; }}
                            />
                          )
                        )}
                        {content?.whatsappVideoPreviewImg && (
                          <CapTooltip
                            title={formatMessage(messages.videoPreviewTooltip)}
                          >
                            <div className="video-preview">
                              <CapImage
                                src={content.whatsappVideoPreviewImg}
                                className="whatsapp-image"
                                alt={formatMessage(messages.previewGenerated)}
                              />
                              <div className="icon-position">
                                <CapImage
                                  className="video-icon"
                                  src={videoPlay}
                                />
                              </div>
                            </div>
                          </CapTooltip>
                        )}
                        {content?.docPreview && (
                          <div className="whatsapp-image">
                            {content?.docPreview}
                          </div>
                        )}
                        {content?.templateHeaderPreview || ""}
                        {content?.templateMsg || ""}
                        {content?.templateFooterPreview || ""}
                        {renderWhatsappCtaPreview()}
                        {renderQuickReplyPreview()}
                      </div>
                    </div>
                    {content?.carouselData && (
                      <div className="scroll-container">
                        {content?.carouselData?.map((data, index) => (
                          <div
                            key={`carousel-${index}-${data?.bodyText}`}
                            className="message-pop align-left message-pop-carousel"
                            style={carouselWhatsappSectionStyle}>
                            <div className="whatsapp-content">
                              {content?.carouselMediaType === "image" && (
                                <CapImage
                                  src={data?.imageSrc ? data?.imageSrc : whatsappImageEmptyPreview}
                                  className="whatsapp-image"
                                  alt={formatMessage(messages.previewGenerated)}
                                />
                              )}
                              {content?.carouselMediaType === "video" && (
                                <CapTooltip
                                  title={formatMessage(messages.videoPreviewTooltip)}
                                >
                                  <div className="video-preview">
                                    <CapImage
                                      src={data?.videoPreviewImg ? data?.videoPreviewImg : whatsappVideoEmptyPreview}
                                      className="whatsapp-image"
                                      alt={formatMessage(messages.previewGenerated)}
                                    />
                                    <div className="icon-position">
                                      <CapImage
                                        className="video-icon"
                                        src={videoPlay}
                                      />
                                    </div>
                                  </div>
                                </CapTooltip>
                              )}
                              <CapLabel type="label5">
                                {content?.isEditFlow ? data?.updatedBodyText?.join("") : data?.bodyText}
                              </CapLabel>
                              {getWhatsappCarouselButtonView(data?.buttons, true)}
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
                <CapHeading
                  type="h3"
                  style={{ textAlign: "center", width: "100%" }}
                  className="margin-t-16"
                >
                  <FormattedMessage
                    {...messages.whatsappMessageLength}
                    values={{ length: whatsappUpdatedLen }}
                  />
                </CapHeading>
              </>
            ) : (
              ""
            )}
            {channel?.toUpperCase() === RCS && (
              <div className="shell-v2 align-center rcs-preview">
                <CapImage
                  className="preview-image"
                  src={rcsIosPreview ? smsMobileIos : smsMobileAndroid}
                  alt={formatMessage(messages.previewGenerated)}
                />
                {renderRcsPreviewContent()}
              </div>
                
            )}
            {channel?.toUpperCase() === ZALO && (
              <CapRow
                useLegacy
                className={`zalo-preview-container ${
                  templateData?.fullMode
                    ? "zalo-preview-container-creative"
                    : "zalo-preview-container-campaign"
                }`}
              >
                <CapRow useLegacy>
                  <CapLabel className="preview-head">
                    {formatMessage(zaloMessage.previewHead)}
                  </CapLabel>
                </CapRow>
                <CapRow useLegacy>
                  <CapLabel className="preview-text">
                    {formatMessage(zaloMessage.previewText)}
                  </CapLabel>
                </CapRow>
                <CapRow useLegacy>
                  <CapLabel
                    data-testid="preview-link-button"
                    onClick={handlePreview}
                    className="preview-link"
                  >
                    {formatMessage(zaloMessage.openPreview)}{" "}
                    <CapIcon type="open-in-new-light"></CapIcon>
                  </CapLabel>
                </CapRow>
              </CapRow>
            )}
            {channel && channel.toLowerCase() === FACEBOOK && (
              <div
                style={{ position: "absolute", left: "80%" }}
                id="facebook-preview"
              >
                <CapFacebookPreview
                  disablePreviewButton={false}
                  selectedAd={content.selectedAd}
                  previewData={content.previewData}
                  primaryText={content.primaryText}
                  callToAction={content.callToAction}
                  displayLink={content.displayLink}
                  orgUnitFacebookPageSettingsMap={{
                    pageAccessToken: content.pageAccessToken,
                    pageId: content.pageId,
                  }}
                  accountId={content.accountId}
                  accessToken={content.accessToken}
                  defaultGeneratePreview
                />
              </div>
            )}
            {channel?.toUpperCase() === INAPP && (
              isBeeFreeTemplate ? (
                  <div className="shell-v2 align-center">
                    <CapRow useLegacy className="preview-image-container">
                      <CapImage
                        className="preview-image"
                        src={this.props.device === ANDROID ? inAppMobileDeviceAndroid : inAppMobileDeviceIos}
                        alt={formatMessage(messages.previewGenerated)}
                      />
                      <iframe 
                        srcDoc={inAppPreviewContent?.value} 
                        title={formatMessage(messages.inappPreview)}
                        style={{
                          position: 'absolute',
                          top: '3rem',
                          left: '5rem',
                          width: '60%',
                          height: '89%',
                          zIndex: 1,
                          pointerEvents: 'none',
                          backgroundColor: 'white',
                          borderRadius: `${CAP_SPACE_08}`,
                        }}
                        frameBorder="0" 
                      />
                    </CapRow>
                  </div>
              ): (
                <div className="shell-v2 align-center">
                <CapImage
                  className="preview-image"
                  src={getPreviewImage()}
                  alt={formatMessage(messages.previewGenerated)}
                />
                <div className="preview-image">
                  <div
                    className={`inapp-message-container-${templateLayoutType}-${device} inapp`}
                  >
                    {isHTMLContent ? (
                      <div
                        className="inapp-html-content"
                        dangerouslySetInnerHTML={{ __html: templateMsg }}
                      />
                    ) : (
                      <div className="preview-inapp-screen">
                      {
                        <CapLabel
                          type="label15"
                          className={`align-center inapp-title-${templateLayoutType}-${device} ${
                            mediaPreview?.inAppImageSrcAndroid
                              ? ""
                              : `without-image-title-${templateLayoutType}-android`
                          } ${
                            mediaPreview?.inAppImageSrcIos
                              ? ""
                              : `without-image-title-${templateLayoutType}-ios`
                          }`}
                        >
                          {templateTitle ? templateTitle : " "}
                          {/* this ternary is required here for preview */}
                        </CapLabel>
                      }
                      {mediaPreview && (
                        <CapImage
                          src={
                            device === ANDROID
                              ? mediaPreview?.inAppImageSrcAndroid
                              : mediaPreview?.inAppImageSrcIos
                          }
                          className={`inapp-image-${templateLayoutType}-${device}`}
                          alt={formatMessage(messages.previewGenerated)}
                        />
                      )}
                      {
                        <CapLabel
                          type="label5"
                          className={`align-left inapp-content-${templateLayoutType}-${device} ${
                            mediaPreview?.inAppImageSrcAndroid
                              ? ""
                              : `without-image-content-${templateLayoutType}-android`
                          } ${
                            mediaPreview?.inAppImageSrcIos
                              ? ""
                              : `without-image-content-${templateLayoutType}-ios`
                          }`}
                        >
                          {templateMsg ? templateMsg : " "}
                          {/* this ternary is required here for preview */}
                        </CapLabel>
                      }
                      {ctaData &&
                        !isEmpty(ctaData) &&
                        ctaData[0]?.text !== "" && (
                        <CapButton
                          type="primary"
                          className={`inapp-button-${templateLayoutType}-${device} ${
                              mediaPreview?.inAppImageSrcAndroid
                                ? ""
                                : `without-image-button-${templateLayoutType}-android`
                          } ${
                              mediaPreview?.inAppImageSrcIos
                                ? ""
                                : `without-image-button-${templateLayoutType}-ios`
                          }`}
                        >
                          {ctaData[0]?.text}
                        </CapButton>
                      )}
                    </div>
                    )}
                  </div>
                </div>
              </div>
              )
            )}
          </CapRow>
        </CapColumn>
      </CapRow>
    );
  }
}
TemplatePreview.propTypes = {
  content: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.string,
  ]),
  channel: PropTypes.string,
  charCounterEnabled: PropTypes.bool,
  location: PropTypes.object,
  device: PropTypes.string,
  unicodeEnabled: PropTypes.bool,
  showCount: PropTypes.bool,
  intl: intlShape.isRequired,
  templateDataRaw: PropTypes.object,
  onPreviewContentClicked: PropTypes.func,
  onTestContentClicked: PropTypes.func,
  showTestAndPreviewIcon: PropTypes.bool,
  fbContent: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.any,
  ]),
  hasJPLocaleHideFeatureEnabled: PropTypes.bool,
  rcsType: PropTypes.string,
  rcsOrientation: PropTypes.string,
};

export default (injectIntl(TemplatePreview));
