import PropTypes from "prop-types";
import React, { useState, useEffect, useCallback} from "react";
import { injectIntl, FormattedMessage, intlShape } from 'react-intl';
import { isUrl } from '../../Line/Container/Wrapper/utils';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectCurrentOrgDetails } from "../../Cap/selectors";
import { getCdnUrl } from '../../../utils/cdnTransformation';
import {
  CapInput,
  CapRadioCard,
  CapHeading,
  CapIcon,
  CapSpin,
  CapRow,
  CapColumn,
  CapTooltipWithInfo,
  CapLabel,
  CapSelect,
  CapRadioGroup,
  CapButton,
  CapNotification,
  CapLink,
  CapHeader,
  CapTab,
  CapTooltip,
  CapDivider,
} from "@capillarytech/cap-ui-library";
import {
  CAP_SPACE_32,
  CAP_SPACE_24,
  CAP_WHITE,
  CAP_SPACE_16,
  CAP_G08,
  FONT_COLOR_02,
  FONT_COLOR_01,
} from '@capillarytech/cap-ui-library/styled/variables';
import styled from 'styled-components';
import CapImageUpload from '../../../v2Components/CapImageUpload';
import CapVideoUpload from '../../../v2Components/CapVideoUpload';
import messages from "./messages";
import CapRadioCardCustom from '../../../v2Components/CapRadioCardCustom';
import { FB_AD_CALL_TO_ACTION } from '../../App/constants';
import CapFacebookPreview from '../../CapFacebookPreview';
import './index.scss';
import {
  ALLOWED_EXTENSIONS_REGEX,
  FB_AD_IMG_HEIGHT,
  FB_AD_IMG_WIDTH,
  FB_AD_IMG_SIZE,
  ALLOWED_EXTENSIONS_VIDEO_REGEX,
  FB_AD_VIDEO_SIZE,
  MAX_CAROUSEL_ALLOWED,
  IMAGE,
  VIDEO,
  CAROUSEL,
  IMAGE_VIDEO,
  NO_CALL_TO_ACTION,
} from './constant';
import cloneDeep from 'lodash/cloneDeep';
import { FACEBOOK } from "../../CreativesContainer/constants";
export const Advertisement = (props) => {
  const CarouselContainer = styled.div`
    width: ${(styledProps) => styledProps.width || '22px'};
    height: 23px;
    margin: 0 1px 0px 1px;
    border: ${CAP_G08};
    background-color: ${CAP_G08};
    display:inline;
`;
  const FbAdFooter = styled.div`
    background-color: ${CAP_WHITE};
    position: fixed;
    bottom: 20px;
    width: 100%;
    margin-left: -32px;
    padding: ${CAP_SPACE_32} ${CAP_SPACE_24};

    .ant-btn {
      margin-right: ${CAP_SPACE_16};
    }
  `;
  const {
    intl,
    isFullMode,
    actions,
    fbADData = {},
    onCreateComplete,
    templateData = {},
    params,
    getFormSubscriptionData,
    facebookTemplateData,
    selectedMarketingObjective,
    orgUnitId,
  } = props;
  const {
    formatMessage,
    } = intl || {};
  const defaultActiveIndex = 0;
  const defaultCarouselContent = {
    subType: IMAGE,
    imageData: {},
    videoData: {},
    webSiteLink: '',
    linkHeadLine: '',
    linkDesc: '',
    errorMsg: {websiteLinkErrorMsg: false},
  };
  const { TextArea } = CapInput;
  const [carouselData, updateCarouselData] = useState([defaultCarouselContent]);
  const [selectedAd, setSelectPane] = useState('');
  const [primaryText, setPrimaryText] = useState('');
  const [pageId, setPageId] = useState(false);
  const [displayLink, setDisplayLink] = useState('');
  const [callToAction, setCallToAction] = useState(NO_CALL_TO_ACTION);
  const [callToActionError, setCallToActionError] = useState(false);
  const [messageTitle, updateMessageTitle] = useState('');
  const [step, updateStep] = useState('modeSelection');
  const [activeIndex, updateActiveIndex] = useState(`${defaultActiveIndex}`);
  const [isEditLoading, updateEditLoading] = useState(false);
  const [isEditFlow, checkEditFlow] = useState(false);
  const [editNameState, setEditNameState] = useState(false);
  const isCarouselSelectedAd = selectedAd === CAROUSEL;
  const isImgVideoSelectedAd = selectedAd === IMAGE_VIDEO;
  const activeCarouselData = carouselData[activeIndex];

  const uploadFbAdAsset = useCallback(( file,
    type,
    fileParams,
    indexFile) => {
    let videoData = {};
    if (type === 'video') {
      const {
        orgUnitFacebookPageSettingsMap = {},
        employeeAccessToken: accessToken = "",
        accountId = "",
       } = selectedFacebookAccount || {};
      const { pageAccessToken, pageId: pId } = orgUnitFacebookPageSettingsMap[pageId] || {};
      videoData = {
        accessToken,
        actId: accountId,
        pageAccessToken,
        pageId: pId,
      };
    }
    actions.uploadFbAdAsset(file,
        type,
        fileParams,
        indexFile,
        videoData,
        );
  }, [pageId]);

  const paramObj = params || {};

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

  useEffect(() => {
    if (params?.id || templateData?.edit) {
      const { FacebookAd = [], pageOrgUnitId: editPageId} = get(templateData, `versions.base.content`) || get(fbADData, `templateDetails.versions.base.content`) || {};
      const editMessageTitle = (templateData || {}).name || get(fbADData, 'templateDetails.name');
      const editFBContent = Object.values(FacebookAd);
      if (editPageId) {
        setPageId(editPageId);
      }
      if (editFBContent.length > 0 ) {
        updateMessageTitle(editMessageTitle);
        const {
          type,
          primaryText: pt,
          callToAction: cta,
          displayLink: dl,
        } = (editFBContent || [])[0];
        setSelectPane(type);
        setPrimaryText(pt);
        setCallToAction(cta);
        if (type !== CAROUSEL) {
          setDisplayLink(dl);
        }
        const newCarouselData = [...carouselData];
        editFBContent.forEach((obj, index) => {
          const data = {
            subType: obj.subType,
            webSiteLink: obj.webSiteLink,
            linkHeadLine: obj.linkHeadLine,
            linkDesc: obj.linkDesc,
          };
          if (obj.subType === IMAGE) {
            data.imageData = {
              imageSrc: getCdnUrl({url: obj.imgSrc, channelName: 'FACEBOOK', channelSubType: 'IMAGE'}),
            };
          }
          if (obj.subType === VIDEO) {
            const {
              previewImageUrl: previewUrl,
              originalContentUrl: videoSrc,
              videoName,
              videoHeight,
              videoWidth,
              videoId,
            } = obj.video;
            data.videoData = {
              videoSrc,
              videoName,
              videoHeight,
              videoWidth,
              previewUrl,
              videoId,
            };
          }
          newCarouselData[index] = {...defaultCarouselContent, ...data};
        });
        updateCarouselData(newCarouselData);
      }
    }
  }, [fbADData[`templateDetails`] || templateData]);


  const CustomToolTip = useCallback((msg) => <CapTooltipWithInfo
    infoIconProps={{svgProps: {width: 12, height: 12}, style: {marginLeft: 5}}}
    title={msg}
  />, []);

  const advertisementTypePanes = [
    {
      title: <FormattedMessage {...messages.imageVideoTitle} />,
      content: <FormattedMessage {...messages.imageVideoDesc} />,
      value: IMAGE_VIDEO,
      customComponent: <CapRadioCardCustom
        showSelected={isImgVideoSelectedAd}
        component={<CapIcon
          type="media" svgProps={{ color: '#b3bac5',
            width: '20px',
            height: '20px'}}>
        </CapIcon>}/>,
    },
    {
      title: <FormattedMessage {...messages.carouselTitle} />,
      content: <FormattedMessage {...messages.carouselDesc} />,
      value: CAROUSEL,
      customComponent: <CapRadioCardCustom
        wrapperStyle={{padding: '9px 0px 8px'}}
        showSelected={isCarouselSelectedAd}
        component={<>
          <CarouselContainer style={{float: 'left'}}/>
          <CarouselContainer style={{float: 'left'}}/>
          <CarouselContainer style={{float: 'left', marginRight: '0px'}} width="10.5px"/>
          </>}
          />,
    },
  ];

  const radioOptions = [{
    label: formatMessage(messages.image), value: IMAGE,
  }, {
    label: formatMessage(messages.video_slideshow), value: VIDEO,
  }];

  const OptionalComponent =
    <CapLabel.CapLabelInline type="label14">{formatMessage(messages.optional)}</CapLabel.CapLabelInline>;

  const callToActionOptions = Object.entries(FB_AD_CALL_TO_ACTION).map(([key, val]) => ({label: val, value: key}));

  const onChangeAdvType = useCallback( ({ target: { value } }) => {
    setSelectPane(value);
  }, [selectedAd]);

  const updateOnImageReUpload = useCallback(() => {
    const newCarouselData = cloneDeep(carouselData);
    newCarouselData[activeIndex].imageData.imageSrc = '';
    updateCarouselData(newCarouselData);
  }, [carouselData, activeIndex]);

  const setUpdateImageSrc = useCallback((val) => {
    const newCarouselData = cloneDeep(carouselData);
    newCarouselData[activeIndex].imageData = {
      imageSrc: val,
    };
    updateCarouselData(newCarouselData);
    actions.clearFbAdAsset(activeIndex);
  }, [carouselData, activeIndex]);

  const onChangePrimaryText = useCallback((e) => {
    e.preventDefault();
    setPrimaryText(e.target.value);
  }, [primaryText]);

  const onChangeDisplayLink = useCallback(({ target: { value } }) => {
    setDisplayLink(value);
  }, [displayLink]);

  const onChangeCallToAction = useCallback((value) => {
    setCallToAction(value);
  }, [callToAction]);

  const onChangeMediaOption = useCallback(({ target: { value } }) => {
    const newCarouselData = [...carouselData];
    newCarouselData[activeIndex].subType = value;
    newCarouselData[activeIndex].imageData = {};
    updateCarouselData(newCarouselData);
    actions.clearFbAdAsset(activeIndex);
  }, [carouselData, activeIndex]);


  const formatSubmitPayload = useCallback(() => {
    const messageData = [];
    let data = { };
    // for image/video selected Ad

    carouselData.forEach((obj) => {
      data = {
        type: selectedAd !== CAROUSEL ? obj.subType : selectedAd,
        subType: obj.subType,
        webSiteLink: obj.webSiteLink,
        linkHeadLine: obj.linkHeadLine,
        linkDesc: obj.linkDesc,
        primaryText,
        callToAction,
      };
      if (!isCarouselSelectedAd) {
        data = {
          ...data,
          primaryText,
          displayLink,
          callToAction,
        };
      }
      if (obj.subType === IMAGE) {
        data.imgSrc = getCdnUrl({url: obj.imageData.imageSrc, channelName: 'FACEBOOK', channelSubType: 'IMAGE'});
      } else {
        const {
          videoSrc,
          videoName,
          videoHeight,
          videoWidth,
          previewUrl,
          videoId,
        } = obj.videoData;
        data.video = {
          previewImageUrl: previewUrl,
          originalContentUrl: videoSrc,
          videoName,
          baseUrl: previewUrl.replace('/1040', ''),
          videoHeight,
          videoWidth,
          videoId,
        };
      }
      messageData.push(data);
    });
    let finalResponse = {
      versions: {
        base: {
          content: {
            FacebookAd: {...messageData},
            pageOrgUnitId: pageId,
          },
        },
      },
      type: FACEBOOK,
      name: messageTitle,
    };
    if (!isFullMode) {
      finalResponse = {...finalResponse, selectedMarketingObjective, accountId};
    }
    return finalResponse;
  }, [carouselData,
    pageId,
    messageTitle,
    primaryText,
    callToAction,
    displayLink,
    selectedMarketingObjective]);

  const onCreateFacebookAd = useCallback( () => {
    actions.createTemplate(
        formatSubmitPayload(),
        (resp, errorMessage) => {
          createCallback(errorMessage);
        }
    );
  }, [carouselData,
    pageId,
    messageTitle,
    primaryText,
    callToAction,
    displayLink]);

  const createCallback = useCallback((errorMessage, isEdit) => {
    if (!errorMessage) {
      CapNotification.success({
        message: isEdit ? formatMessage(messages.editNotification) : formatMessage(messages.createNotification),
      });
      if (isEdit) {
        actions.clearEditResponse();
      } else {
        actions.clearCreateResponse();
      }
      onCreateComplete();
    } else {
      CapNotification.error({
        message: errorMessage,
      });
    }
  }, []);

  const onEditFacebookAd = useCallback(() => {
    actions.editTemplate(
      {
        ...formatSubmitPayload(),
        _id: params.id,
      },
        (resp, errorMessage) => {
          createCallback(errorMessage, true);
        });
  }, [carouselData,
    pageId,
    messageTitle,
    primaryText,
    callToAction,
    displayLink, params]);

  const onDoneCallback = useCallback(() => {
    if (isFullMode) {
      if (isEditFlow) {
        return onEditFacebookAd;
      }
      return onCreateFacebookAd;
    }
    return () => getFormSubscriptionData({
      value: formatSubmitPayload(),
      _id: params && params.id,
      validity: true,
      type: FACEBOOK,
    });
  }, [carouselData,
    pageId,
    messageTitle,
    primaryText,
    callToAction,
    displayLink, params]);

  const onTextTitleChange = useCallback((e) => {
    const val = e.target.value;
    updateMessageTitle(val);
  }, [messageTitle]);


  const isDisableDone = useCallback((isPreview) => {
    let flag = false;
    if (primaryText === "" ) {
      flag = true;
    }
    if (selectedAd === CAROUSEL && carouselData.length === 1 && !isPreview) {
      flag = true;
      return flag;
    }
    const subTypes = [];
    carouselData.forEach((obj) => {
      const {
        webSiteLink,
        imageData,
        videoData,
        subType,
        errorMsg,
      } = obj;
      if (webSiteLink === "" || errorMsg.websiteLinkErrorMsg ) {
        flag = true;
      }
      if (!imageData?.imageSrc && subType === IMAGE) {
        flag = true;
      } else if (!videoData?.videoSrc && subType === VIDEO) {
        flag = true;
      }
      subTypes.push(subType);
    });
    if (subTypes.includes(VIDEO) ) {
      if (callToAction === NO_CALL_TO_ACTION && !callToActionError) {
        setCallToActionError(messages.callToActionMandatoryError);
        flag = true;
      } else if (callToAction !== NO_CALL_TO_ACTION && callToActionError) {
        setCallToActionError(false);
        flag = false;
      }
    } else if (callToActionError) {
      setCallToActionError(false);
      flag = false;
    }
    return flag;
  }, [
    callToActionError,
    carouselData,
    callToAction,
    primaryText,
    selectedAd,
  ]
);
  const isDisableContinue = () => isFullMode ? (messageTitle.trim() === "" || selectedAd === "") : ( selectedAd === "");

  const onClickContinue = useCallback(() => { updateStep('createFacebookAd'); }, [step]);

  const onVideoUploadUpdateAssestList = useCallback((index, data) => {
    const newCarouselData = [...carouselData];
    newCarouselData[index].videoData = data;
    updateCarouselData(newCarouselData);
  }, [carouselData]);

  const shiftRightContent = useCallback(() => {
    const newActiveIndex = Number(activeIndex) + 1;
    updateActiveIndex(`${newActiveIndex}`);
  }, [activeIndex]);

  const shiftLeftContent = useCallback(() => {
    const newActiveIndex = Number(activeIndex) - 1;
    updateActiveIndex(`${newActiveIndex}`);
  }, [activeIndex]);

  const onTabChange = useCallback((index) => {
    updateActiveIndex(index);
  }, [activeIndex]);

  const spinLoader = fbADData.createTemplateInProgress || isEditLoading || false;
  const showMedia = activeCarouselData.subType === IMAGE;
  const adSpinLoader = get(fbADData, 'orgOuData.status', '') === 'REQUEST';

  const MediaComponent = ({index = 0}) => <>
    <CapRadioGroup
      style={{paddingBottom: '18px'}}
      options={radioOptions}
      onChange={onChangeMediaOption}
      value={activeCarouselData.subType}
      index={index}
      key={`${index}-fb-radio-card`}
    />

    {showMedia ? <CapImageUpload
      style={{paddingBottom: '21px', width: '460px'}}
      allowedExtensionsRegex={ALLOWED_EXTENSIONS_REGEX}
      imgWidth={FB_AD_IMG_WIDTH}
      imgHeight={FB_AD_IMG_HEIGHT}
      imgSize={FB_AD_IMG_SIZE}
      uploadAsset={uploadFbAdAsset}
      isFullMode={isFullMode}
      imageSrc={activeCarouselData.imageData.imageSrc || ''}
      updateImageSrc={setUpdateImageSrc}
      updateOnReUpload={updateOnImageReUpload}
      index={index}
      className={`cap-image-upload-${selectedAd}`}
      key={`${index}-fb-image-upload`}
      imageData={fbADData}
      channel={FACEBOOK}
       /> :
      <CapVideoUpload
        style={{paddingBottom: '21px'}}
        index={index}
        allowedExtensionsRegex={ALLOWED_EXTENSIONS_VIDEO_REGEX}
        videoSize={FB_AD_VIDEO_SIZE}
        isFullMode={isFullMode}
        uploadAsset={uploadFbAdAsset}
        uploadedAssetList={carouselData[index].videoData}
        onVideoUploadUpdateAssestList={onVideoUploadUpdateAssestList}
        key={`${index}-fb-video-upload`}
        videoData={fbADData}
       />
     }
  </>;

  const PrimaryTextComponent = (
    <TextArea
      id={'fbAd_textarea'}
      label={<>
        {formatMessage(messages.primaryText)}
        {CustomToolTip(formatMessage(messages.primaryTextToolTip))}
    </>}
      className="cap-input-wrapper"
      autosize={false}
      onChange={onChangePrimaryText}
      defaultValue={primaryText || ''}
      value={primaryText || ''}
      maxLength={125}
      rows={3}
      cols={2}
      placeholder={formatMessage(messages.primaryTextPlaceholder)}
  />);

  const linkHeadlineComponent = (index = 0) => {
    const onChangeLinkHeadLine = (e) => {
      e.preventDefault();
      const newCarouselData = [...carouselData];
      newCarouselData[activeIndex].linkHeadLine = e.target.value;
      updateCarouselData(newCarouselData);
    };
    return (<CapInput
      className="cap-input-wrapper"
      id="fbAd-link-headline"
      type="input"
      onChange={onChangeLinkHeadLine}
      key={`${index}-line-headline`}
      label={<>
        {formatMessage(messages.linkHeadline)}{' '}
        {OptionalComponent}
        {CustomToolTip(formatMessage(messages.linkHeadlineToolTip))}
    </>}
      value={carouselData[index].linkHeadLine}
      maxLength={40}
      index={index}
      placeholder={formatMessage(messages.linkHeadlinePlaceHolder)}
    />);
  };

  const linkDescComponent = (index = 0) => {
    const onChangeLinkDesc = (e) => {
      e.preventDefault();
      const newCarouselData = [...carouselData];
      newCarouselData[activeIndex].linkDesc = e.target.value;
      updateCarouselData(newCarouselData);
    };
    return (<CapInput
      className="cap-input-wrapper"
      id="fbAd-link-desc"
      type="input"
      onChange={onChangeLinkDesc}
      key={`${index}-line-desc`}
      label={<>
        {formatMessage(messages.linkDesc)}{' '}
        {OptionalComponent}
        {CustomToolTip(formatMessage(messages.linkDescToolTip))}
    </>}
      value={(carouselData[index] || {}).linkDesc}
      maxLength={40}
      index={index}
      placeholder={formatMessage(messages.linkDescPlaceHolder)}
    />);
  };

  const WebsiteLinkComponent = (index = 0 ) => {
    const onChangeWebSiteLink = (e) => {
      e.preventDefault();
      let errorMsg = false;
      const value = e.target.value;
      const newCarouselData = [...carouselData];
      if (!isUrl(value)) {
        errorMsg = formatMessage(messages.inValidUrliErrorMessage);
      }
      newCarouselData[activeIndex].webSiteLink = value;
      newCarouselData[activeIndex].errorMsg = {
        websiteLinkErrorMsg: errorMsg,
      };
      updateCarouselData(newCarouselData);
    };

    const {webSiteLink = "", errorMsg = {} } = carouselData[index] || {};
    return (<CapInput
      className="cap-input-wrapper"
      id="fbAd-web-site-link"
      type="input"
      key={`${index}-webSite-link`}
      onChange={onChangeWebSiteLink}
      label={formatMessage(messages.webSiteLink)}
      value={webSiteLink}
      placeholder={formatMessage(messages.websiteLinkPlaceHolder)}
      errorMessage={errorMsg.websiteLinkErrorMsg}
      index={index}
    />);
  };

  const DisplayLinkComponent = (false && <CapInput
    className="cap-input-wrapper"
    id="fbAd-display-link"
    type="input"
    style={{display: 'none'}}
    onChange={onChangeDisplayLink}
    label={<>
      {formatMessage(messages.displayLink)}{' '}
      {OptionalComponent}
      </>
    }
    defaultValue={displayLink}
    value={displayLink}
    placeholder={formatMessage(messages.displayLinkPlaceHolder)}
  />);

  const CallToActionComponent = (<CapSelect
    label={formatMessage(messages.callToAction)}
    key={"select-account"}
    onChange={onChangeCallToAction}
    style={{width: '324px'}}
    options={callToActionOptions}
    value={callToAction}
    errorMessage={callToActionError ? formatMessage(callToActionError) : ""}
  ></CapSelect>);

  const addContent = useCallback(() => {
    const newCarouselData = [
      ...carouselData,
      {
        ...defaultCarouselContent,
        activeIndex: carouselData.length,
      },
    ];
    updateCarouselData(newCarouselData);
  }, [carouselData]);

  const deleteContent = useCallback(() => {
    const newCarouselData = [...carouselData];
    newCarouselData.splice(activeIndex, 1);
    updateCarouselData(newCarouselData);
    const parsedActiveIndex = Number(activeIndex);
    const newActiveIndex = parsedActiveIndex === 0 ? parsedActiveIndex : parsedActiveIndex - 1;
    updateActiveIndex(`${newActiveIndex}`);
  }, [carouselData, activeIndex]);

  const operations = (
  <>
    <CapButton
      onClick={addContent}
      type="flat"
      disabled={MAX_CAROUSEL_ALLOWED === carouselData.length}
      isAddBtn
      style={{ padding: 0, marginTop: 12 }}
        >
      <FormattedMessage {...messages.addCard} />
    </CapButton>
    <div
      style={{
        top: 54,
        right: 0,
      }}
      className="extra-button-group"
      >
      <CapTooltip
        title={<FormattedMessage {...messages.shiftLeftTooltipLabel} />}
        >
        <CapButton
          onClick={shiftLeftContent}
          disabled={defaultActiveIndex === Number(activeIndex)}
          type="link">
          <CapIcon type="left" size="s" />
        </CapButton>
      </CapTooltip>
      <CapTooltip
        title={<FormattedMessage {...messages.shiftRightTooltipLabel} />}>
        <CapButton
          onClick={shiftRightContent}
          disabled={carouselData.length === (Number(activeIndex) + 1)}
          type="link">
          <CapIcon type="right" size="s" />
        </CapButton>
      </CapTooltip>
      <CapTooltip
        title={<FormattedMessage {...messages.deleteTooltipLabel} />}>
        <CapButton
          onClick={deleteContent}
          disabled={carouselData.length === 1}
          type="link">
          <CapIcon type="delete" size="s" />
        </CapButton>
      </CapTooltip>
    </div>
    </>
  );

  const getTabPanes = () => carouselData.map((data, index) => {
    const isSelected = Number(activeIndex) === index;
    return {
      key: index,
      tab: (
        <span
          style={{
            display: 'inline-block',
            borderRadius: '50%',
            color: CAP_WHITE,
            backgroundColor: !isSelected ? FONT_COLOR_02 : FONT_COLOR_01,
            height: CAP_SPACE_24,
            width: CAP_SPACE_24,
            textAlign: 'center',
            paddingTop: 4,
          }}
          >
          {index + 1}
        </span>
        ),
      content: <div key={`${index}-card-container`}>
        <MediaComponent index={index}/>
        {WebsiteLinkComponent(index)}
        {linkHeadlineComponent(index)}
        {linkDescComponent(index)}
      </div>,
    };
  });

  const onClickEditName = useCallback(() => {
    setEditNameState(true);
  }, [editNameState]);

  const onEditFocusOut = useCallback((e) => {
    const data = e.target.value;
    if (data.trim() !== "") {
      setEditNameState(false);
      updateMessageTitle(e.target.value);
    }
  }, [messageTitle, editNameState]);

  const onChangeFacebookPage = useCallback((value) => {
    setPageId(value);
  }, [pageId]);

  const selectedFacebookAccount = templateData?.edit ? templateData?.selectedFacebookAccount : facebookTemplateData?.selectedFacebookAccount;
  const {orgUnitFacebookPageSettingsMap = {}, employeeAccessToken: accessToken = "", accountId = "" } = selectedFacebookAccount || {};

  const getOrgName =()=>{
    const { currentOrgDetails } = props;
    const { basic_details: { name: orgName } = {} } = currentOrgDetails || {};
    return orgName;
  }
  const getPageAccessOrgs = useCallback(() => {
    const {status, data } = fbADData.orgOuData || {};
    const pageAccessOrgsOptions = [];
    const orgName = getOrgName()
    if (!status) {
      // !status is the case of library
      //if org id is the parent org
      if (orgUnitFacebookPageSettingsMap[-1] && !pageId) {
        setPageId(-1);
      }
      if (orgUnitFacebookPageSettingsMap[-1]) {
        pageAccessOrgsOptions.push({label: orgName, value: -1});
      }
      // if we are coming from default startegy and calling templates from facebook/index.js
      if (!pageId && orgUnitId && orgUnitFacebookPageSettingsMap[orgUnitId]) {
        setPageId(orgUnitId);
      }
    } else if (status === 'SUCCESS') {
      Object.keys(data).forEach((obj) => {
        if ((orgUnitFacebookPageSettingsMap[data[obj]] || {}).pageAccessToken && data[obj]!== -1) {
          pageAccessOrgsOptions.push({label: obj, value: data[obj]});
        }
      });
      if (orgUnitFacebookPageSettingsMap[-1]) {
        pageAccessOrgsOptions.push({label: orgName, value: -1});
      }
      if (!pageId && !isEmpty(data)) {
        setPageId((pageAccessOrgsOptions[0] || {} ).value);
      } else if (orgUnitFacebookPageSettingsMap[-1] && !pageId) {
        setPageId(-1);
      }
    }
    return pageAccessOrgsOptions;
  }, [pageId, fbADData]);

  const options = getPageAccessOrgs() || [];
  const { data = {} } = fbADData.orgOuData || {};
  const orgName = getOrgName()
  let selectedPageName = Object.keys(data).find((key) => data[key] === pageId);
  if(data[selectedPageName] === -1){
    selectedPageName = orgName;
  }
  return ( (step === 'modeSelection' && (isEmpty(templateData) || templateData?.mode === "create")) ?
       ( <CapSpin spinning={adSpinLoader} className="add-facebook-ad-section">
         <div style={{ position: 'fixed', top: '25px', zIndex: 1}}>
           <CapHeader
             inline
             title={formatMessage(messages.newFacebookCreatives)}
             className={"cap-header-facebook-ad"}
            />
         </div>
         {isFullMode &&  <>
           <CapInput
             id={`fbAd_input`}
             onChange={onTextTitleChange}
             className="text-template-title"
             defaultValue={messageTitle || ''}
             value={messageTitle || ''}
             style={{marginBottom: 27, width: '762px'}}
             size="default"
             label={formatMessage(messages.creativeName)}
              />
           <CapSelect
             label={formatMessage(messages.facebookPage)}
             key={"select-facebook-page"}
             onChange={onChangeFacebookPage}
             options={options}
             defaultValue={(options[0] || {} ).value}
             value={pageId || (options[0] || {} ).value}
             style={{marginBottom: 27, width: '372px'}}
          ></CapSelect>
        </>}
         <CapHeading
           type="h4"
           style={{marginBottom: 11}}
            >
           {formatMessage(messages.AdvertisementType)}
         </CapHeading>
         <CapRadioCard
           panes={advertisementTypePanes}
           onChange={onChangeAdvType}
           selected={selectedAd}
           className="facebook-ad-type-card"
          />
         <FbAdFooter>
           <CapButton
             onClick={onClickContinue}
             disabled={isDisableContinue()}
             className="create-msg"
              >
             <FormattedMessage {...messages.clickButtonLabel} />
           </CapButton>
         </FbAdFooter>
       </CapSpin> ) : (
         <CapSpin spinning={spinLoader}>
           {!isFullMode && isEmpty(templateData) && <div style={{ position: 'fixed', top: '25px', zIndex: 1}}>
             <CapHeader
               inline
               title={formatMessage(messages.newFacebookCreatives)}
               className={"cap-header-facebook-ad"}
            />
           </div>}
           <div className="add-facebook-ad-section">
           <CapRow  >
            <CapColumn span={12}>
             <CapRow type="flex" align="bottom" justify="start" gap={4}>
              {isFullMode && <>
                <CapHeading
                  type="h2"
                  className="truncate-text"
                  >
                  {editNameState ? <CapInput
                    type="input"
                    className="cap-input-edit-name"
                    onBlur={onEditFocusOut}
                    defaultValue={messageTitle || ''}
                    /> : messageTitle
                    }
                </CapHeading>
                {!editNameState && <CapLink
                  className="cap-link-edit-name"
                  title={<FormattedMessage {...messages.creativesTemplatesEditName}/>}
                  onClick={onClickEditName}
                    />}
                </>}
             </CapRow>
               {isFullMode && <><CapHeading
                 type="h4"
                 style={{marginBottom: 4}}
                    >
                 {formatMessage(messages.facebookPage)}
               </CapHeading>
                 <CapHeading
                   type="h6"
                   style={{marginBottom: 24}}
                    >
                   {selectedPageName}
                 </CapHeading></>}
               {!isCarouselSelectedAd ? <>
                 <MediaComponent />
                 {PrimaryTextComponent}
                 {linkHeadlineComponent()}
                 {linkDescComponent()}
                 {WebsiteLinkComponent()}
                 {DisplayLinkComponent}
                 {CallToActionComponent}
                 </> : <>
                   {PrimaryTextComponent}
                   {CallToActionComponent}
                   <CapDivider style={{width: '460px', minWidth: '460px'}}/>
                   <CapTab
                     style={{width: '460px'}}
                     defaultActiveKey={`${defaultActiveIndex}`}
                     activeKey={activeIndex}
                     tabBarExtraContent={operations}
                     onChange={onTabChange}
                     panes={getTabPanes()}
                    />
                 </>
              }
             </CapColumn>
             <CapColumn span={8}>
               <CapFacebookPreview
                 disablePreviewButton={isDisableDone(true)}
                 selectedAd={selectedAd}
                 previewData={carouselData}
                 primaryText={primaryText}
                 callToAction={callToAction}
                 displayLink={displayLink}
                 orgUnitFacebookPageSettingsMap={orgUnitFacebookPageSettingsMap[pageId] || {}}
                 accessToken={accessToken}
                 accountId={accountId}
                 key={`facebookPreview-${pageId}`}
                  />
             </CapColumn>
           </CapRow>
           </div>
           <FbAdFooter>
             <CapButton
               onClick={onDoneCallback()}
               disabled={isDisableDone()}
             >
               <FormattedMessage {...messages.doneButtonLabel} />
             </CapButton>
           </FbAdFooter>
         </CapSpin>
          )
  );
};

Advertisement.propTypes = {
  intl: intlShape,
  isFullMode: PropTypes.bool,
  onCreateComplete: PropTypes.func,
  fbADData: PropTypes.object,
  actions: PropTypes.any,
  getFormSubscriptionData: PropTypes.func,
  facebookTemplateData: PropTypes.object,
  templateData: PropTypes.object,
  params: PropTypes.object,
  selectedMarketingObjective: PropTypes.any,
  currentOrgDetails: PropTypes.object,
};

const mapStateToProps = (state, props) =>
  createStructuredSelector({
    currentOrgDetails: props?.cap
      ? () => props.cap.currentOrgDetails
      : selectCurrentOrgDetails(),
  });

export default connect(mapStateToProps, null)(injectIntl(Advertisement));