import React from 'react';
import { EditorState, RichUtils, convertToRaw, convertFromRaw, AtomicBlockUtils } from 'draft-js';

import Editor from 'draft-js-plugins-editor';
import createImagePlugin from 'draft-js-image-plugin';
import { admin as adminApi } from '@devcms/sdk';

const imagePlugin = createImagePlugin();
const plugins = [imagePlugin];

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

    let editorState;
    try {

      let value = '';
      // Backward compatibility for old richtext format
      if (typeof props.value === 'string') {
        value = JSON.parse(props.value);
      } else {
        value = props.value;
      }

      editorState = EditorState.createWithContent(convertFromRaw(value));
    } catch {
      editorState = EditorState.createEmpty();
    }

    this.state = { editorState: editorState };

    this.handleEditorChange = this.handleEditorChange.bind(this);
    this.handleKeyCommand = this.handleKeyCommand.bind(this);
  }

  handleEditorChange(editorState) {
    this.setState({ editorState });

    this.props.onChange(this.props.name, JSON.stringify(convertToRaw(editorState.getCurrentContent())));
  }

  handleKeyCommand(command, editorState) {
    const newState = RichUtils.handleKeyCommand(editorState, command);
    if (newState) {
      this.handleEditorChange(newState);
      return 'handled';
    }

    return 'not-handled';
  }

  renderControls() {
    const selection = this.state.editorState.getSelection();
    const blockType = this.state.editorState
      .getCurrentContent()
      .getBlockForKey(selection.getStartKey())
      .getType();

    return [
      { label: 'B', style: 'BOLD', toggleMethod: RichUtils.toggleInlineStyle },
      { label: 'I', style: 'ITALIC', toggleMethod: RichUtils.toggleInlineStyle },
      { label: 'U', style: 'UNDERLINE', toggleMethod: RichUtils.toggleInlineStyle },

      { label: 'H2', style: 'header-two', toggleMethod: RichUtils.toggleBlockType },
      { label: 'H3', style: 'header-three', toggleMethod: RichUtils.toggleBlockType },
      { label: 'H4', style: 'header-four', toggleMethod: RichUtils.toggleBlockType },
      { label: 'Quote', style: 'blockquote', toggleMethod: RichUtils.toggleBlockType },
      { label: 'UL', style: 'unordered-list-item', toggleMethod: RichUtils.toggleBlockType },
      { label: 'OL', style: 'ordered-list-item', toggleMethod: RichUtils.toggleBlockType },
      { label: 'Code', style: 'code-block', toggleMethod: RichUtils.toggleBlockType },
    ].map((type) => {
      const className = [
        'richtext-toolbar-btn',
        `richtext-toolbar-btn-${blockType === type.style ? 'active' : ''}`,
        `richtext-toolbar-btn-${type.style.toLowerCase()}`
      ].join(' ');

      const toggle = () => this.handleEditorChange(type.toggleMethod(this.state.editorState, type.style));

      return <button key={type.style} type="button" className={className} onMouseDown={toggle}>{type.label}</button>;
    }).concat([this.renderAttachButton()]);
  }

  renderAttachButton() {
    return <button key='img-upload' className="richtext-toolbar-btn-image-upload">
            <label htmlFor="image-upload">Img</label>
            <input id="image-upload" type="file" onChange={this.handleFileChange.bind(this)} />
          </button>
  }

  handleFileChange(e) {
    adminApi.media.upload({
      file: e.target.files[0]
    }).then(media => {
      const state = this.insertImage(this.state.editorState, media.url);
      this.handleEditorChange(state);
    });
  }

  insertImage(editorState, url) {
    const contentState = editorState.getCurrentContent();
    const contentStateWithEntity = contentState.createEntity(
      'image',
      'IMMUTABLE',
      { src: url }
    );

    const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
    const newEditorState = EditorState.set(editorState, {
      currentContent: contentStateWithEntity
    });

    return AtomicBlockUtils.insertAtomicBlock(newEditorState, entityKey, ' ');
  };

  render() {

    return (
      <div className="box-content">
        <div className="columns">
          <div className="column-12">
            <div className="field field-info">
              <h3 className="field-info-title">{this.props.title}</h3>
              <p className="field-info-text">{this.props.desc}</p>
            </div>
          </div>
          <div className="column-12">
            <div className="richtext">
              <div className="richtext-toolbar">{this.renderControls()}</div>
              <Editor
                plugins={plugins}
                editorState={this.state.editorState}
                handleKeyCommand={this.handleKeyCommand}
                onChange={this.handleEditorChange}
                placeholder="Start writing..."
              />
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default FieldRichText;
