/*
 *
 * Facebook
 *
 */
import PropTypes from "prop-types";
import React, { useState, useEffect, useCallback } from "react";
import { injectIntl, FormattedMessage, intlShape } from "react-intl";
import {
  CapHeading,
  CapLabel,
  CapRow,
  CapColumn,
  CapButton,
  CapDrawer,
  CapCustomCard,
  CapIcon,
  CapRadioGroup,
  CapTooltip,
} from '@capillarytech/cap-ui-library';
import Templates from '../Templates';
import { createStructuredSelector } from 'reselect';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import messages from "./messages";
import styles, { CampaignDetailCapColumn } from './Facebook.style';
import * as actions from './actions';
import withStyles from '../../hoc/withStyles';
import MarketingObjective from '../../v2Components/MarketingObjective';
import { makeSelectMarketingObjectiveList, makeSelectFbAd, makeSelectTemplate } from './selectors';
import Advertisement from './Advertisement';
import {
  VALUE_APP_INSTALLS,
  VALUE_BRAND_AWARENESS,
  VALUE_CONVERSIONS,
  VALUE_LEAD_GENERATION,
  VALUE_LOCAL_AWARENESS,
  VALUE_MESSAGES,
  VALUE_POST_ENGAGEMENT,
  VALUE_PRODUCT_CATALOG_SALES,
  VALUE_REACH,
  VALUE_VIDEO_VIEWS,
  VALUE_LINK_CLICKS,
  AD_MANAGER,
  CREATIVE,
} from './constants';
import injectSaga from '../../utils/injectSaga';
import injectReducer from '../../utils/injectReducer';
import { v2GallerySagas } from '../Assets/Gallery/sagas';
import v2FacebookReducer from './reducer';
import { compose } from 'redux';

const StyledCampaignDetailCapColumn = withStyles(CapColumn, CampaignDetailCapColumn);

const panesMapList = {
  [VALUE_APP_INSTALLS]: 'fbMarketingObjectiveAppInstallTitle',
  [VALUE_BRAND_AWARENESS]: 'fbMarketingObjectiveBrandAwarenessTitle',
  [VALUE_CONVERSIONS]: 'fbMarketingObjectiveConversionsTitle',
  [VALUE_LEAD_GENERATION]: 'fbMarketingObjectiveLeadGenerationTitle',
  [VALUE_LOCAL_AWARENESS]: 'fbMarketingObjectiveStoreTrafficTitle',
  [VALUE_MESSAGES]: 'fbMarketingObjectiveMessagesTitle',
  [VALUE_POST_ENGAGEMENT]: 'fbMarketingObjectiveEngagementTitle',
  [VALUE_PRODUCT_CATALOG_SALES]: 'fbMarketingObjectiveCatalogSalesTitle',
  [VALUE_REACH]: 'fbMarketingObjectiveReachTitle',
  [VALUE_VIDEO_VIEWS]: 'fbMarketingObjectiveVideoViewsTitle',
  [VALUE_LINK_CLICKS]: 'fbMarketingObjectiveTrafficTitle',
};

