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

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 EditChartNote extends Component {
  constructor(props) {
    super(props);

    this.state = {
      note: props.note || ""
    };

    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.saveChartNote(this.props.chartId, "");
    } else {
      this.props.saveChartNote(this.props.chartId, this.state.note);
    }
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.saveChartNote(this.props.chartId, this.state.note);
  };

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

  render() {
    return (
      <Form onSubmit={this.handleSubmit}>
        <InputWrapper>
          <TextArea
            label="Report Note"
            id="note"
            forwardRef={this.textInput}
            value={this.state.note}
            onChange={this.handleChange}
            onBlur={this.handleBlur}
          />
        </InputWrapper>
        <ButtonMargin>
          <ButtonWrapper ref={this.clearButton}>
            <Button
              type="secondary"
              label="Clear"
              onClick={() => {}} // empty function here because it's required in bufferui
            />
          </ButtonWrapper>
          <Button type="primary" onClick={this.handleSubmit} label="OK" />
        </ButtonMargin>
      </Form>
    );
  }
}

EditChartNote.propTypes = {
  chartId: PropTypes.string.isRequired,
  note: PropTypes.string,
  saveChartNote: PropTypes.func.isRequired
};

EditChartNote.defaultProps = {
  chartId: "",
  note: ""
};

export default EditChartNote;
