import React, { useMemo, useState, useEffect } from 'react'

import TPMMDEditor from '../../../modules/tpm/challengesnew/tpm-md-editor'
import { markdownToHTML } from 'educoder'
import './index.scss'

function noop() { }

export const defaultQuillOpt = [
  'bold', 'italic', 'underline',
  { list: 'ordered' }, { list: 'bullet' },
  { script: 'sub' }, { script: 'super' },
  { 'color': [] },
  { 'background': [] },
  'image', 'code-block', 'formula', 'clean'
]
export default ({ is_md, value, onChange, placeholder, autoFocus = true, isError, isShowEditor, height = 160, options = defaultQuillOpt, index, onActiveOption = noop, md_id, showResizeBar = false }) => {
  let html = useMemo(() => {
    if (value) {
      return is_md ? markdownToHTML(value) : value
    }
    return placeholder
  }, [is_md, placeholder, value])

  const [isFocus, setIsFocus] = useState(false)
  useEffect(() => {
    if (isShowEditor) {
      setIsFocus(autoFocus)
    } else {
      setIsFocus(false)
    }
  }, [autoFocus, isShowEditor])


  function onMdContentChangeHandler(v) {
    onChange(v, index)
  }

  function onActiveHandler(e) {
    e.preventDefault()
    e.stopPropagation()
    onActiveOption(index)
  }
  return (
    <div className='editor-content-panel-wrapper'>
      <div className={`editor-content-panel markdown-body ${isShowEditor ? 'hide' : null} ${isError ? 'error' : null} ${value ? 'hasValue' : null} `}
        dangerouslySetInnerHTML={{ __html: html }} onClick={onActiveHandler} />

      {is_md ?
        <TPMMDEditor
          initValue={value}
          height={height}
          mdID={md_id}
          noStorage={true}
          className={`${isShowEditor ? null : 'hideMd'} ${isError ? 'md-error' : null} `}
          onChange={onMdContentChangeHandler}
          showResizeBar={showResizeBar}
          placeholder={placeholder}
        /> : null
      }

    </div>
  )
}