const getCategorizedMarketingObjectiveList = (marketingObjectivesList, formatMessage) => {
  const marketingObjectives = [
    {
      label: formatMessage(messages.fbMarketingObjectiveAwareness),
      panes: [
        {
          title: formatMessage(messages.fbMarketingObjectiveBrandAwarenessTitle),
          content: formatMessage(messages.fbMarketingObjectiveBrandAwarenessDescription),
          value: VALUE_BRAND_AWARENESS,
          icon: <CapIcon type="speaker" />,
        },
        {
          title: formatMessage(messages.fbMarketingObjectiveReachTitle),
          content: formatMessage(messages.fbMarketingObjectiveReachDescription),
          value: VALUE_REACH,
          icon: <CapIcon type="connect" />,
        },
      ],
    },
    {
      label: formatMessage(messages.fbMarketingObjectiveConsideration),
      panes: [
        {
          title: formatMessage(messages.fbMarketingObjectiveTrafficTitle),
          content: formatMessage(messages.fbMarketingObjectiveTrafficDescription),
          value: VALUE_LINK_CLICKS,
          icon: <CapIcon type="pointer" />,
        },
        {
          title: formatMessage(messages.fbMarketingObjectiveEngagementTitle),
          content: formatMessage(messages.fbMarketingObjectiveEngagementDescription),
          value: VALUE_POST_ENGAGEMENT,
          icon: <CapIcon type="group-chat" />,
        },
        {
          title: formatMessage(messages.fbMarketingObjectiveAppInstallTitle),
          content: formatMessage(messages.fbMarketingObjectiveAppInstallDescription),
          value: VALUE_APP_INSTALLS,
          icon: <CapIcon type="apps" />,
        },
        {
          title: formatMessage(messages.fbMarketingObjectiveVideoViewsTitle),
          content: formatMessage(messages.fbMarketingObjectiveVideoViewsDescription),
          value: VALUE_VIDEO_VIEWS,
          icon: <CapIcon type="video" />,
        },
        {
          title: formatMessage(messages.fbMarketingObjectiveLeadGenerationTitle),
          content: formatMessage(messages.fbMarketingObjectiveLeadGenerationDescription),
          value: VALUE_LEAD_GENERATION,
          icon: <CapIcon type="funnel" />,
        },
        {
          title: formatMessage(messages.fbMarketingObjectiveMessagesTitle),
          content: formatMessage(messages.fbMarketingObjectiveMessagesDescription),
          value: VALUE_MESSAGES,
          icon: <CapIcon type="message-filled" />,
        },
      ],
    },
    {
      label: formatMessage(messages.fbMarketingObjectiveConversionsTitle),
      panes: [
        {
          title: formatMessage(messages.fbMarketingObjectiveConversionsTitle),
          content: formatMessage(messages.fbMarketingObjectiveConversionsDescription),
          value: VALUE_CONVERSIONS,
          icon: <CapIcon type="global" style={{fontSize: 20 }}/>,
        },
        {
          title: formatMessage(messages.fbMarketingObjectiveCatalogSalesTitle),
          content: formatMessage(messages.fbMarketingObjectiveCatalogSalesDescription),
          value: VALUE_PRODUCT_CATALOG_SALES,
          icon: <CapIcon type="basket" />,
        },
        {
          title: formatMessage(messages.fbMarketingObjectiveStoreTrafficTitle),
          content: formatMessage(messages.fbMarketingObjectiveStoreTrafficDescription),
          value: VALUE_LOCAL_AWARENESS,
          icon: <CapIcon type="store-traffic" />,
        },
      ],
    },
  ];

  return marketingObjectives.map(({ label, panes }) => ({
    label,
    panes: panes.filter((pane) => !!marketingObjectivesList.includes(pane.value)),
  }));
};

