/**
*
* ToastrMessage
*
*/

import PropTypes from 'prop-types';

import React from 'react';
import { FormattedMessage } from 'react-intl';
import styled from 'styled-components';
import { messageTypeConfig } from '../../config/toastr';
import messages from './messages';

const StyledMessageWrapper = styled.div`
  background: #f9f9fa;
  transition: all .2s fade-out;
  -webkit-box-shadow: 2px 2px 10px -1px rgba(0,0,0,0.39);
  -moz-box-shadow: 2px 2px 10px -1px rgba(0,0,0,0.39);
  box-shadow: 2px 2px 10px -1px rgba(0,0,0,0.39);
  border-radius: 5px;
`;
const StyleIcon = styled.i`
  float: right;
  cursor: pointer;
  fontSize: 16px;
`;
const MessageContent = styled.div`
  padding-left: 14px;
`;

const MessageHeader = styled.div`
  padding-left: 14px;
  font-weight: bold;
  font-family: proxima-nova,sans-serif;
`;

const StyledMessageType = styled.div `
  position: absolute;
  width: 10px;
  height: 100%;
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
`;

class ToastrMessage extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(prop) {
    super(prop);
    this.state = { percent: 0 };
    this.intervalId = null;
    this.closeMessagePopup = this.closeMessagePopup.bind(this);
  }

  componentDidMount() {
    const distance = 100 / ((this.props.timeout - 500) / 100);
    if (this.props.timeout && this.props.timeout > 500) {
      this.intervalId = setInterval(() => {
        const percent = this.state.percent + distance;
        this.setState({ percent: percent < 100 ? percent : 100 });
      }, 100);
    }
  }

  componentDidUpdate() {
    if (this.state.percent >= 100 && this.intervalId) {
      this.props.handleMessageClose(this.props.messageId);
      clearTimeout(this.intervalId);
    }
  }

  componentWillUnmount() {
    if (this.intervalId) {
      clearTimeout(this.intervalId);
    }
  }

  closeMessagePopup(messageIndex) {
    this.props.handleMessageClose(messageIndex);
  }


  render() {
    return (
      <StyledMessageWrapper key={this.props.messageId}>
        <StyledMessageType style={{ ...messageTypeConfig[this.props.type] }} />
        <div style={{ padding: `${16}px` }}>
          <MessageHeader>
            { this.props.title ? <span style={{ fontSize: `${20}px` }}>{this.props.title}</span> : '' }
            <StyleIcon className="material-icons" onClick={() => this.closeMessagePopup(this.props.messageId)}><FormattedMessage {...messages.close} /></StyleIcon>
          </MessageHeader>
          <MessageContent>
            {this.props.text}
          </MessageContent>
        </div>
      </StyledMessageWrapper>
    );
  }
}

ToastrMessage.propTypes = {
  messageId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  timeout: PropTypes.oneOfType([PropTypes.number, PropTypes.bool]),
  title: PropTypes.string,
  text: PropTypes.string,
  type: PropTypes.string,
  handleMessageClose: PropTypes.func,
};

export default ToastrMessage;
