import React from 'react';
import Accordion from '../../shared/Accordion';
import { connect } from 'react-redux';

import { showError, showSuccess } from '../../../../actions/notice';

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

    this.state = props.base;
    this.state.showStatuses = !!props.showStatuses;

    this.handleTitleChange = this.handleTitleChange.bind(this);
    this.handleTitleBlur = this.handleTitleBlur.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleTagChange = this.handleTagChange.bind(this);
    this.handleRemoveTag = this.handleRemoveTag.bind(this);
    this.handlePublish = this.handlePublish.bind(this);
    this.handleStatusChange = this.handleStatusChange.bind(this);
    this.toggleStatusDropdown = this.toggleStatusDropdown.bind(this);
  }

  updateParentState(cb) {
    this.props.onChange({
      title: this.state.title,
      slug: this.state.slug,
      layout: this.state.layout,
      tags: this.state.tags,
      status: this.state.status
    }, cb);
  }

  updateState(newState, cb) {
    this.setState(newState, () => {
      this.updateParentState(cb);
    });
  }

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

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

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

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

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

  handleRemoveTag(e) {
    this.state.tags.splice(e.target.getAttribute('data-index'), 1);

    this.updateState({ tags: this.state.tags })
  }

  handleTagChange(e) {
    this.setState({ tag: e.target.value });

    if (e.which !== 13) {
      return;
    }

    e.preventDefault();
    if (!e.target.value) {
      return;
    }

    const tags = this.state.tags.concat([e.target.value])
      .filter((value, index, self) => self.indexOf(value) === index);

    this.updateState({ tags: tags, tag: '' });
  }

  handlePublish(e) {
    e.persist();

    this.updateState({ status: 'published' }, this.props.saveEntry);

    this.setState({ showStatuses: false });
  }

  renderTitleInput() {
    return (
      <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">Slug allows you to define SEO-friendly url paths. There can be only one content entry with given slug.</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="About Us" 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="about-us" onChange={this.handleInputChange} />
          </div>
        </div>
      </div>
    );
  }

  renderLayoutInput() {
    const layouts = this.props.entryType.layouts;
    if (!layouts || Object.keys(layouts).length < 2) {
      return null;
    }

    return (
      <React.Fragment>
        <div className="columns">
          <div className="column-12 column-mobile-6">
            <div className="field field-info">
              <h3 className="field-info-title">Choose field layout</h3>
              <p className="field-info-text">Layout defines a set of fields which are available. After page is saved, it is not possible to change the layout.</p>
            </div>
          </div>
          <div className="column-12 column-mobile-6">
            <div className="field">
              <label htmlFor="layout">Layout</label>
              <select name="layout" id="layout" value={this.state.layout} disabled={this.props.editing} onChange={this.handleInputChange}>
                {Object.entries(layouts).map(([name, layout]) => {
                  return <option key={name} value={name}>{layout.title}</option>;
                })}
              </select>
            </div>
          </div>
        </div>
        <hr/>
      </React.Fragment>
    );
  }

  renderTags() {
    return (
      <div className="columns">
        <div className="column-12 column-mobile-6">
          <div className="field field-info">
            <h3 className="field-info-title">Choose page Tags</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.</p>
          </div>
        </div>
        <div className="column-12 column-mobile-6">
          <div className="field">
            <label htmlFor="tags">Tags</label>
            <input type="search" name="tags" value={this.state.tag} id="tags" className="input-text" onChange={this.handleTagChange} onKeyDown={this.handleTagChange} autoComplete="off"/>
          </div>
          <div className="field">
            {this.state.tags.map((tag, index) => {
              return <span className="tag" key={tag}>#{tag}<button type="button" data-index={index} onClick={this.handleRemoveTag}>&times;</button></span>;
            })}
          </div>
        </div>
      </div>
    );
  }

  renderPublishButton() {

    if (this.state.status === 'published') {
      return null;
    }

    return <button type="button" className="btn btn-green" onClick={this.handlePublish}>Publish</button>;
  }

  handleStatusChange(e) {
    e.persist();

    this.updateState({ status: e.target.getAttribute('data-status') }, this.props.saveEntry);
    this.setState({ showStatuses: false });
  }

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

  renderStatusDropdown() {

    if (!this.state.showStatuses) {
      return;
    }

    return (
      <ul className="dropdown">
         <li className="dropdown-item">
            <button type="button" className={`btn btn-link ${(this.state.status === 'draft') ? 'active-status' : ''}`} data-status="draft" onClick={this.handleStatusChange}>Draft</button>
         </li>
         <li className="dropdown-item">
           <button type="button" className={`btn btn-link ${(this.state.status === 'published') ? 'active-status' : ''}`} data-status="published" onClick={this.handleStatusChange}>Published</button>
         </li>
      </ul>
    );
  }

  render() {
    return (
      <Accordion title="Page settings" desc="Set up things like title, slug and layout of your entry" open>
        <div className="box-content">
          {this.renderTitleInput()}
          <hr/>
          {this.renderLayoutInput()}

          {this.renderTags()}
        </div>
        <div className="box-footer">
          <div>
            <button type="button" className="btn btn-blue" onClick={this.props.saveEntry}>Save</button>
            {this.renderPublishButton()}
          </div>
          <div>
            <span className="dropdown-wrapper">
              Status: <strong className={`badge-status badge-status-${this.state.status} dropdown-trigger`} onClick={this.toggleStatusDropdown}>{this.state.status}</strong>
              {this.renderStatusDropdown()}
            </span>
            <i className="vert"/>
            <span>24/09/2019</span>
          </div>
        </div>
      </Accordion>
    );
  }
}

export default connect(
  (state) => ({
    site: state.site
  }),
  { showError, showSuccess }
)(BaseFields);
