// 3rd-Party Libraries
import React from 'react';
import PropTypes from 'prop-types';
import debounce from 'lodash/debounce';

// Permissions
import { PermissionContext } from '@ui/compositions/Tutorials/Modal';

// Readme Libs
const syntaxHighlighter =
  typeof window !== 'undefined' ? require('@readme/syntax-highlighter/dist/index.js').default : () => {};

export default function TutorialResponse({ response, updateTutorial }) {
  const handleChange = (value, { origin }, readOnly) => {
    if (['+input', 'paste', '+delete'].includes(origin) && !readOnly) {
      updateTutorial({ response: value });
    }
  };

  const onChange = process.env.NODE_ENV === 'test' ? handleChange : debounce(handleChange, 300);
  const codeMirrorOpts = readOnly => (readOnly ? { highlightMode: true, tokenizeVariables: true } : { editable: true });

  return (
    <PermissionContext.Consumer>
      {readOnly => (
        <React.Fragment>
          {syntaxHighlighter(response, 'json', codeMirrorOpts(readOnly), {
            onChange: (editor, data, value) => onChange(value, data, readOnly),
          })}
        </React.Fragment>
      )}
    </PermissionContext.Consumer>
  );
}

TutorialResponse.propTypes = {
  response: PropTypes.string,
  updateTutorial: PropTypes.func,
};

TutorialResponse.defaultProps = {
  response: '',
};
