import React, { Component } from 'react';
import PropTypes from 'prop-types';
import SimpleMDE from 'simplemde';

import 'simplemde/dist/simplemde.min.css';
import './InstructionsEditor.css';

class InstructionsEditor extends Component {
  constructor(props) {
    super(props);
    this.destroySimpleMDE = this.destroySimpleMDE.bind(this);
  }

  componentDidMount() {
    const { code, onAnyCode } = this.props;
    this.destroySimpleMDE();
    this.simplemde = new SimpleMDE({
      element: this.textarea,
      initialValue: code,
      renderingConfig: {
        codeSyntaxHighlighting: true,
      },
      showIcons: ['code', 'table'],
      hideIcons: ['preview'],
      shortcuts: {
        'drawLink': 'Cmd-U',
      },
    });
    this.simplemde.codemirror.on('change', () => {
      onAnyCode(this.simplemde.value());
    });
  }

  componentWillUnmount() {
    this.destroySimpleMDE();
  }

  destroySimpleMDE() {
    const simplemde = this.simplemde;
    if (simplemde) {
      simplemde.toTextArea();
      this.simplemde = null;
    }
  }

  render() {
    return (
      <textarea
        id="instructions-markdown-editor"
        ref={(textarea) => { this.textarea = textarea; }}
      />
    );
  }
}

InstructionsEditor.propTypes = {
  code: PropTypes.string,
  onAnyCode: PropTypes.func.isRequired,
};

InstructionsEditor.defaultProps = {
  code: '',
};

export default InstructionsEditor;
