import { memo } from 'react';
import { JSONEditor, JSONEditorPropsOptional } from 'vanilla-jsoneditor';
import { useEffect, useRef } from 'react';
import './index.less';
import { debounce } from 'lodash';
interface CustomJsonEditorProps {
  /**
   *  @description value
   */
  content?: any;
  /**
   * onChange
   */
  onChange?: (val: { val?: any }) => void;
  /**
   *  @ description JsonEditor只读
   */
  readOnly?: boolean;
  height?: number;
  options?: JSONEditorPropsOptional;
}
const CustomJsonEditor = ({
  content,
  onChange,
  readOnly,
  height,
  options,
}: CustomJsonEditorProps) => {
  const refContainer = useRef(null);
  const refEditor = useRef<{
    updateProps: (props: any) => void;
    destroy: () => void;
  }>(null);

  useEffect(() => {
    // @ts-ignore
    refEditor.current = new JSONEditor({
      // @ts-ignore
      target: refContainer.current,
      props: {
        // @ts-ignore
        mode: 'text',
        mainMenuBar: false,
        ...options,
      },
    });

    return () => {
      // destroy editor
      if (refEditor.current) {
        refEditor.current?.destroy();
        // @ts-ignore
        refEditor.current = null;
      }
    };
  }, []);

  // update props
  useEffect(() => {
    if (refEditor.current) {
      refEditor.current?.updateProps({
        content: {
          text: JSON.stringify(content, null, 2),
        },
      });
    }
  }, [content]);
  useEffect(() => {
    if (refEditor.current) {
      refEditor.current?.updateProps({
        onChange: debounce((val) => {
          try {
            if (val.text.trim() === '') {
              onChange?.({});
            }
            if (JSON.stringify(content) !== JSON.stringify(JSON.parse(val.text))) {
              onChange?.(JSON.parse(val.text));
            }
          } catch (error) {}
        }, 300),
      });
    }
  }, [onChange, content]);
  useEffect(() => {
    if (refEditor.current) {
      refEditor.current?.updateProps({
        readOnly,
      });
    }
  }, [readOnly]);
  return <div className="vanilla-jsoneditor-react" style={{ height }} ref={refContainer}></div>;
};
export default memo(CustomJsonEditor);
