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 ConfigProvider from 'antd/lib/config-provider';
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,
} 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;

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,
  });
  // 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 = {},
      } = editViberContent || {};
      const { text: ctaBtnText = "", url = "" } = button || {};
      updateTextMessageTitle(editMessageTitle);
      updateTextMessageContent(text || "");
      updateButtonText(ctaBtnText);
      updateButtonUrl(url);
      setIsCtaSaved(true);
      setButtonType(button?.text ? VIBER_BUTTON_TYPES.CTA : NONE);
      if (!isEmpty(button)) {
        setCtadata({ buttonText: button?.text, buttonURL: button?.url });
      }
      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 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 onTemplateMediaTypeChange = ({ target: { value } }) => {
    setTemplateMediaType(value);
  };

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

  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>
      <ConfigProvider theme={{ components: { Radio: { radioSize: 20, dotSize: 8 } } }}>
        <CapRadioGroup
          id="viber-media-radio"
          options={mediaRadioOptions}
          value={templateMediaType}
          onChange={onTemplateMediaTypeChange}
          className="viber-media-radio"
        />
      </ConfigProvider>
    </>
  );

  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

  // 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 }),
          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 }),
        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,
        },
      }),
      // Add button if present (for payload)
      ...((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, imageSrc, viberVideoSrcAndPreview, 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">
      <CapRow type="flex" align="middle" justify="start" gap={4}>
        <CapHeading type="h4" className="button-text">
          {formatMessage(messages.buttonText)}
        </CapHeading>
        <CapTooltip title={formatMessage(messages.buttonTextTooltip)}>
          <CapIcon type="info" size="s" />
        </CapTooltip>  
      </CapRow>
      <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 type='flex' align="middle" 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 = () => (
    <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>
      )}
      <ConfigProvider theme={{ components: { Radio: { radioSize: 20, dotSize: 8 } } }}>
        <CapRadioGroup
          options={buttonRadioOptions}
          value={buttonType}
          onChange={onChangeButtonType}
          disabled={templateMediaType === VIBER_MEDIA_TYPES.VIDEO}
          className="viber-btn-radio-group"
        />
      </ConfigProvider>
      {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 (!isEmpty(ctaData)) {
      messageData.button = {};
      messageData.button.text = ctaData?.buttonText;
      messageData.button.url = ctaData?.buttonURL;
    }
    return {
      versions: {
        base: {
          content: {
            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 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 (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()}
            {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={onDoneCallback()}
            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],
});
