import React, { useState, useEffect, forwardRef, useMemo } from 'react';
import WangEditor from './OneStopWangEditor';

function Index({ onChange, value, otherProps, dataColumn, disabled, json, uuid }) {
  const [ready, setReady] = useState(false);
  const domKey = uuid || 'wang-editor-dom-content';
  useEffect(() => {
    let dom = document.getElementById(`wangEditor-${domKey}`);
    if(dom && dom.parentNode){
      dom.parentNode.removeChild(dom);
    }
    setReady(true);
  }, []);

  if(!ready){
    return null;
  }
  if(disabled){
    if(!value || value === 'null'){
      return <div></div>
    }
    return <div dangerouslySetInnerHTML={{__html: `<div class="wangEditorHtml">${value}</div>`}} />
  }
  return (
    <WangEditor
      key={'cmsContent'}
      zIndex={otherProps?.zIndex || undefined}
      menus={otherProps?.menus || undefined}
      placeholder={json.placeholder || ''}
      height={otherProps?.height || 450}
      value={value || ''}
      domKey={domKey}
      onChangeValue={onChange}
    />
  );
}

export default forwardRef((props, _ref) => {
  // console.log(props);
  if(!props.uuid){
    return <div></div>;
  }

  const otherProps = useMemo(() => {
    let other = {};
    if (props.json?.otherProps) {
      let a = props.json?.otherProps;
      try {
        other = new Function(a)();
        // console.log(this.otherProps);
      } catch (e) {
        other = {};
      }
    }
    return other;
  }, [props.json?.otherProps]);


  return <Index {...props} otherProps={otherProps}/>;
});
