/**
*
* NewCallTask
*
*/

import React from 'react';
import PropTypes from 'prop-types';
import { CapRow, CapColumn, CapInput, CapButton, CapSpin, CapCheckbox } from '@capillarytech/cap-ui-library';
import { injectIntl, intlShape, FormattedMessage } from 'react-intl';
import {
  FONT_SIZE_S,
} from '@capillarytech/cap-ui-library/styled/variables';
import TagList from '../../v2Containers/TagList';
import CallTaskPreview from '../CallTaskPreview';
import messages from './messages';
import './_newCallTask.scss';
import { hasStore2DoorFeature } from '../../utils/common';

const CALL = 'CALL';
const STOREMAX_WHATSAPP = 'STOREMAX_WHATSAPP';
class NewCallTask extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.state = this.getInitialState();
  }

  getInitialState = () => {
    const { templateData, messageDetails, mode } = this.props;
    const actionType = mode === 'edit' ? messageDetails.messageContent.message_content_id_1.callTaskActionType : CALL;
    return {
      subject: templateData && templateData.subject ? templateData.subject : '',
      messageBody: templateData && templateData.messageBody ? templateData.messageBody : '',
      description: templateData && templateData.description ? templateData.description : '',
      callTaskActionType: actionType,
    };
  }

  onTagSelect = (data) => {
    this.insertAtCursor(`{{${data}}}`);
  }

  setInputRef = (textarea) => {
    this.textArea = textarea;
  }

  insertAtCursor = (myValue) => {
    this.textArea.focus();
    const textAreaRef = this.textArea.textAreaRef;
    let pos = textAreaRef.selectionEnd + myValue.length;
    //IE support
    let newMessage = textAreaRef.value + myValue;
    if (document.selection) {
      this.textArea.focus();
      const sel = document.selection.createRange();
      sel.text = myValue;
    } else if (textAreaRef.selectionStart || textAreaRef.selectionStart === '0') { //MOZILLA and others
      const startPos = textAreaRef.selectionStart;
      const endPos = textAreaRef.selectionEnd;
      newMessage = textAreaRef.value.substring(0, startPos) + myValue + textAreaRef.value.substring(endPos, textAreaRef.value.length);
      pos = startPos + myValue.length;
    }
    this.setState({
      messageBody: newMessage,
    }, () => {
      textAreaRef.selectionStart = pos;
      textAreaRef.selectionEnd = pos;
    });
  };

  updateSubject = (e) => {
    this.setState({
      subject: e.target.value,
    });
  }

  updateMessageBody = (e) => {
    this.setState({
      messageBody: e.target.value,
    });
  }

  updateDescription = (e) => {
    this.setState({
      description: e.target.value,
    });
  }

  submitForm = () => {
    this.props.onCallTaskSubmit(this.state);
  }

  onS2DCheckChange = (e) => {
    if (e.target.checked) {
      this.setState({callTaskActionType: STOREMAX_WHATSAPP});
    } else {
      this.setState({callTaskActionType: CALL});
    }
  };

  render() {
    const { intl, isLoading, metaEntities, selectedOfferDetails , injectedTags} = this.props;
    const { formatMessage } = intl;
    const { subject, messageBody, description, callTaskActionType } = this.state;
    const tags = metaEntities && metaEntities.tags ? metaEntities.tags.standard : [];
    const isStore2DoorEnabled = hasStore2DoorFeature();
    return (
      <CapSpin spinning={isLoading}>
        <CapRow gutter={16}>
          <CapColumn span={12}>
            <div style={{ height: 'calc(100vh - 187px)', overflowY: 'auto', paddingRight: "8px" }}>
              <div style={{ marginBottom: '34px' }}>
                <CapInput
                  label={formatMessage(messages.callTaskTitle)}
                  onChange={this.updateSubject}
                  value={subject}
                  isRequired
                  size="default"
                />
              </div>
              <div style={{ position: 'relative', marginBottom: '34px' }}>
                <TagList
                  className="new-call-task-tagList"
                  label={formatMessage(messages.personalisationTags)}
                  tags={tags}
                  onTagSelect={this.onTagSelect}
                  selectedOfferDetails={selectedOfferDetails}
                  injectedTags={injectedTags}
                />
                <CapInput.TextArea
                  setInputRef={this.setInputRef}
                  label={formatMessage(messages.messageHeader)}
                  onChange={this.updateMessageBody}
                  value={messageBody}
                  isRequired
                />
              </div>
              <CapInput.TextArea
                label={formatMessage(messages.description)}
                onChange={this.updateDescription}
                value={description}
                isRequired
                />
              {isStore2DoorEnabled && <CapCheckbox
                onChange={this.onS2DCheckChange}
                checked={callTaskActionType === STOREMAX_WHATSAPP}
                style={{marginTop: FONT_SIZE_S}}
              >
                <FormattedMessage {...messages.useInS2D}/>
              </CapCheckbox>}
            </div>
            <CapButton
              disabled={!subject || !messageBody || !description}
              className="new-call-task-done-button"
              onClick={this.submitForm}>
              {formatMessage(messages.done)}
            </CapButton>
          </CapColumn>
          <CapColumn span={12}>
            <CallTaskPreview
              subject={subject}
              messageBody={messageBody}
              callTaskActionType={callTaskActionType}
            />
          </CapColumn>
        </CapRow>
      </CapSpin>
    );
  }
}

NewCallTask.propTypes = {
  intl: intlShape.isRequired,
  onCallTaskSubmit: PropTypes.func,
  templateData: PropTypes.object,
  isLoading: PropTypes.bool,
  metaEntities: PropTypes.object,
  selectedOfferDetails: PropTypes.array,
  messageDetails: PropTypes.object,
  mode: PropTypes.string,
  injectedTags: PropTypes.object,
};

export default injectIntl(NewCallTask);
