import React, { useState, useEffect, useCallback } from 'react';
import { bindActionCreators } from 'redux';
import { createStructuredSelector } from 'reselect';
import { injectIntl, FormattedMessage } from 'react-intl';
import isEmpty from 'lodash/isEmpty';
import get from 'lodash/get';
import CapHeader from '@capillarytech/cap-ui-library/CapHeader';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapColumn from '@capillarytech/cap-ui-library/CapColumn';
import CapSpin from '@capillarytech/cap-ui-library/CapSpin';
import CapLabel from '@capillarytech/cap-ui-library/CapLabel';
import CapInput from '@capillarytech/cap-ui-library/CapInput';
import CapHeading from '@capillarytech/cap-ui-library/CapHeading';
import CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapNotification from '@capillarytech/cap-ui-library/CapNotification';
import CapTooltip from '@capillarytech/cap-ui-library/CapTooltip';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
import CapRadioGroup from '@capillarytech/cap-ui-library/CapRadioGroup';
import CapTab from '@capillarytech/cap-ui-library/CapTab';
import CapDivider from '@capillarytech/cap-ui-library/CapDivider';
import CapSelect from '@capillarytech/cap-ui-library/CapSelect';
import CapAskAira from '@capillarytech/cap-ui-library/CapAskAira';
import { GA } from '@capillarytech/cap-ui-utils';
import * as globalActions from '../Cap/actions';
import { makeSelectViber, makeSelectCreateViber } from './selectors';
import * as viberActions from './actions';
import { validateTags } from '../../utils/tagValidations';
import UnifiedPreview from '../../v2Components/CommonTestAndPreview/UnifiedPreview';
import { ANDROID } from '../../v2Components/CommonTestAndPreview/constants';
import TestAndPreviewSlidebox from '../../v2Components/TestAndPreviewSlidebox';
import { isUrl } from '../Line/Container/Wrapper/utils';
import messages from './messages';
import creativesMessages from '../CreativesContainer/messages';
import TagList from '../TagList';
import CapTagListWithInput from '../../v2Components/CapTagListWithInput';
import { makeSelectMetaEntities, setInjectedTags } from '../Cap/selectors';
import {
  ALLOWED_IMAGE_EXTENSIONS_REGEX_VIBER,
  ALLOWED_EXTENSIONS_VIDEO_REGEX_VIBER,
  VIBER_IMG_HEIGHT,
  VIBER_IMG_WIDTH,
  VIBER_IMG_SIZE,
  VIBER_VIDEO_SIZE,
  charLimit,
  VIBER_MEDIA_TYPES,
  VIBER_BUTTON_TYPES,
  NONE,
  mediaRadioOptions,
  buttonRadioOptions,
  VIBER_CAROUSEL_MAX_BUTTONS,
  VIBER_CAROUSEL_MAX_CARDS,
  VIBER_CAROUSEL_MIN_CARDS,
  VIBER_CAROUSEL_CARD_TITLE_MIN_LENGTH,
  VIBER_CAROUSEL_CARD_TITLE_MAX_LENGTH,
  VIBER_CAROUSEL_FIRST_BUTTON_TITLE_MAX_LENGTH,
  VIBER_CAROUSEL_SECOND_BUTTON_TITLE_MAX_LENGTH,
  VIBER_CAROUSEL_BUTTON_URL_MAX_LENGTH,
  VIBER_CAROUSEL_IMG_HEIGHT,
  VIBER_CAROUSEL_IMG_WIDTH,
  VIBER_CAROUSEL_IMG_SIZE,
} from './constants';
import withCreatives from '../../hoc/withCreatives';
import {
  CREATE, EDIT, TRACK_CREATE_VIBER, TRACK_EDIT_VIBER,
} from '../App/constants';
import { gtmPush } from '../../utils/gtmTrackers';
import { VIBER } from '../CreativesContainer/constants';
import { getCdnUrl } from '../../utils/cdnTransformation';
import { isAiContentBotDisabled } from '../../utils/common';
import globalMessages from '../Cap/messages';
import CapImageUpload from '../../v2Components/CapImageUpload';
import CapVideoUpload from '../../v2Components/CapVideoUpload';
import './index.scss';
import { ViberFooter } from './style';
import injectReducer from '../../utils/injectReducer';
import v2ViberReducer from './reducer';


const { TextArea } = CapInput;
const STATIC_URL = 'STATIC_URL';
const DYNAMIC_URL = 'DYNAMIC_URL';
const CAROUSEL_URL_TYPE_OPTIONS = (formatMessage) => ([
  { value: STATIC_URL, label: formatMessage(messages.carouselUrlTypeStatic) },
  { value: DYNAMIC_URL, label: formatMessage(messages.carouselUrlTypeDynamic) },
]);
let carouselCardIdSeed = 0;
const getNextCarouselCardId = () => {
  const nextId = `viber-carousel-card-${carouselCardIdSeed}`;
  carouselCardIdSeed += 1;
  return nextId;
};
const createEmptyCarouselButton = () => ({
  title: '',
  action: '',
  urlType: STATIC_URL,
  isSaved: false,
  hasAttemptedSave: false,
  hasTouchedAction: false,
});
const createEmptyCarouselCard = () => ({
  id: getNextCarouselCardId(),
  text: '',
  mediaUrl: '',
  buttons: [createEmptyCarouselButton()],
});
const createDefaultCarouselCards = () => [
  createEmptyCarouselCard(),
  createEmptyCarouselCard(),
];