const Facebook = (props) => {
  const {
    className,
    templateData,
    cap,
    messageDetails: {
      name: fbAdSetValue,
      targetAudience: {
        label: fbAudienceValue,
      } = {},
    } = {},
    onFacebookSubmit,
    marketingObjectiveList,
    facebookActions,
    intl,
    isFullMode,
    fbADData,
    onCreateComplete,
    params,
    facebookTemplateData,
    messageStrategy,
    router,
    handlePeviewTemplate,
    renderNewCardGrid,
    onSelectTemplate,
    createNew,
    fbAdManager,
    getFormSubscriptionData,
    showDisabledFBInfo,
    orgUnitId,
  } = props;
  const {
    campaignDetails: {
      name: fbCampaignValue,
      socialRemoteCampaignId,
      socialObjective,
    } = {},
    orgSettings: {
      accountSettings: {
        socialAccountSettings: {
          facebookAccountSettings: [{ accountName, accountId }] = [{}],
        } = {},
      } = {},
    } = {},
  } = cap || {};
  const {
    selectedMarketingObjective: fbMarketingObjectiveValue = VALUE_REACH,
  } = templateData || {};
  const [isDrawerVisible, setDrawerVisibility] = useState(false);
  const [selectedMarketingObjective, setMarketingObjective] = useState(socialObjective || fbMarketingObjectiveValue);
  const [adManager, setAdManager] = useState(AD_MANAGER);
  const [showTemplateList, setTemplateList] = useState(false);


  useEffect(() => {
    if (!isFullMode) {
      facebookActions.getMarketingObjectives();
    } else {
      const orgId = window.localStorage.getItem('orgID');
      facebookActions.getOrgOUs(orgId);
    }
  }, []);

  const categorizedMarketingObjectiveList = getCategorizedMarketingObjectiveList(marketingObjectiveList, intl.formatMessage);

  const campaignDataList = [
    {
      label: 'fbCampaignName',
      value: fbCampaignValue,
    },
    {
      label: 'fbMarketingObjective',
      value: selectedMarketingObjective ? intl.formatMessage(messages[panesMapList[selectedMarketingObjective]]) : '',
      onChange: () => setDrawerVisibility(!isDrawerVisible),
    },
    {
      label: 'fbAdSetName',
      value: fbAdSetValue,
    },
    {
      label: 'fbAudience',
      value: fbAudienceValue || <FormattedMessage {...messages.fbNoAudienceSelected} />,
    },
  ];

  const adSetParameters = ['fbAdsDetailOne', 'fbAdsDetailTwo', 'fbAdsDetailThree'];

  const onMarketingObjectiveSelect = (value) => setMarketingObjective(value);

  const radioOptions = [{
    label: showDisabledFBInfo ? <CapTooltip title={intl.formatMessage(messages.facebookDisableinfo)}>{intl.formatMessage(messages.capFbAdManager)}</CapTooltip> : intl.formatMessage(messages.capFbAdManager), value: CREATIVE, disabled: showDisabledFBInfo,
  }, {
    label: intl.formatMessage(messages.fbAdManager), value: AD_MANAGER,
  }];

  const onChangeAdManager = useCallback(({ target: { value } }) => {
    setAdManager(value);
  }, [setAdManager]);

  const onFacebookAdManagerContinue = useCallback(() => {
    if (adManager === AD_MANAGER) {
      onFacebookSubmit({ channel: "FACEBOOK", selectedMarketingObjective, accountId });
    } else {
      setTemplateList(true);
    }
  }, [
    selectedMarketingObjective,
    accountId,
    adManager,
    setAdManager,
    setTemplateList,
    showTemplateList,
  ]);
  const query = {type: 'embedded', module: 'library'};
  const location = {pathname: `/FACEBOOK`, search: '', query};
   
  // fbAdManager ==cretaives only the case for default startegy and user selected "capillary ad manager"
  // below condition (fbAdManager !==CREATIVE) is for edit fb ad manager from campaign
  //-> select capillary ad manager-> select template
  return ((showTemplateList && fbAdManager !==CREATIVE) ? (
    <Templates
      key={"FACEBOOK"}
      location={location}
      route={{name: "FACEBOOK"}}
      router={router}
      isFullMode={isFullMode}
      createNew={createNew}
      onSelectTemplate={onSelectTemplate}
      renderNewCardGrid={renderNewCardGrid}
      handlePeviewTemplate={handlePeviewTemplate}
      fbAdManager={CREATIVE} // it means we are selecting capillary ad manager from campaign
    />
  ) :
    (!isFullMode && ((fbAdManager !== CREATIVE && messageStrategy === "DEFAULT") 
    || (templateData?.edit && templateData?.fbContentType !==CREATIVE && fbAdManager !== CREATIVE )) ) ?

    // not fullmode + 
    // default strtaegy and not selected "capillary ad manager" from campaign message + 
    //edit template && not coming from campaign message where user selected "capillary ad manager" (means  edit "fb ad manager" from campaign) &&
    // & also we are not selecting capillary ad manager from campaign

    (<div className={className}>

        <div className="is-scrollable-section" >
          <div className="account-details-wrapper">
            <div className="account-name-section">
              <CapHeading type="h4">
                <FormattedMessage {...messages.fbAccount} />
              </CapHeading>
              <CapHeading type="h3">{accountName}</CapHeading>
            </div>

            <div className="account-section-container">
              <CapHeading type="h3">
                <FormattedMessage {...messages.fbAdCampaignSetDetailsTitle} />
              </CapHeading>
              <CapLabel type="label1">
                <FormattedMessage
                  {...messages.fbAdCampaignSetDetailsDescription}
                />
              </CapLabel>
            </div>

            <CapRow span={12} type="flex">
              {campaignDataList.map(({ label, value, onChange }, index) => (
                <StyledCampaignDetailCapColumn
                  span={index % 2 === 0 ? 6 : 14}
                  key={label}
                >
                  <CapRow useLegacy>
                    <CapLabel type="label2">
                      <FormattedMessage {...messages[label]} />
                    </CapLabel>
                    <CapHeading type="h4">
                      {value}
                      {!socialRemoteCampaignId && onChange && (
                      <CapButton
                        type="link"
                        className="marketingObjective-change-button facebook-marketing-objective-change"
                        onClick={onChange}
                        >
                        <FormattedMessage {...messages.fbChange} />
                      </CapButton>
                      )}
                    </CapHeading>
                  </CapRow>
                </StyledCampaignDetailCapColumn>
              ))}
            </CapRow>
            <CapDrawer
              content={
                <MarketingObjective
                  selectedMarketingObjective={selectedMarketingObjective}
                  onMarketingObjectiveSelect={onMarketingObjectiveSelect}
                  defaultmarketingObjective={socialObjective || fbMarketingObjectiveValue}
                  onSubmit={setDrawerVisibility}
                  marketingObjectiveList={categorizedMarketingObjectiveList}
                />
              }
              visible={isDrawerVisible}
              width={380}
              onClose={() => setDrawerVisibility(false)}
            />
          </div>

          <div className="fb-ad-manager-section">
            <CapHeading type="h4" style={{marginBottom: 17}}>
              <FormattedMessage
                {...messages.adManagerHeading}
            />
            </CapHeading>
            <CapRadioGroup
              style={{paddingBottom: '18px'}}
              options={radioOptions}
              onChange={onChangeAdManager}
              value={adManager}
              key={`fb-ad-creatives`}
          />
            {adManager === AD_MANAGER ? <>
              <div className="account-section-container">
                <CapLabel type="label1">
                  <FormattedMessage {...messages.fbAdsDescription} />
                </CapLabel>
              </div>


              <CapRow span={12} type="flex">
                <CapColumn span={6}>
                  <CapCustomCard
                    type="Facebook"
                    FBDynamicComponent={() => (
                      <CapIcon
                        size="l"
                        type="scenery"
                        className="facebook-dynamic-content"
                      />
                    )}
                  />
                </CapColumn>
                <CapColumn span={16}>
                  <ul className="parameter-list">
                    {adSetParameters.map((parameter, index) => (
                      <li key={parameter} className="parameter-list-item">
                        <CapLabel type="label2" className="parameter-index">
                          {index + 1}
                        </CapLabel>
                        <CapHeading type="h5">
                          <FormattedMessage {...messages[parameter]} />
                        </CapHeading>
                      </li>
                    ))}
                  </ul>
                </CapColumn>
              </CapRow></> : <CapLabel type="label1"><FormattedMessage {...messages.capAdManagerHeading}/></CapLabel>}

          </div>
        </div>
        <CapButton
          className="facebook-confirm-button"
          type="primary"
          onClick={onFacebookAdManagerContinue}
        >
          <FormattedMessage {...messages.fbContinue} />
        </CapButton>
      </div>
      ) :
      <div style={{height: '1200px'}}>
        <Advertisement
          cap={cap}
          isFullMode={isFullMode}
          actions={facebookActions}
          fbADData={fbADData}
          onCreateComplete={onCreateComplete}
          templateData={templateData}
          params={params}
          facebookTemplateData={facebookTemplateData}
          messageStrategy={messageStrategy}
          getFormSubscriptionData={getFormSubscriptionData}
          selectedMarketingObjective={selectedMarketingObjective}
          fbAdManager={fbAdManager}
          orgUnitId={orgUnitId}
        />
      </div>
  );
};

