import {Divider, Row, theme} from 'antd';
import debounce from 'lodash/debounce';
import {
  forwardRef,
  memo,
  useImperativeHandle, useMemo,
  useRef,
  useState
} from 'react';
import MonacoEditor from 'react-monaco-editor';

import {styled} from "styled-components";
import DatartQueryLanguageSpecification from "./DatartQueryLanguageSpecification";


const component = forwardRef((props, ref) => {
  const editorRef = useRef(null);
  const [editorText, setEditorText] = useState(props.value);
  const [description, setDescription] = useState();

  useImperativeHandle(ref, () => ({
    insertField: (value, funcDesc) => {
      if (!value) {
        return;
      }
      if (funcDesc) {
        setDescription(funcDesc);
      }

      setEditorText(pre=>pre+value)
    },
  }));

  const getEditorNewLineCharactor = () => {
    return editorRef?.current?.editor?.getModel()?.getEOL();
  };

  const onChange = debounce(newValue => {
    setEditorText(newValue);

    const removeNewLineCharactor = value =>
      value.replace(getEditorNewLineCharactor(), ' ');

    props.onChange && props.onChange(removeNewLineCharactor(newValue));
  }, 200);

  const handleDescriptionChange = debounce(descKey => {
    if (!descKey) {
      return;
    }
    const funcDesc = props.functionDescriptions?.find(d => d.name === descKey);
    if (!!funcDesc) {
      setDescription(funcDesc);
    }
  }, 200);

  const handleEdtiorWillMount = monacoEditor => {
    monacoEditor.languages.register({ id: 'dql' });
    monacoEditor.languages.setMonarchTokensProvider('dql', {
      ...DatartQueryLanguageSpecification,
      builtinFunctions: (props?.functionDescriptions || []).map(f => f.name),
    });
  };

  const handleEditorDidMount = (editor, monaco) => {
    const model = editor.getModel();
    editor.onDidChangeCursorPosition(listener => {
      const positionWord = model.getWordAtPosition(listener.position);
      handleDescriptionChange(positionWord?.word);
    });
  };

  return (
    <StyledChartComputedFieldEditor>
      <MonacoEditor
        // ref={editorRef}
        width="100%"
        height="200"
        language="dql"
        value={editorText}
        onChange={onChange}
        editorWillMount={handleEdtiorWillMount}
        editorDidMount={handleEditorDidMount}
        options={{
          lineDecorationsWidth: 1,
          minimap: { enabled: false },
        }}
        overrideServices={
          {
            // onDidChangeCursorPosition: () => console.log('overrideServices |onDidChangeCursorPosition ---->'),
          }
        }
      />
    </StyledChartComputedFieldEditor>
  );
})

export const ComputedEditor = memo(component);

const StyledChartComputedFieldEditor = styled.div`
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 200px;
  border: 1px solid ${p=>p.theme.colorBorder};
`;