/**
*
* EmailPreviewV2
*
*/

import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { isEmpty, get } from 'lodash';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { createStructuredSelector } from 'reselect';
import { CapSpin, CapTab, CapIcon, CapLabel } from '@capillarytech/cap-ui-library';
import { CAP_G01, CAP_G06, FONT_SIZE_VL } from '@capillarytech/cap-ui-library/styled/variables';
import moment from 'moment';
import messages from './messages';
import './_emailPreviewV2.scss';
import tabletBody from '../../assets/iPad.svg';
import mobileBody from '../../assets/DeviceForEmail.png';
import { iframePreviewAdjustWidth, removeLinksFromHtmlContent } from './../../utils/common';

import {selectTemplateContent} from '../../v2Containers/Templates/selectors';
import * as templateActions from '../../v2Containers/Templates/actions';
import { EMAIL } from '../../v2Containers/CreativesContainer/constants';

const deviceAspectRatio = {
  desktop: () => ({
    height: "500",
    width: "1024",
  }),
  tablet: (emailSubject) => ({
    height: emailSubject ? "570" : "600",
    width: "450",
  }),
  mobile: (emailSubject) => ({
    height: emailSubject ? "541" : "511",
    width: "340",
  }),
};
const devices = {
  mobile: 'mobile',
  desktop: 'desktop',
  tablet: 'tablet',
};

const StyledCapIcon = styled(CapIcon)`
  color: ${(props) => props.active ? CAP_G01 : CAP_G06};
  font-size: ${FONT_SIZE_VL};
`;

export class EmailPreviewV2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentDevice: props.device || devices.desktop,
    };
  }
  componentWillMount() {
    const {templateData, templateContent} = this.props;
    if (isEmpty(templateContent) && !isEmpty(templateData) && templateData._id) { // templateData: comes from templates list email preview
      this.props.templateActions.getTemplateDetails(templateData._id, EMAIL); // templateContent: html data to be shown in iframe
    }
  }
  componentWillUnmount() {
    this.props.templateActions.resetTemplateData();
  }
  changePreviewDevice = (device) => {
    this.setState({currentDevice: device});
  }
  render() {
    let messageContainerName = '';
    const {currentDevice} = this.state;
    const { templateContent, templateData = {}, templateSubject } = this.props;
    const copyContent = templateContent && removeLinksFromHtmlContent(templateContent);
    const updateCopyContent = templateContent && iframePreviewAdjustWidth(copyContent);
    let subjectClassName = 'email-subject-desktop';
    if (currentDevice === devices.tablet) {
      messageContainerName = 'tablet-message-container';
      subjectClassName = "email-subject-tablet";
    } else if (currentDevice === devices.mobile) {
      messageContainerName = 'mobile-message-container';
      subjectClassName = "email-subject-mobile";
    }
    const emailSubject = get(templateData, 'versions.base.subject') || templateSubject;
    const emailSubjectLabel = emailSubject && (
      <CapLabel className={subjectClassName} type="label2">
        <FormattedMessage {...messages.subject} /> {emailSubject}</CapLabel>
    );
    const iframeDiv = (<div className={`${messageContainerName}`}>
      {emailSubjectLabel}
      <iframe srcDoc={updateCopyContent} {...deviceAspectRatio[currentDevice](emailSubject)} >
        <p><FormattedMessage {...messages.browserDoesntSupportIframe} /></p>
      </iframe>
    </div>);


    return (
      <div className="email-preview-v2">
        <CapSpin spinning={!templateContent}>
          <div id="emailPreivew-container">
            <div id="emailPreivew-content-wrapper">
              <div id="emailPreivew-content">
                <CapTab
                  className="email-preview-device-tabs"
                  activeKey={currentDevice}
                  onChange={this.changePreviewDevice}
                  panes={[
                    {
                      key: 'desktop',
                      tab: <StyledCapIcon type="desktop" active={currentDevice === 'desktop'} />,
                      content: <div className="email-preview-container">
                        {iframeDiv}
                      </div>,
                    },
                    {
                      key: 'tablet',
                      tab: <StyledCapIcon type="tablet" active={currentDevice === 'tablet'} />,
                      content: (<div className="email-preview-container">
                        <div className="shell align-center">
                          <img src={tabletBody} alt="capillary" width="520" />
                          {iframeDiv}
                        </div>
                      </div>),
                    },
                    {
                      key: 'mobile',
                      tab: <StyledCapIcon type="mobile" active={currentDevice === 'mobile'} />,
                      content: (<div className="email-preview-container">
                        <div className="shell align-center">
                          <img src={mobileBody} alt="capillary" width="386" />
                          {iframeDiv}
                        </div>
                      </div>),
                    },
                  ]}
                  />
                {/* <div className="email-preview-container">
                  <div className={currentDevice === devices.desktop ? '' : "shell align-center"}>
                    {currentDevice === devices.tablet ?
                      <img src={tabletBody} alt="capillary" width="520" /> : ''}
                    {currentDevice === devices.mobile ?
                      <img src={mobileBody} alt="capillary" width="85%" /> : ''}
                    <div className={messageContainerName}>
                      <iframe id="email-iframe" srcDoc={templateContent} {...deviceAspectRatio[currentDevice]} >
                        <p><FormattedMessage {...messages.noIframeSupport}/></p>
                      </iframe>
                    </div>
                  </div>


                </div> */}
              </div>
            </div>
          </div>
          {this.props.templateData && this.props.templateData.updatedByName &&
            [
              <p className="preview-info" key="lastModified"><FormattedMessage {...messages.lastModified} />: {moment(this.props.templateData.updatedAt).format('MM-DD-YYYY')}</p>,
              <p style={{marginBottom: '8px'}} key="uploadedBy" className="preview-info"><FormattedMessage {...messages.uploadedBy} /> : {this.props.templateData.updatedByName}</p>,
            ]
        }
        </CapSpin>
      </div>

    );
  }

}

EmailPreviewV2.propTypes = {
  templateContent: PropTypes.string,
  templateSubject: PropTypes.string,
  templateData: PropTypes.object,
  templateActions: PropTypes.object,
  device: PropTypes.string,
};

const mapStateToProps = (state, props) => createStructuredSelector({
  templateContent: props.templateData ? selectTemplateContent() : () => props.templateContent, // when props has templateContent that means preview with content
});
function mapDispatchToProps(dispatch) {
  return {
    templateActions: bindActionCreators(templateActions, dispatch),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(EmailPreviewV2);
