import React from 'react';
import styled from 'styled-components';
import { FormattedMessage } from 'react-intl';
import get from 'lodash/get';
import { CapHeader, CapIcons, CapLabel, CapLink, CapSteps, CapIcon, CapHeading } from '@capillarytech/cap-ui-library';
import moment from 'moment';
import PropTypes from 'prop-types';
import './index.scss';
import messages from './messages';
import whatsppMsg from '../Whatsapp/messages';
import { LANGUAGE_OPTIONS } from '../Whatsapp/constants';
import globalMessages from '../Cap/messages';
import { MAP_TEMPLATE } from '../WeChat/Wrapper/constants';
import { NO_COMMUNICATION, FTP, WHATSAPP, RCS, ZALO, INAPP } from '../App/constants';
import { isTraiDLTEnable } from '../../utils/common';
import { formatString } from '../../utils/Formatter';
import {
  CAP_SPACE_12,
} from '@capillarytech/cap-ui-library/styled/variables';
import { WHATSAPP_HELP_DOC_LINK, JOURNEY } from './constants';

const { CapLabelInline } = CapLabel;
const StyledLabel = styled(CapLabelInline)`
  margin-right: ${CAP_SPACE_12};
`;
const PrefixWrapper = styled.div`
  margin-right: 16px;
`;
const renderData = (type, value, channel) => (
  <StyledLabel className={channel?.toLowerCase() === ZALO ? 'zalo-template-name-spacing' : ''} type={type}>
    {value}
  </StyledLabel>
);

