import React from 'react';
import { Link } from 'react-router-dom';

class Header extends React.Component {
  state= {
    show: false
  };

  constructor(props) {
    super(props);

    this.state.show = !!props.show;

    this.onToggle = this.onToggle.bind(this);
  }

  onToggle() {
    this.setState({ show: !this.state.show });
  }

  renderDeleteButton() {
    if (!this.props.editing) {
      return null;
    }

    return (
      <React.Fragment>
        <i className="vert"/>
        <button type="button" className="btn btn-link" onClick={this.onToggle}>Delete this {this.props.entryType.title}</button>
      </React.Fragment>
    );
  }

  renderDeletePopup() {
    if (!this.state.show) {
      return;
    }

    return (
      <div className="popup">
        <div className="box box-center-narrow box-card">
          <div className="box-content">
            <h3>Are you sure that you want to delete this post?</h3>
          </div>
          <div className="box-footer">
            <div>
              <button type="button" className="btn btn-blue" onClick={this.onToggle}>Cancel</button>
              <button type="button" className="btn btn-red" onClick={this.props.onDelete}>Delete</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  render() {
    return (
      <React.Fragment>
        <div className="title title-action">
          <div>
            <Link to={`/entries/${this.props.entryType.title.toLowerCase()}`} className="btn btn-link">Back to all {this.props.entryType.plural}</Link>
            {this.renderDeleteButton()}
            <i className="vert"/>
            <button type="button" className="btn btn-blue" onClick={this.props.saveEntry}>Save</button>
          </div>
          <div>
            <h1>{this.props.editing ? 'Edit' : 'New'} {this.props.entryType.title}</h1>
            <p>{this.props.entryType.desc}</p>
          </div>
        </div>
        {this.renderDeletePopup()}
      </React.Fragment>
    );
  }
}

export default Header;
