import React from 'react';

import { Link, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { admin as adminApi } from '@devcms/sdk';

class TagsForm extends React.Component {
  constructor(props) {
    super(props);

    const { match: { params: { id } } } = props;

    this.state = {
      show: false,
      loaded: false,
      redirect: null,

      title: '',
      slug: '',
      tag: null,

      id: id,
    };

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleTitleChange = this.handleTitleChange.bind(this);
    this.handleTitleBlur = this.handleTitleBlur.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  static getDerivedStateFromProps(props, state) {
    if (props.match.params.id !== state.id) {
      return {
        tag: null,
        loaded: false,
        redirect: null,
        id: props.match.params.id,
      };
    }

    return null;
  }

  componentDidMount() {
    this.fetchTag();
  }

  componentDidUpdate() {
    if (this.state.loaded === false) {
      this.fetchTag();
    }
  }

  fetchTag() {
    if (this.state.id) {
      adminApi.tags.get(this.state.id).then(tag => {
        this.setState({
          tag: tag, loaded: true,
          title: tag.title, slug: tag.slug,
        });
      });
    } else {
      this.setState({
        title: '', slug: '',
        loaded: true,
      });
    }
  }

  convertToSlug(value) {
    return value.replace(/[^\w- ]+/g, '').replace(/ +/g,'-').toLowerCase()
  }

  handleInputChange({ target }) {
    const value = target.type === 'checkbox' ? target.checked : target.value;

    this.setState({ [target.name]: value });
  }

  handleTitleChange({ target: { value } }) {
    this.setState({ title: value });
  }

  handleTitleBlur({ target: { value } }) {
    this.setState({ slug: this.state.slug || this.convertToSlug(value) });
  }

  handleSubmit(e) {
    e.preventDefault();

    this.state.tag ? this.update() : this.create();
  }

  create() {
    adminApi.tags.create({
      title: this.state.title,
      slug: this.state.slug,
    }).then(tag => {
      this.setState({
        tag: tag,
        redirect: `/tags/${tag.id}`
      });
    }).catch(error => this.setState({ error: error }));
  }

  update() {
    adminApi.tags.update(this.state.tag.id, {
      title: this.state.title,
      slug: this.state.slug,
    }).then(tag => this.setState({ tag: tag }))
      .catch(error => this.setState({ error: error }));
  }

  handleDelete() {
    this.delete();
  }

  delete() {
    adminApi.tags.delete(this.state.tag.id).then(() => {
      this.setState({ redirect: `/tags/` });
    }).catch(error => this.props.showError('Error occurred while deleting record.'));
  }

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

  renderDeleteButton() {
    if (!this.state.tag) {
      return null;
    }

    return <button type="button" className="btn btn-link" onClick={this.onToggle.bind(this)}>Delete</button>;
  }

  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 {this.state.title}?</h3>
          </div>
          <div className="box-footer">
            <div>
              <button type="button" className="btn btn-blue" onClick={this.onToggle.bind(this)}>Cancel</button>
              <button type="button" className="btn btn-red" onClick={this.handleDelete.bind(this)}>Delete</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  render() {
    if (this.state.redirect) {
      return <Redirect to={this.state.redirect}/>
    }

    if (!this.state.loaded) {
      return null;
    }

    return (
      <form onSubmit={this.handleSubmit}>
        <div className="title title-action">
          <div>
            <Link to="/tags" className="btn btn-link">Back to all tags</Link>
            <i className="vert"/>
            {this.renderDeleteButton()}
            <i className="vert"/>
            <button type="submit" className="btn btn-blue">Save</button>
          </div>
          <div>
            <h1>New tag</h1>
            <p>Tags are taxonomy which can be used to filter and organize your content</p>
          </div>
        </div>

        <div className="box box-card">
          <div className="box-content">
            <div className="columns">
              <div className="column-12 column-mobile-6">
                <div className="field field-info">
                  <h3 className="field-info-title">Title and Slug</h3>
                  <p className="field-info-text">A tag is a sort of taxonomy which you can use to categorize your entries. Each entry can contain multiple tags and visitors can click on a tag to find similar entries that have that same tag. There can be only one tag with given slug. Slug allows you to define SEO-friendly url paths.</p>
                </div>
              </div>
              <div className="column-12 column-mobile-6">
                <div className="field">
                  <label htmlFor="title">Title</label>
                  <input type="text" name="title" id="title" value={this.state.title} className="input-text" placeholder="Digital Marketing" onChange={this.handleTitleChange} onBlur={this.handleTitleBlur}/>
                </div>
                <div className="field">
                  <label htmlFor="slug">Slug</label>
                  <input type="text" name="slug" id="slug" value={this.state.slug} className="input-text" placeholder="digital-marketing" onChange={this.handleInputChange}/>
                </div>
              </div>
            </div>
          </div>

          <div className="box-footer">
            <button type="submit" className="btn btn-blue">Save</button>
          </div>
        </div>
        {this.renderDeletePopup()}
      </form>
    );
  }
}

export default connect(
  (state) => ({
    site: state.site
  })
)(TagsForm);