export function SlideBoxHeader(props) {
  const { slidBoxContent, templateData, onShowTemplates, creativesMode, isFullMode, showPrefix, shouldShowTemplateName, channel, templateNameRenderProp, weChatTemplateType, onWeChatMaptemplateStepChange, weChatMaptemplateStep, templateStep, smsRegister, handleClose, moduleType } = props;
  const showTemplateNameHeader = isFullMode && shouldShowTemplateName;
  const mapTemplateCreate = !showTemplateNameHeader && slidBoxContent === 'createTemplate' && weChatTemplateType === MAP_TEMPLATE && templateStep !== 'modeSelection';
  const isTraiDlt = isTraiDLTEnable(isFullMode, smsRegister);
  const showCreateTraiSMSHeader = isTraiDlt && channel.toLowerCase() === "sms";
  const isWhatsappEdit = channel.toLowerCase() === WHATSAPP && slidBoxContent === 'editTemplate';
  const isInAppEdit = channel.toLowerCase() === INAPP && slidBoxContent === 'editTemplate';
  const isWhatsappCreate = channel.toLowerCase() === WHATSAPP && slidBoxContent === 'createTemplate';
  const isInAppCreate = channel.toLowerCase() === INAPP && slidBoxContent === 'createTemplate';
  const isZaloEdit = channel.toLowerCase() === ZALO && slidBoxContent === 'editTemplate';
  const zaloOverview = isZaloEdit && isFullMode;
  const whatsappOverview = isWhatsappEdit && isFullMode;
  const shouldShowInAppEditHeader = isInAppEdit && !isFullMode;
  const headerMessage = whatsappOverview ? messages.whatsappOverview : zaloOverview ? messages.zaloOverview : messages.editMessageContent;
  const {
    whatsappTemplateName,
    whatsappTemplateCategory,
    whatsappTemplateLanguageCode,
  } = templateData || {};
  const templateName = whatsappTemplateName || templateData?.name;
  const showRcsTemplateName = channel.toLowerCase() === RCS && slidBoxContent === 'editTemplate' && !isFullMode && templateName;
  const showTemplateName = isWhatsappEdit || showRcsTemplateName || isZaloEdit;
  const whatsappCategory = whatsappTemplateCategory || get(templateData, `versions.base.content.whatsapp.category`, '');
  const whatsappLanguageCode = whatsappTemplateLanguageCode || get(templateData, `versions.base.content.whatsapp.languages[0].language`, '');

  const getChannelLabel = (currentChannel = '') => {
    const labels = {
      sms: <FormattedMessage {...messages.smsHeader} />,
      email: <FormattedMessage {...messages.emailHeader} />,
      mobilepush: <FormattedMessage {...messages.pushNotificationHeader} />,
      inapp: <FormattedMessage {...messages.inAppHeader} />,
      wechat: <FormattedMessage {...messages.wechat} />,
      line: <FormattedMessage {...messages.lineHeader} />,
      no_communication: <FormattedMessage {...messages.noCommunication} />,
      ftp: <FormattedMessage {...messages.ftp} />,
      whatsapp: <FormattedMessage {...messages.whatsappTemplate} />,
      rcs: <FormattedMessage {...messages.rcsCreative} />,
      zalo: <FormattedMessage {...messages.zaloTemplate} />,
      viber: <FormattedMessage {...messages.viberTemplate} />,
      webpush: <FormattedMessage {...messages.webPushTemplate} />,
    };
    return labels[currentChannel.toLowerCase()];
  };

  const openWhatsappHelpDoc = () => {
    window.open(WHATSAPP_HELP_DOC_LINK, '_blank');
  };

  return (
    <div key="creatives-container-slidebox-header-content">
      {slidBoxContent === 'templates' && !showTemplateNameHeader && (
      <CapHeader
        title={<FormattedMessage {...messages.creativeTemplates} />}
        description={![NO_COMMUNICATION, FTP].includes(channel) &&
          <FormattedMessage {...messages.creativeTemplatesDesc} />
            }
        prefix={!isFullMode && moduleType === JOURNEY &&
          <PrefixWrapper>
            <CapIcons.BackIcon onClick={handleClose} />
          </PrefixWrapper>
        }
          />
        )}
      {showTemplateNameHeader && templateNameRenderProp()}
      {slidBoxContent === 'preview' && (
      <CapHeader
        className="support-video-elements"
        title={<CapHeading className='slidebox-header-template-name' type="h1">{templateData.name}</CapHeading>}
        description={<CapLabel type="label3">
          <FormattedMessage {...messages.lastUpdated} values={{date: moment(templateData.updatedAt).format('DD MMM YYYY'), user: templateData.updatedByName}}/>
        </CapLabel>}
        prefix={!isFullMode &&
          <PrefixWrapper>
            <CapIcons.BackIcon onClick={onShowTemplates} />
          </PrefixWrapper>
            }
          />
        )}
      {!showTemplateNameHeader && slidBoxContent === 'editTemplate' && (shouldShowInAppEditHeader || !isInAppCreate) && (
        <CapHeader
          className="support-video-elements"
          title={<FormattedMessage {...headerMessage} values={{ channel: getChannelLabel(channel) }} />}
          description={
            <>
              {showTemplateName ? (
                <>
                  {renderData("label1", <FormattedMessage {...globalMessages.templateNameLabel} />, channel)}
                  <StyledLabel className='whatsapp-rcs-slidebox-template-name' type="label2">{templateName}</StyledLabel>
                </>
              ) : ""}
              {isWhatsappEdit && (
                <>
                  {renderData("label3", <FormattedMessage {...whatsppMsg.labelSeperator} />)}
                  {renderData("label1", <FormattedMessage {...whatsppMsg.templateCategoryLabel} />)}
                  {renderData("label2", formatString(whatsappCategory))}
                  {renderData("label3", <FormattedMessage {...whatsppMsg.labelSeperator} />)}
                  {renderData("label1", <FormattedMessage {...whatsppMsg.languageLabel} />)}
                  {renderData("label2", LANGUAGE_OPTIONS?.find((option) => option.value === whatsappLanguageCode)?.label)}
                </>)
              }
            </>
          }
          prefix={creativesMode !== 'edit' && !isFullMode && showPrefix &&
            <PrefixWrapper>
              <CapIcons.BackIcon onClick={onShowTemplates} />
            </PrefixWrapper>
          }
        />
      )}
      {!showTemplateNameHeader && slidBoxContent === 'createTemplate' && ( templateStep === 'modeSelection' || (templateStep === "createTemplateContent" && weChatTemplateType !== MAP_TEMPLATE) ) && (
      <CapHeader
        className="support-video-elements"
        title={<FormattedMessage {...(showCreateTraiSMSHeader ? messages.UploadSMStemplates : messages.createMessageContent)} values={{channel: getChannelLabel(channel)}}/>}
        prefix={!isFullMode && showPrefix &&
          <PrefixWrapper>
            <CapIcons.BackIcon onClick={onShowTemplates} />
          </PrefixWrapper>
            }
          />
        )}
      {isWhatsappCreate && (
      <CapLink
        onClick={openWhatsappHelpDoc}
        title={<FormattedMessage {...messages.learnTips} />}
        suffix={<CapIcon type="open-in-new" size="s" />}
        className="learn-tips-link"
          />
        )}
      {mapTemplateCreate && (
        <CapSteps
          onChange={onWeChatMaptemplateStepChange}
          current={weChatMaptemplateStep}
          size="small"
          className="wechat-steps"
        >
          <CapSteps.CapStep
            title={<CapLabel type="label8"><FormattedMessage {...messages.selectTemplate} /></CapLabel>}
          />
          <CapSteps.CapStep
            title={<CapLabel type="label8"><FormattedMessage {...messages.addContent} /></CapLabel>}
            disabled
          />
        </CapSteps>
        )}
    </div>
  );
}
SlideBoxHeader.propTypes = {
  slidBoxContent: PropTypes.node,
  templateData: PropTypes.object,
  onShowTemplates: PropTypes.func,
  creativesMode: PropTypes.string,
  isFullMode: PropTypes.bool,
  showPrefix: PropTypes.bool,
  channel: PropTypes.string,
  shouldShowTemplateName: PropTypes.bool,
  templateNameRenderProp: PropTypes.func,
  smsRegister: PropTypes.any,
};
export default SlideBoxHeader;
