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

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

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

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

    this.state = {
      name: props.name,
    };
    this.textInput = React.createRef(); // focus the input when the component mounts
  }

  componentDidMount() {
    this.textInput.current.focus();
  }

  handleBlur = () => {
    this.props.saveChanges(this.state.name);
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.saveChanges(this.state.name);
  }

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

  render() {
    return (
      <Form>
        <Wrapper>
          <Input
            ref={this.textInput}
            value={this.state.name}
            onChange={this.handleChange}
            onBlur={this.handleBlur}
            autoFocus
          />
        </Wrapper>
        <Button type="primary" onClick={this.handleSubmit} label="OK" />
      </Form>
    );
  }
}

EditTitle.propTypes = {
  name: PropTypes.string.isRequired,
  saveChanges: PropTypes.func.isRequired,
};

export default EditTitle;