export const Viber = (props) => {
  const {
    intl,
    isFullMode,
    injectedTags,
    location,
    metaEntities,
    globalActions: globalActionsProps,
    handleClose,
    onCreateComplete,
    params,
    templateData = {},
    actions,
    viber = {},
    getFormSubscriptionData,
    viberData = {},
    selectedOfferDetails = [],
    eventContextTags,
    waitEventContextTags,
    // TestAndPreviewSlidebox props
    showTestAndPreviewSlidebox: propsShowTestAndPreviewSlidebox,
    handleTestAndPreview: propsHandleTestAndPreview,
    handleCloseTestAndPreview: propsHandleCloseTestAndPreview,
  } = props || {};

  const { formatMessage } = intl;
  const [imageSrc, setImageSrc] = useState('');
  const [messageContent, updateTextMessageContent] = useState('');
  const [buttonText, updateButtonText] = useState('');
  const [buttonURL, updateButtonUrl] = useState('');
  const [errorMessageTextarea, updateErrorMessageTextArea] = useState(false);
  const [isEditLoading, updateEditLoading] = useState(false);
  const [isEditFlow, checkEditFlow] = useState(false);
  const [messageTitle, updateTextMessageTitle] = useState("");
  const [errorMessageTitle, updateErrorMessageTitle] = useState(false);
  const [buttonURLErrorMessage, updateButtonURLErrorMessage] = useState(false);
  const [accountName, updateAccountName] = useState("");
  const [showTestAndPreviewSlidebox, setShowTestAndPreviewSlidebox] = useState(false);
  const [templateMediaType, setTemplateMediaType] = useState(
    VIBER_MEDIA_TYPES.TEXT
  );
  const [assetList, updateAssetList] = useState([]);
  const [viberVideoSrcAndPreview, setViberVideoSrcAndPreview] = useState({
    viberVideoSrc: '',
    viberVideoPreviewImg: '',
    duration: 0,
  });
  const [carouselCards, setCarouselCards] = useState(() => createDefaultCarouselCards());
  const [activeCarouselCardIndex, setActiveCarouselCardIndex] = useState(0);
  const [showCarouselValidationErrors, setShowCarouselValidationErrors] = useState(false);
  // cta button
  const [buttonType, setButtonType] = useState(NONE);
  const [ctaData, setCtadata] = useState({});
  const [isCtaSaved, setIsCtaSaved] = useState(false);
  const aiContentBotDisabled = isAiContentBotDisabled();

  const updateImageSrc = React.useCallback((url) => {
    const newUrl = getCdnUrl({url, channelName: 'VIBER'});
    setImageSrc(newUrl);
  }, []);

  const paramObj = params || {};
  useEffect(() => {
    const { id } = paramObj;
    if (id && !get(templateData, `versions.base.content`)) {
      updateEditLoading(true);
      actions.getTemplateDetails(id, updateEditLoading);
      checkEditFlow(true);
    }
  }, [paramObj.id]);

  useEffect(() => {
    const { name = '' } = viberData.selectedViberAccount || {};
    updateAccountName(name);
  }, [viberData.selectedViberAccount]);

  useEffect(() => {
    if ((params && params.id) || (templateData || {}).edit) {
      const { content: editViberContent = {} } = get(templateData, `versions.base.content`)
        || get(viber, `templateDetails.versions.base.content`)
        || {};
      const editMessageTitle = (templateData || {}).name || get(viber, "templateDetails.name");
      const {
        text = "",
        button = {},
        image = {},
        video = {},
        cards = [],
        type = "",
      } = editViberContent || {};
      const { text: ctaBtnText = "", url = "" } = button || {};
      updateTextMessageTitle(editMessageTitle);
      updateTextMessageContent(text || "");
      updateButtonText(ctaBtnText);
      updateButtonUrl(url);
      setIsCtaSaved(!isEmpty(button));
      setButtonType(button?.text ? VIBER_BUTTON_TYPES.CTA : NONE);
      setCtadata(!isEmpty(button) ? { buttonText: button?.text, buttonURL: button?.url } : {});
      if (type === VIBER_MEDIA_TYPES.CAROUSEL) {
        const normalizedCards = (cards || []).map((card) => ({
          id: card?.id || getNextCarouselCardId(),
          text: card?.text || '',
          mediaUrl: card?.mediaUrl || '',
          buttons: ((card?.buttons || []).length ? card.buttons : [createEmptyCarouselButton()]).map((carouselButton) => ({
            title: carouselButton?.title || '',
            action: carouselButton?.action || '',
            urlType: carouselButton?.urlType || STATIC_URL,
            isSaved: Boolean(carouselButton?.title && carouselButton?.action),
            hasAttemptedSave: Boolean(carouselButton?.hasAttemptedSave),
            hasTouchedAction: Boolean(carouselButton?.hasTouchedAction),
          })),
        }));
        const cardsToSet = normalizedCards.length
          ? normalizedCards
          : createDefaultCarouselCards();
        setTemplateMediaType(VIBER_MEDIA_TYPES.CAROUSEL);
        setCarouselCards(cardsToSet.slice(0, VIBER_CAROUSEL_MAX_CARDS));
        setActiveCarouselCardIndex(0);
      } else if (!isEmpty(image)) {
        setTemplateMediaType(VIBER_MEDIA_TYPES.IMAGE);
        updateImageSrc(image?.url);
      } else if (!isEmpty(video)) {
        setTemplateMediaType(VIBER_MEDIA_TYPES.VIDEO);
        setViberVideoSrcAndPreview({
          viberVideoSrc: video?.url,
          viberVideoPreviewImg: video?.thumbnailUrl,
          duration: video?.duration,
        });
        updateAssetList({
          ...assetList,
          previewUrl: video?.thumbnailUrl,
          videoSrc: video?.url,
          videoDuration: video?.duration,
        });
      } else {
        setTemplateMediaType(VIBER_MEDIA_TYPES.TEXT);
      }
    }
  }, [viber.templateDetails || templateData]);

  // Text area Code start here

  // Tags Code start from here
  useEffect(() => {
    const type = location && location.query && location.query.type;
    const getTagsQuery = {
      layout: 'LINE',
      type: 'TAG',
      context: type ? 'outbound' : 'default',
      embedded: type || 'full',
    };
    globalActionsProps.fetchSchemaForEntity(getTagsQuery);
  }, []);

  const onTagSelect = (data) => {
    // update message content
    const messageData = `${messageContent}{{${data}}}`;
    updateTextMessageContent(messageData);
    updateTextContentError(messageData);
  };

  const onButtonTagSelect = (data) => {
    const newUrl = `${buttonURL}{{${data}}}`;
    updateButtonUrl(newUrl);
    onChangeButtonUrl({ target: { value: newUrl } });
  };
  const onCarouselCardTagSelect = (cardIndex, data) => {
    setCarouselCards((prevCards) => prevCards.map((card, index) => {
      if (index !== cardIndex) {
        return card;
      }
      return {
        ...card,
        text: `${card?.text || ''}{{${data}}}`,
      };
    }));
  };

  const handleOnTagsContextChange = (data) => {
    const query = {
      layout: 'LINE',
      type: 'TAG',
      context:
            (data || '').toLowerCase() === 'all' ? 'default' : (data || '').toLowerCase(),
      embedded:
            location.query.type === 'embedded'
              ? location.query.type
              : 'full',
    };
    globalActionsProps.fetchSchemaForEntity(query);
  };

  const tags = metaEntities?.tags?.standard || [];
  // tags Code end here

  // validation on Text area and tags validation
  const updateTextContentError = (value) => {
    let errorMessage = false;
    const { valid, isBraceError } = validateTags({
      content: value,
      tagsParam: tags,
      location,
      tagModule: 'outbound',
      isFullMode,
    }) || {};
    if (value.trim() === '') {
      errorMessage = formatMessage(messages.emptyContentErrorMessage);
    } else if (value.length > charLimit) {
      errorMessage = formatMessage(messages.limitExceededContentErrorMessage);
    } else if (isBraceError) {
      errorMessage = formatMessage(globalMessages.unbalanacedCurlyBraces);
    } else if (!valid) {
      errorMessage = formatMessage(messages.invalidTagError);
    }
    updateErrorMessageTextArea(errorMessage);
  };

  // on change event of Text Area
  const onTextContentChange = ({ target: { value } }) => {
    updateTextMessageContent(value);
    updateTextContentError(value);
  };

  const onTextTitleChange = ({ target: { value } }) => {
    updateTextMessageTitle(value);
    updateTextTitleError(value);
  };

  const updateTextTitleError = (value) => {
    let errorMessage = false;
    if (value === '') {
      errorMessage = formatMessage(messages.emptyTitleErrorMessage);
    }
    updateErrorMessageTitle(errorMessage);
  };
  // Text Area container
  const renderTextAreaViber = () => (
    <>
      <CapColumn className="viber-message-header">
        <CapHeading type="h5" className="viber-message-header-style">
          {formatMessage(messages.message)}
        </CapHeading>
        <TagList
          key="viber_tags"
          className="tag-list-viber"
          moduleFilterEnabled={
            location?.query?.type !== "embedded"
          }
          label={formatMessage(messages.addLabels)}
          onTagSelect={onTagSelect}
          onContextChange={handleOnTagsContextChange}
          location={location}
          tags={tags}
          injectedTags={injectedTags || {}}
          id="viber_tags"
          userLocale={localStorage.getItem("jlocale") || "en"}
          selectedOfferDetails={selectedOfferDetails}
          eventContextTags={eventContextTags}
          waitEventContextTags={waitEventContextTags}
        />
      </CapColumn>
      <div className="viber-textarea-wrapper">
        <TextArea
          id="viber_textarea"
          autosize={false}
          onChange={onTextContentChange}
          className={`${errorMessageTextarea ? "error" : ""}`}
          errorMessage={errorMessageTextarea}
          defaultValue={messageContent || ""}
          value={messageContent || ""}
          rows={5}
          cols={2}
          placeholder={formatMessage(messages.enterMessage)}
        />
        {!aiContentBotDisabled && (
          <CapAskAira.ContentGenerationBot
            text={messageContent || ""}
            setText={(text) => {
              onTextContentChange({ target: { value: text } });
            }}
            iconPlacement="float-br"
            iconSize="1.6rem"
            rootStyle={{
              bottom: "0.2rem",
              right: "0.2rem",
              left: "auto",
              position: "absolute",
            }}
          />
        )}
      </div>
      <CapLabel type="label1" className="char-count-viber">
        <FormattedMessage {...messages.charCount} />
        {(messageContent || "").length}
/
        {charLimit}
        {" "}
      </CapLabel>
    </>
  );
  // Text area Code End here

  // template media code start here
  const isMediaTypeImage = templateMediaType === VIBER_MEDIA_TYPES.IMAGE;
  const isMediaTypeVideo = templateMediaType === VIBER_MEDIA_TYPES.VIDEO;
  const isMediaTypeCarousel = templateMediaType === VIBER_MEDIA_TYPES.CAROUSEL;
  const getCarouselButtonTitleMaxLength = (buttonIndex) => (
    buttonIndex === 0
      ? VIBER_CAROUSEL_FIRST_BUTTON_TITLE_MAX_LENGTH
      : VIBER_CAROUSEL_SECOND_BUTTON_TITLE_MAX_LENGTH
  );
  const renderLength = (len, max) => (
    <CapHeading type="label1" className="viber-carousel-field-length-top">
      {len || 0}
/
      {max}
      {' '}
      <FormattedMessage {...messages.characters} />
    </CapHeading>
  );
  const getCarouselCardTextError = (cardText = '', showEmptyError = true) => {
    const trimmedCardText = (cardText || '').trim();
    if (!trimmedCardText && showEmptyError) {
      return formatMessage(messages.textCannotBeEmptyError);
    }
    if (!trimmedCardText) {
      return false;
    }
    if (trimmedCardText?.length < VIBER_CAROUSEL_CARD_TITLE_MIN_LENGTH) {
      return formatMessage(messages.carouselCardTitleMinLengthError);
    }
    if (cardText.length > VIBER_CAROUSEL_CARD_TITLE_MAX_LENGTH) {
      return formatMessage(messages.carouselCardTitleMaxLengthError);
    }
    return false;
  };
  const getCarouselButtonTitleError = (button = {}, buttonIndex = 0, showEmptyError = true) => {
    const title = button?.title || '';
    const trimmedTitle = title.trim();
    const maxLength = getCarouselButtonTitleMaxLength(buttonIndex);
    if (!trimmedTitle && showEmptyError) {
      return formatMessage(messages.textCannotBeEmptyError);
    }
    if (!trimmedTitle) {
      return false;
    }
    if (title.length > maxLength) {
      return buttonIndex === 0
        ? formatMessage(messages.carouselFirstButtonTitleMaxLengthError)
        : formatMessage(messages.carouselSecondButtonTitleMaxLengthError);
    }
    return false;
  };
  const getCarouselButtonActionError = (button = {}, showEmptyError = true) => {
    const action = button?.action || '';
    if (!action?.trim() && showEmptyError) {
      return formatMessage(messages.urlCannotBeEmptyError);
    }
    if (!action?.trim()) {
      return false;
    }
    if (action.length > VIBER_CAROUSEL_BUTTON_URL_MAX_LENGTH) {
      return formatMessage(messages.carouselButtonUrlMaxLengthError);
    }
    if (!isUrl(action)) {
      return formatMessage(messages.inValidUrliErrorMessage);
    }
    return false;
  };
  const hasInvalidCarouselCard = carouselCards.some(
    (card) => Boolean(getCarouselCardTextError(card?.text)) || !isUrl(card?.mediaUrl || '')
  );
  const hasInvalidCarouselButton = carouselCards.some((card) => (card?.buttons || []).some(
    (button, buttonIndex) => {
      const hasAnyValue = Boolean(button?.title || button?.action);
      if (buttonIndex !== 0 && !hasAnyValue) {
        return false;
      }
      return Boolean(getCarouselButtonTitleError(button, buttonIndex))
        || Boolean(getCarouselButtonActionError(button))
        || !button?.isSaved;
    }
  ));
  const isCarouselCardCountInvalid = carouselCards.length < VIBER_CAROUSEL_MIN_CARDS
    || carouselCards.length > VIBER_CAROUSEL_MAX_CARDS;
  const isCarouselButtonComplete = (button, buttonIndex) => {
    const hasAnyValue = Boolean(button?.title || button?.action);
    if (buttonIndex !== 0 && !hasAnyValue) {
      return true;
    }
    return !getCarouselButtonTitleError(button, buttonIndex)
      && !getCarouselButtonActionError(button)
      && Boolean(button?.isSaved);
  };
  const isCarouselCardComplete = (card = {}) => (
    !getCarouselCardTextError(card?.text)
    && isUrl(card?.mediaUrl || '')
    && (card?.buttons || []).every((button, buttonIndex) => isCarouselButtonComplete(button, buttonIndex))
  );
  const canAccessCarouselCardAtIndex = (targetIndex) => (
    carouselCards.slice(0, targetIndex).every((card) => isCarouselCardComplete(card))
  );
  const isCarouselTabDisabled = (cardIndex) => (
    cardIndex > 0 && !canAccessCarouselCardAtIndex(cardIndex)
  );

  const onTemplateMediaTypeChange = ({ target: { value } }) => {
    setTemplateMediaType(value);
    if (value === VIBER_MEDIA_TYPES.CAROUSEL && carouselCards.length === 0) {
      setCarouselCards(createDefaultCarouselCards());
      setActiveCarouselCardIndex(0);
    }
    if ([VIBER_MEDIA_TYPES.VIDEO, VIBER_MEDIA_TYPES.CAROUSEL].includes(value)) {
      setButtonType(NONE);
      setCtadata({});
      updateButtonText('');
      updateButtonUrl('');
      setIsCtaSaved(false);
    }
  };

  const uploadViberAsset = (file, type, fileParams) => {
    actions.uploadViberAsset(file, type, fileParams, 0);
  };

  const uploadViberAssetByIndex = (file, type, fileParams, templateType = 0) => {
    actions.uploadViberAsset(file, type, fileParams, templateType);
  };

  const updateOnViberImageReUpload = useCallback(() => {
    setImageSrc("");
  }, [imageSrc]);

  const setUpdateViberImageSrc = useCallback(
    (val) => {
      setImageSrc(val);
      actions.clearViberAsset(0);
    },
    [imageSrc]
  );

  const setUpdateViberVideoSrc = useCallback(
    (index, data) => {
      const { videoSrc = "", previewUrl = "", videoDuration } = data;
      setViberVideoSrcAndPreview({
        viberVideoSrc: videoSrc,
        viberVideoPreviewImg: previewUrl,
        duration: videoDuration,
      });
      updateAssetList(data);
      actions.clearViberAsset(0);
    },
    [viberVideoSrcAndPreview?.viberVideoSrc]
  );

  const renderMediaSection = () => (
    <>
      <CapHeading type="h4" className="viber-render-heading">
        {formatMessage(messages.mediaLabel)}
      </CapHeading>
      <CapRadioGroup
        id="viber-media-radio"
        options={mediaRadioOptions}
        value={templateMediaType}
        onChange={onTemplateMediaTypeChange}
        className="viber-media-radio"
      />
    </>
  );

  const renderImageComponent = () => (
    <CapImageUpload
      allowedExtensionsRegex={ALLOWED_IMAGE_EXTENSIONS_REGEX_VIBER}
      imgSize={VIBER_IMG_SIZE}
      imgWidth={VIBER_IMG_WIDTH}
      imgHeight={VIBER_IMG_HEIGHT}
      uploadAsset={uploadViberAsset}
      isFullMode={isFullMode}
      imageSrc={imageSrc}
      updateImageSrc={setUpdateViberImageSrc}
      updateOnReUpload={updateOnViberImageReUpload}
      index={0}
      className="cap-custom-image-upload"
      key="viber-uploaded-image"
      imageData={viber}
      channel={VIBER}
    />
  );

  const renderVideoComonent = () => (
    <CapVideoUpload
      index={0}
      allowedExtensionsRegex={ALLOWED_EXTENSIONS_VIDEO_REGEX_VIBER}
      videoSize={VIBER_VIDEO_SIZE}
      isFullMode={isFullMode}
      uploadAsset={uploadViberAsset}
      uploadedAssetList={assetList}
      onVideoUploadUpdateAssestList={setUpdateViberVideoSrc}
      videoData={viber}
      className="cap-custom-video-upload"
      formClassName="viber-video-upload"
      channel={VIBER}
      errorMessage={formatMessage(messages.videoErrorMessage)}
      showVideoNameAndDuration
      assetUploading={viber?.assetUploading}
    />
  );

  const renderMediaComponent = () => (
    <>
      {isMediaTypeImage && renderImageComponent()}
      {isMediaTypeVideo && renderVideoComonent()}
    </>
  );
  // template media code end here

  const onCarouselCardChange = (cardIndex, key, value) => {
    setCarouselCards((prevCards) => prevCards.map((card, index) => (
      index === cardIndex ? { ...card, [key]: value } : card
    )));
  };

  const addCarouselCard = () => {
    if (carouselCards.length >= VIBER_CAROUSEL_MAX_CARDS) {
      return;
    }
    if (!isCarouselCardComplete(carouselCards[carouselCards.length - 1])) {
      return;
    }
    setCarouselCards((prevCards) => {
      const updatedCards = [...prevCards, createEmptyCarouselCard()];
      setActiveCarouselCardIndex(updatedCards.length - 1);
      return updatedCards;
    });
  };

  const removeCarouselCard = (cardIndex) => {
    if (carouselCards.length <= VIBER_CAROUSEL_MIN_CARDS) {
      return;
    }
    setCarouselCards((prevCards) => {
      const updatedCards = prevCards.filter((_, index) => index !== cardIndex);
      if (activeCarouselCardIndex >= updatedCards.length) {
        setActiveCarouselCardIndex(updatedCards.length - 1);
      } else if (activeCarouselCardIndex > cardIndex) {
        setActiveCarouselCardIndex(activeCarouselCardIndex - 1);
      }
      return updatedCards;
    });
  };

  const onCarouselTabChange = (cardIndex) => {
    const targetIndex = Number(cardIndex);
    if (Number.isNaN(targetIndex) || targetIndex < 0 || targetIndex >= carouselCards.length) {
      return;
    }
    if (isCarouselTabDisabled(targetIndex)) {
      return;
    }
    setActiveCarouselCardIndex(targetIndex);
  };

  const onCarouselButtonChange = (cardIndex, buttonIndex, key, value) => {
    setCarouselCards((prevCards) => prevCards.map((card, index) => {
      if (index !== cardIndex) {
        return card;
      }
      return {
        ...card,
        buttons: (card?.buttons || []).map((button, idx) => (
          idx === buttonIndex
            ? {
              ...button,
              [key]: value,
              isSaved: false,
              ...(key === 'action' && value?.trim() ? { hasTouchedAction: true } : {}),
            }
            : button
        )),
      };
    }));
  };

  const markCarouselButtonActionTouched = (cardIndex, buttonIndex) => {
    setCarouselCards((prevCards) => prevCards.map((card, index) => {
      if (index !== cardIndex) {
        return card;
      }
      return {
        ...card,
        buttons: (card?.buttons || []).map((button, idx) => (
          idx === buttonIndex ? { ...button, hasTouchedAction: true } : button
        )),
      };
    }));
  };

  const addCarouselButton = (cardIndex) => {
    setCarouselCards((prevCards) => prevCards.map((card, index) => {
      if (index !== cardIndex || (card?.buttons || []).length >= VIBER_CAROUSEL_MAX_BUTTONS) {
        return card;
      }
      return {
        ...card,
        buttons: [...(card?.buttons || []), createEmptyCarouselButton()],
      };
    }));
  };

  const removeCarouselButton = (cardIndex, buttonIndex) => {
    setCarouselCards((prevCards) => prevCards.map((card, index) => {
      if (index !== cardIndex) {
        return card;
      }
      const buttons = card?.buttons || [];
      if (buttons.length <= 1) {
        return card;
      }
      return {
        ...card,
        buttons: buttons.filter((_, idx) => idx !== buttonIndex),
      };
    }));
  };

  const canRemoveCarouselButton = (card) => (card?.buttons || []).length > 1;

  const saveCarouselButton = (cardIndex, buttonIndex) => {
    setCarouselCards((prevCards) => prevCards.map((card, index) => {
      if (index !== cardIndex) {
        return card;
      }
      return {
        ...card,
        buttons: (card?.buttons || []).map((button, idx) => {
          if (idx !== buttonIndex) {
            return button;
          }
          const nextButtonState = {
            ...button,
            hasAttemptedSave: true,
          };
          if (getCarouselButtonTitleError(nextButtonState, buttonIndex, true) || getCarouselButtonActionError(nextButtonState)) {
            return nextButtonState;
          }
          return {
            ...nextButtonState,
            isSaved: true,
          };
        }),
      };
    }));
  };

  const editCarouselButton = (cardIndex, buttonIndex) => {
    setCarouselCards((prevCards) => prevCards.map((card, index) => {
      if (index !== cardIndex) {
        return card;
      }
      return {
        ...card,
        buttons: (card?.buttons || []).map((button, idx) => (
          idx === buttonIndex ? { ...button, isSaved: false } : button
        )),
      };
    }));
  };

  const updateCarouselImageSrc = useCallback((cardIndex, url) => {
    const transformedUrl = getCdnUrl({ url, channelName: 'VIBER' });
    setCarouselCards((prevCards) => prevCards.map((card, index) => (
      index === cardIndex ? { ...card, mediaUrl: transformedUrl } : card
    )));
    actions.clearViberAsset(cardIndex);
  }, []);

  const updateOnCarouselImageReUpload = useCallback((cardIndex) => {
    setCarouselCards((prevCards) => prevCards.map((card, index) => (
      index === cardIndex ? { ...card, mediaUrl: '' } : card
    )));
    actions.clearViberAsset(cardIndex);
  }, []);

  const getCarouselTabPanes = () => (
    carouselCards.map((card, cardIndex) => {
      const isTabDisabled = isCarouselTabDisabled(cardIndex);
      return ({
      key: `${cardIndex}`,
      tab: (
        <span className={isTabDisabled ? 'viber-carousel-tab-label-disabled' : ''}>
          {cardIndex + 1}
        </span>
      ),
      disabled: isTabDisabled,
      content: (
        <div className="viber-carousel-card">
          <CapRow type="flex" justify="space-between" align="middle">
            <CapHeading type="h5">
              {formatMessage(messages.carouselCardHeading, { index: cardIndex + 1 })}
            </CapHeading>
            <CapButton
              type="flat"
              className="viber-carousel-delete-icon-btn"
              disabled={carouselCards.length <= VIBER_CAROUSEL_MIN_CARDS}
              onClick={() => removeCarouselCard(cardIndex)}
            >
              <CapIcon type="delete" size="s" />
            </CapButton>
          </CapRow>
          <CapImageUpload
            allowedExtensionsRegex={ALLOWED_IMAGE_EXTENSIONS_REGEX_VIBER}
            imgSize={VIBER_CAROUSEL_IMG_SIZE}
            imgWidth={VIBER_CAROUSEL_IMG_WIDTH}
            imgHeight={VIBER_CAROUSEL_IMG_HEIGHT}
            uploadAsset={uploadViberAssetByIndex}
            isFullMode={isFullMode}
            imageSrc={card?.mediaUrl || ''}
            updateImageSrc={(url) => updateCarouselImageSrc(cardIndex, url)}
            updateOnReUpload={() => updateOnCarouselImageReUpload(cardIndex)}
            index={cardIndex}
            className="cap-custom-image-upload"
            key={`viber-carousel-image-upload-${card?.id}`}
            imageData={viber}
            channel={VIBER}
          />
          {showCarouselValidationErrors && !isUrl(card?.mediaUrl || '') && (
            <CapLabel type="label3" className="viber-carousel-image-recommendation">
              Supported image types are .jpg, .jpeg, .png. Max size: 10 MB. Recommended resolution: 696 px x 600 px.
            </CapLabel>
          )}
          <CapRow className="viber-carousel-card-title-header" type="flex" justify="space-between">
            <CapHeading type="h5">
              {formatMessage(messages.carouselCardTextLabel)}
            </CapHeading>
            <TagList
              key={`viber_carousel_card_tags_${cardIndex}`}
              className="tag-list-viber"
              moduleFilterEnabled={location?.query?.type !== "embedded"}
              label={formatMessage(messages.addLabels)}
              onTagSelect={(data) => onCarouselCardTagSelect(cardIndex, data)}
              onContextChange={handleOnTagsContextChange}
              location={location}
              tags={tags}
              injectedTags={injectedTags || {}}
              id={`viber_carousel_card_tags_${cardIndex}`}
              userLocale={localStorage.getItem("jlocale") || "en"}
              selectedOfferDetails={selectedOfferDetails}
              eventContextTags={eventContextTags}
            />
          </CapRow>
          <CapInput
            value={card?.text || ''}
            onChange={({ target: { value } }) => onCarouselCardChange(cardIndex, 'text', value)}
            placeholder={formatMessage(messages.carouselCardTextPlaceholder)}
            errorMessage={getCarouselCardTextError(card?.text, showCarouselValidationErrors)}
          />
          {renderLength((card?.text || '').length, VIBER_CAROUSEL_CARD_TITLE_MAX_LENGTH)}
          <CapHeading type="h5" className="viber-carousel-button-label">
            {formatMessage(messages.btnLabel)}
          </CapHeading>
          {(card?.buttons || []).map((button, buttonIndex) => (
            // eslint-disable-next-line react/no-array-index-key
            <div className="viber-carousel-button" key={`carousel-button-${card?.id}-${buttonIndex}`}>
              {button?.isSaved ? (
                <CapRow className="viber-carousel-saved-button" align="middle" type="flex">
                  <CapIcon size="s" type="six-dots" className="viber-carousel-saved-button-icon" />
                  <CapIcon size="s" type="reply" className="viber-carousel-saved-button-icon" />
                  <CapLabel type="label4" className="viber-carousel-saved-button-text">
                    {button?.title}
                  </CapLabel>
                  <CapRow className="viber-carousel-saved-button-actions" align="middle" type="flex">
                    <CapColumn className="button-edit-icon" onClick={() => editCarouselButton(cardIndex, buttonIndex)}>
                      <CapIcon type="edit" size="s" />
                    </CapColumn>
                    {canRemoveCarouselButton(card) && (
                      <CapColumn
                        className="button-edit-icon viber-carousel-delete-icon"
                        onClick={() => removeCarouselButton(cardIndex, buttonIndex)}
                      >
                        <CapIcon type="delete" size="s" />
                      </CapColumn>
                    )}
                  </CapRow>
                </CapRow>
              ) : (
                <div className="cta-section">
                  <CapRow
                    type="flex"
                    justify="space-between"
                    align="middle"
                    className="viber-carousel-button-title-header"
                  >
                    <CapHeading type="h5">
                      {formatMessage(messages.carouselButtonTitleLabel)}
                    </CapHeading>
                  </CapRow>
                  <CapInput
                    value={button?.title ?? ''}
                    onChange={({ target: { value } }) => onCarouselButtonChange(cardIndex, buttonIndex, 'title', value)}
                    placeholder={formatMessage(messages.carouselButtonTitlePlaceholder)}
                    errorMessage={getCarouselButtonTitleError(
                      button,
                      buttonIndex,
                      showCarouselValidationErrors || Boolean(button?.hasAttemptedSave),
                    )}
                  />
                  {renderLength((button?.title || '').length, getCarouselButtonTitleMaxLength(buttonIndex))}
                  <CapRow gutter={12}>
                    <CapColumn span={6}>
                      <CapHeading type="h4" className="cta-label">
                        {formatMessage(messages.carouselButtonUrlTypeLabel)}
                      </CapHeading>
                      <CapSelect
                        className="viber-carousel-url-type-select"
                        dropdownClassName="viber-carousel-url-type-dropdown"
                        dropdownMatchSelectWidth={false}
                        options={CAROUSEL_URL_TYPE_OPTIONS(formatMessage)}
                        value={button?.urlType || STATIC_URL}
                        onChange={(value) => onCarouselButtonChange(cardIndex, buttonIndex, 'urlType', value)}
                      />
                    </CapColumn>
                    <CapColumn span={18}>
                      <CapInput
                        label={formatMessage(messages.carouselButtonActionLabel)}
                        value={button?.action ?? ''}
                        onChange={({ target: { value } }) => onCarouselButtonChange(cardIndex, buttonIndex, 'action', value)}
                        onBlur={() => markCarouselButtonActionTouched(cardIndex, buttonIndex)}
                        placeholder={formatMessage(messages.carouselButtonActionPlaceholder)}
                        errorMessage={getCarouselButtonActionError(
                          button,
                          showCarouselValidationErrors
                            || Boolean(button?.hasAttemptedSave)
                            || Boolean(button?.hasTouchedAction),
                        )}
                      />
                    </CapColumn>
                  </CapRow>
                  <div className="cta-actions">
                    <CapButton
                      className="cta-btn-action"
                      onClick={() => saveCarouselButton(cardIndex, buttonIndex)}
                    >
                      {formatMessage(messages.save)}
                    </CapButton>
                    {canRemoveCarouselButton(card) && (
                      <CapButton
                        type="secondary"
                        onClick={() => removeCarouselButton(cardIndex, buttonIndex)}
                      >
                        {formatMessage(globalMessages.delete)}
                      </CapButton>
                    )}
                  </div>
                </div>
              )}
            </div>
          ))}
          {(card?.buttons || []).length < VIBER_CAROUSEL_MAX_BUTTONS && (
            <CapButton
              type="flat"
              className="viber-add-row-btn"
              onClick={() => addCarouselButton(cardIndex)}
            >
              + Add Button
            </CapButton>
          )}
        </div>
      ),
      });
    })
  );

  const carouselTabOperations = (
    <>
      <CapDivider type="vertical" />
      <CapButton
        type="flat"
        className="viber-carousel-tab-add-btn"
        onClick={addCarouselCard}
        disabled={
          carouselCards.length >= VIBER_CAROUSEL_MAX_CARDS
          || !isCarouselCardComplete(carouselCards[carouselCards.length - 1])
        }
      >
        <CapIcon type="plus" />
      </CapButton>
    </>
  );

  const renderCarouselSection = () => (
    <div className="viber-carousel-section">
      <CapHeading type="h4" className="viber-render-heading">
        {formatMessage(messages.carouselCardsLabel)}
      </CapHeading>
      <CapRow className="viber-carousel-tab">
        <CapTab
          activeKey={`${activeCarouselCardIndex}`}
          tabBarExtraContent={carouselTabOperations}
          onChange={onCarouselTabChange}
          panes={getCarouselTabPanes()}
        />
      </CapRow>
      {isCarouselCardCountInvalid && (
        <CapLabel type="label3" className="viber-form-error">
          {formatMessage(messages.carouselCardsLimitError)}
        </CapLabel>
      )}
      {hasInvalidCarouselCard && (
        <CapLabel type="label3" className="viber-form-error">
          {formatMessage(messages.carouselCardError)}
        </CapLabel>
      )}
      {hasInvalidCarouselButton && (
        <CapLabel type="label3" className="viber-form-error">
          {formatMessage(messages.carouselButtonError)}
        </CapLabel>
      )}
    </div>
  );

  const renderInteractiveSection = () => (
    <>
      {isMediaTypeCarousel && renderCarouselSection()}
    </>
  );

  // Button Code start here

  const isBtnTypeCta = buttonType === VIBER_BUTTON_TYPES.CTA;
  const onChangeButtonText = ({ target: { value } }) => {
    updateButtonText(value);
  };

  const onChangeButtonUrl = ({ target: { value } }) => {
    let errorMessage = false;
    updateButtonUrl(value);
    if (!isUrl(value)) {
      errorMessage = formatMessage(messages.inValidUrliErrorMessage);
    }
    updateButtonURLErrorMessage(errorMessage);
  };
  const getPreviewSection = () => (
    // const accountName = get(lineData, 'selectedLineAccount.name', '');
    <UnifiedPreview
      channel={VIBER}
      content={{
        viberPreviewContent: {
          ...(isMediaTypeImage && { imageURL: imageSrc }),
          ...(isMediaTypeVideo && { videoParams: viberVideoSrcAndPreview }),
          ...(isMediaTypeCarousel && {
            cards: carouselCards,
            type: VIBER_MEDIA_TYPES.CAROUSEL,
            showCarouselEditorPreview: true,
          }),
          buttonText,
          messageContent,
        },
        accountName: (accountName[0] || "").toUpperCase(),
        brandName: accountName,
      }}
      device={ANDROID}
      showDeviceToggle={false}
      showHeader={false}
      formatMessage={formatMessage}
    />
  );

  // Get template content for Test and Preview
  // This function returns data for both preview and payload building
  // - viberPreviewContent: Used by preview component
  // - Other fields: Used by payload function for test message
  const getTemplateContent = useCallback(() => {
    const templateContent = {
      // Preview structure (for ViberPreviewContent component)
      viberPreviewContent: {
        ...(isMediaTypeImage && { imageURL: imageSrc }),
        ...(isMediaTypeVideo && { videoParams: viberVideoSrcAndPreview }),
        ...(isMediaTypeCarousel && {
          cards: carouselCards,
          type: VIBER_MEDIA_TYPES.CAROUSEL,
          showCarouselEditorPreview: true,
        }),
        buttonText: ctaData?.buttonText || buttonText,
        messageContent,
      },
      // Account info for preview
      accountName: (accountName[0] || "").toUpperCase(),
      brandName: accountName,
      // Payload fields (for test message API)
      messageContent,
      // Add image if present (for payload)
      ...(isMediaTypeImage && imageSrc && {
        image: {
          url: imageSrc,
        },
      }),
      // Add video if present (for payload)
      ...(isMediaTypeVideo && viberVideoSrcAndPreview.viberVideoSrc && {
        video: {
          url: viberVideoSrcAndPreview.viberVideoSrc,
          thumbnailUrl: viberVideoSrcAndPreview.viberVideoPreviewImg,
          duration: viberVideoSrcAndPreview.duration,
        },
      }),
      ...(isMediaTypeCarousel && {
        type: VIBER_MEDIA_TYPES.CAROUSEL,
        cards: carouselCards.map((card) => ({
          text: card?.text ?? '',
          mediaUrl: card?.mediaUrl ?? '',
          buttons: (card?.buttons ?? []).map((button) => ({
            title: button?.title ?? '',
            action: button?.action ?? '',
          })),
        })),
      }),
      // Add button if present (for payload)
      ...(!isMediaTypeCarousel && (ctaData?.buttonText || buttonText) && (ctaData?.buttonURL || buttonURL) && {
        button: {
          text: ctaData?.buttonText || buttonText,
          url: ctaData?.buttonURL || buttonURL,
        },
      }),
      // Add buttonURL separately for payload function to access
      buttonURL: ctaData?.buttonURL || buttonURL,
      // Add account info (for payload)
      accountId: viberData?.selectedViberAccount?.id || null,
      accountDetails: viberData?.selectedViberAccount ? JSON.stringify(viberData.selectedViberAccount) : null,
      scenarioKey: viberData?.selectedViberAccount?.scenarioKey || 'viber-api',
      // Add delivery settings (for payload)
      domainGatewayMapId: viberData?.selectedViberAccount?.domainGatewayMapId || 0,
      domainId: viberData?.selectedViberAccount?.domainId || 0,
      sender: viberData?.selectedViberAccount?.sender || 'test1',
    };
    return templateContent;
  }, [
    isMediaTypeImage,
    isMediaTypeVideo,
    isMediaTypeCarousel,
    imageSrc,
    viberVideoSrcAndPreview,
    carouselCards,
    ctaData,
    buttonText,
    buttonURL,
    messageContent,
    accountName,
    viberData,
  ]);

  // Handle Test and Preview button click
  const handleTestAndPreview = useCallback(() => {
    setShowTestAndPreviewSlidebox(true);
    if (propsHandleTestAndPreview) {
      propsHandleTestAndPreview();
    }
  }, [propsHandleTestAndPreview]);

  // Handle close Test and Preview slidebox
  const handleCloseTestAndPreview = useCallback(() => {
    setShowTestAndPreviewSlidebox(false);
    if (propsHandleCloseTestAndPreview) {
      propsHandleCloseTestAndPreview();
    }
  }, [propsHandleCloseTestAndPreview]);

  const handleSaveCta = () => {
    setCtadata({ buttonText, buttonURL });
    setIsCtaSaved(true);
  };

  const handleEditCta = () => {
    setIsCtaSaved(false);
    updateButtonText(ctaData?.buttonText);
    updateButtonUrl(ctaData?.buttonURL);
  };

  const handleCancelCta = () => {
    if (isEmpty(ctaData)) {
      setButtonType(NONE);
    } else {
      setIsCtaSaved(true);
    }
  };

  const isCtaSaveDisabled = isEmpty(buttonText.trim())
    || isEmpty(buttonURL.trim())
    || buttonURLErrorMessage;

  const ButtonViber = !isCtaSaved ? (
    <div className="cta-section">
      <CapHeading type="h4" className="button-text">
        {formatMessage(messages.buttonText)}
        <CapTooltip title={formatMessage(messages.buttonTextTooltip)}>
          <CapIcon type="info" size="s" />
        </CapTooltip>
      </CapHeading>
      <CapInput
        id="viber-button-text"
        className="cta-text-input"
        type="input"
        onChange={onChangeButtonText}
        defaultValue={buttonText}
        value={buttonText}
        maxLength={20}
        placeholder={formatMessage(messages.enterButtonText)}
      />
      <CapTagListWithInput
        inputId="viber-button-url"
        inputValue={buttonURL}
        inputOnChange={onChangeButtonUrl}
        inputPlaceholder={formatMessage(messages.enterButtonUrl)}
        inputErrorMessage={buttonURLErrorMessage}
        headingText={formatMessage(messages.buttonUrl)}
        headingStyle={{ marginTop: '3%', marginRight: '68%'}}
        className="tag-list-viber"
        moduleFilterEnabled={location?.query?.type !== "embedded"}
        onTagSelect={onButtonTagSelect}
        onContextChange={handleOnTagsContextChange}
        location={location}
        tags={tags}
        injectedTags={injectedTags || {}}
        userLocale={localStorage.getItem("jlocale") || "en"}
        selectedOfferDetails={selectedOfferDetails}
        eventContextTags={eventContextTags}
        waitEventContextTags={waitEventContextTags}
      />
      <CapColumn className="cta-actions">
        <CapButton
          disabled={isCtaSaveDisabled}
          className="cta-btn-action"
          onClick={handleSaveCta}
        >
          {formatMessage(messages.save)}
        </CapButton>
        <CapButton type="secondary" className="cta-btn-action" onClick={handleCancelCta}>
          {formatMessage(messages.cancel)}
        </CapButton>
      </CapColumn>
    </div>
  ) : (
    <CapRow className="cta-section-saved">
      <CapLabel type="label4" className="cta-text">
        {ctaData?.buttonText}
      </CapLabel>
      <CapLabel type="label2" className="button-url">
        {ctaData?.buttonURL}
      </CapLabel>
      <CapColumn className="button-edit-icon" onClick={handleEditCta}>
        <CapIcon type="edit" size="s" aria-label="edit-cta-icon"></CapIcon>
      </CapColumn>
    </CapRow>
  );

  const onChangeButtonType = ({ target: { value } }) => {
    setButtonType(value);
    setCtadata({});
    updateButtonText("");
    updateButtonUrl("");
    setIsCtaSaved(false);
  };

  const renderButtonsSection = () => {
    if (isMediaTypeCarousel) {
      return null;
    }
    return (
      <div className="button-section">
        <CapHeader
          className="viber-render-heading"
          title={(
            <CapRow type="flex">
              <CapHeading type="h4">
                {formatMessage(messages.btnLabel)}
              </CapHeading>
              <CapHeading className="viber-optional-label">
                {formatMessage(messages.optional)}
              </CapHeading>
            </CapRow>
          )}
          description={
            <CapLabel type="label3">{formatMessage(messages.btnDesc)}</CapLabel>
          }
        />
        {templateMediaType === VIBER_MEDIA_TYPES.VIDEO && (
          <CapLabel type="label3">
            {formatMessage(messages.videoButtonDisabled)}
          </CapLabel>
        )}
        <CapRadioGroup
          options={buttonRadioOptions}
          value={buttonType}
          onChange={onChangeButtonType}
          disabled={templateMediaType === VIBER_MEDIA_TYPES.VIDEO}
          className="viber-btn-radio-group"
        />
        {isBtnTypeCta && ButtonViber}
      </div>
    );
  };
  // Button Code End here

  // to generate payload for create and edit
  const formatSubmitPayload = () => {
    const messageData = {
      text: messageContent,
    };
    if (isMediaTypeImage) {
      messageData.image = {};
      messageData.image.url = imageSrc;
    }
    if (isMediaTypeVideo) {
      const { viberVideoSrc, duration, viberVideoPreviewImg } = viberVideoSrcAndPreview;
      messageData.video = {};
      messageData.video.url = viberVideoSrc;
      messageData.video.thumbnailUrl = viberVideoPreviewImg;
      messageData.video.duration = duration; // integer value in seconds
    }
    if (isMediaTypeCarousel) {
      messageData.type = VIBER_MEDIA_TYPES.CAROUSEL;
      messageData.cards = carouselCards.map((card) => ({
        text: card?.text ?? '',
        mediaUrl: card?.mediaUrl ?? '',
        buttons: (card?.buttons ?? []).map((button) => ({
          title: button?.title ?? '',
          action: button?.action ?? '',
        })),
      }));
    }

    if (!isMediaTypeCarousel && !isEmpty(ctaData)) {
      messageData.button = {};
      messageData.button.text = ctaData?.buttonText;
      messageData.button.url = ctaData?.buttonURL;
    }
    return {
      versions: {
        base: {
          content: {
            ...(isMediaTypeCarousel && {
              destinations: [
                {
                  to: {
                    phoneNumber: "{{viber_user_id}}",
                  },
                },
              ],
            }),
            content: {...messageData},
          },
        },
      },
      type: "VIBER",
      name: messageTitle,
    };
  };

  const createCallback = ({ errorMessage, resp }, isEdit) => {
    if (!errorMessage) {
      CapNotification.success({
        message: isEdit ? formatMessage(messages.viberEditNotification) : formatMessage(messages.viberCreateNotification),
      });
      if (isEdit) {
        actions.clearEditResponse();
      } else {
        actions.clearCreateResponse();
      }
      const timeTaken = GA.timeTracker.stopTimer(isEdit ? TRACK_EDIT_VIBER : TRACK_CREATE_VIBER, {
        category: 'Creatives',
        action: isEdit ? TRACK_EDIT_VIBER : TRACK_CREATE_VIBER,
      });
      gtmPush('creativeDetails', {
        id: resp.templateId._id || resp.templateId,
        name: messageTitle,
        channel: VIBER,
        timeTaken,
        content: messageContent,
        mode: isEdit ? EDIT : CREATE,
      });
    } else {
      CapNotification.error({
        message: errorMessage,
      });
    }
  };

  const onCreateViber = () => {
    actions.createTemplate(
      formatSubmitPayload(),
      (resp, errorMessage) => {
        createCallback({resp, errorMessage});
        if (!errorMessage) {
          onCreateComplete();
        }
      }
    );
  };

  const onEditViber = () => {
    actions.editTemplate(
      {
        ...formatSubmitPayload(),
        _id: params.id,
      },
      (resp, errorMessage) => {
        createCallback({resp, errorMessage}, true);
        if (!errorMessage) {
          onCreateComplete();
        }
      }
    );
  };

  const onDoneCallback = () => {
    if (isFullMode) {
      if (isEditFlow) {
        return onEditViber;
      }
      return onCreateViber;
    }
    return () => getFormSubscriptionData({
      value: formatSubmitPayload(),
      _id: params && params.id,
      validity: true,
      type: 'VIBER',
    });
  };

  const hasCarouselValidationError = isCarouselCardCountInvalid || hasInvalidCarouselCard || hasInvalidCarouselButton;
  const getDoneHandler = () => {
    const doneCallback = onDoneCallback();
    return () => {
      if (isMediaTypeCarousel) {
        setShowCarouselValidationErrors(true);
        if (hasCarouselValidationError) {
          return;
        }
      }
      doneCallback();
    };
  };

  const isDisableDone = () => {
    // textbox area should not empty and should have max 1000 charactor
    if (messageContent?.trim() === '' || errorMessageTextarea) {
      return true;
    }
    //if template title is empty
    if (isFullMode && messageTitle?.trim() === '') {
      return true;
    }
    // if media type is image/video than image/video should be uploaded
    if (
      (isMediaTypeImage && !imageSrc)
      || (isMediaTypeVideo && !viberVideoSrcAndPreview.viberVideoSrc)
    ) {
      return true;
    }
    // block submit while a media asset upload is still in progress
    if ((isMediaTypeImage || isMediaTypeVideo) && viber?.assetUploading) {
      return true;
    }
    if (isMediaTypeCarousel && (isCarouselCardCountInvalid || hasInvalidCarouselCard || hasInvalidCarouselButton)) {
      return true;
    }
    if (isBtnTypeCta && !isCtaSaved) {
      return true;
    }
    return false;
  };

  return (
    <>
      <CapSpin spinning={isEditLoading}>
        <CapRow>
          <CapColumn span={14}>
            {isFullMode ? (
              <CapInput
                id="viber_input"
                onChange={onTextTitleChange}
                errorMessage={errorMessageTitle}
                placeholder={formatMessage(
                  messages.textMessageTitlePlaceholder
                )}
                defaultValue={messageTitle || ""}
                value={messageTitle || ""}
                size="default"
                label={formatMessage(messages.textMessageTitleLabel)}
                data-testid="template_name"
              />
            ) : null}
            {renderMediaSection()}
            {renderMediaComponent()}
            {renderTextAreaViber()}
            {renderInteractiveSection()}
            {renderButtonsSection()}
            <div style={{marginBottom: '100px'}} />
          </CapColumn>
          <CapColumn span={8}>
            <CapRow>
              <CapColumn span={24} offset={4}>
                {getPreviewSection()}
                <CapHeading
                  type="h3"
                  style={{margin: '24px 0px 0px 28px'}}
                >
                  <FormattedMessage {...messages.message} />
:
                  {" "}
                  (
                  {(messageContent || '').length}
/
                  {charLimit}
                  {' '}
                  {" "}
                  <FormattedMessage {...messages.characters} />
)
                </CapHeading>
              </CapColumn>
            </CapRow>
          </CapColumn>
        </CapRow>
        <ViberFooter>
          <CapButton
            onClick={getDoneHandler()}
            disabled={isDisableDone()}
            className="create-msg viber-create-msg"
          >
            <FormattedMessage {...messages.doneButtonLabel} />
          </CapButton>
          <CapButton
            onClick={handleTestAndPreview}
            className="test-and-preview-button"
            type="secondary"
          >
            <FormattedMessage {...creativesMessages.testAndPreview} />
          </CapButton>
        </ViberFooter>
      </CapSpin>
      {/* Test and Preview Slidebox */}
      <TestAndPreviewSlidebox
        show={showTestAndPreviewSlidebox || propsShowTestAndPreviewSlidebox}
        onClose={handleCloseTestAndPreview}
        channel={VIBER}
        formData={getTemplateContent()} // Pass templateContent as formData (contains all payload fields)
        content={getTemplateContent()} // Also pass as content for preview (contains viberPreviewContent)
        formatMessage={formatMessage}
      />
    </>
  );
};

const mapStateToProps = createStructuredSelector({
  metaEntities: makeSelectMetaEntities(),
  injectedTags: setInjectedTags(),
  viberData: makeSelectViber(),
  viber: makeSelectCreateViber(),
});

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

const withReducer = injectReducer({ key: 'viber', reducer: v2ViberReducer });

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