import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import TextArea from '@bufferapp/ui/TextArea';
import Button from '@bufferapp/ui/Button';

const Form = styled.form`
  margin-top: 20px;
  padding: 0;
  display: flex;
  align-items: center;
`;

const InputWrapper = styled.div`
  margin-right: 8px;
  width: 100%;
`;

const ButtonWrapper = styled.div`
  margin-right: 8px;
`;

const ButtonMargin = styled.div`
  display: flex;
  margin-top: 16px;
`;

class EditDescription extends Component {
  constructor(props) {
    super(props);

    this.state = {
      description: props.description,
    };
    this.textInput = React.createRef();
    this.clearButton = React.createRef();
  }

  componentDidMount() {
    this.textInput.current.focus(); // focus the input when the component mounts
  }

  handleBlur = (e) => {
    // we're using this to clear the form because the onBlur hits before onClick
    if (this.clearButton.current.contains(e.relatedTarget)) {
      this.props.saveDescription('');
    } else {
      this.props.saveDescription(this.state.description);
    }
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.saveDescription(this.state.description);
  };

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

  render() {
    return (
      <Form onSubmit={this.handleSubmit}>
        <InputWrapper>
          <TextArea
            label="Report Summary"
            id="description"
            forwardRef={this.textInput}
            value={this.state.description}
            onChange={this.handleChange}
            onBlur={this.handleBlur}
          />
        </InputWrapper>
        <ButtonMargin>
          <ButtonWrapper ref={this.clearButton}>
            <Button type="secondary" label="Clear" onClick={() => {}} />
          </ButtonWrapper>
          <Button type="primary" onClick={this.handleSubmit} label="OK" />
        </ButtonMargin>
      </Form>
    );
  }
}

EditDescription.propTypes = {
  description: PropTypes.string.isRequired,
  saveDescription: PropTypes.func.isRequired,
};

export default EditDescription;
