// 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 : () => {};

// Style
let classes = {};
/* istanbul ignore next */
if (typeof window !== 'undefined' || typeof _COMPILED_ === 'undefined') classes = require('./style.module.scss');

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 ? { dark: true, highlightMode: true, tokenizeVariables: true } : { dark: true, editable: true };

  return (
    <PermissionContext.Consumer>
      {readOnly => (
        <React.Fragment>
          {!readOnly && (
            <i
              className={`${classes['TutorialResponse-Tooltip']} fa fa-question-circle`}
              data-tooltip="Leave the response section empty to hide it from your users"
              data-tooltip-position="left"
            />
          )}
          {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: '',
};