Facebook.propTypes = {
  className: PropTypes.string,
  templateData: PropTypes.object,
  cap: PropTypes.object,
  messageDetails: PropTypes.object,
  params: PropTypes.object,
  onFacebookSubmit: PropTypes.func,
  marketingObjectiveList: PropTypes.arrayOf(PropTypes.string),
  facebookActions: PropTypes.func,
  intl: intlShape,
  isFullMode: PropTypes.boolean,
  fbADData: PropTypes.object,
  onCreateComplete: PropTypes.func,
  facebookTemplateData: PropTypes.object,
  messageStrategy: PropTypes.string,
  getFormSubscriptionData: PropTypes.func,
};

Facebook.defaultProps = {
  marketingObjectiveList: [""],
};

const mapStateToProps = createStructuredSelector({
  marketingObjectiveList: makeSelectMarketingObjectiveList(),
  fbADData: makeSelectFbAd(),
  facebookTemplateData: makeSelectTemplate(),
});

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

const withConnect = connect(mapStateToProps, mapDispatchToProps);
const withReducer = injectReducer({ key: 'facebook', reducer: v2FacebookReducer });
const withSaga = injectSaga({ key: 'gallery', saga: v2GallerySagas });

export default compose(withSaga, withReducer, withConnect)(injectIntl(withStyles(Facebook, styles)));
