import {memo, useCallback, useEffect, useRef} from 'react';
import MonacoEditor from "react-monaco-editor";
import {styled} from "styled-components";
import { language } from 'monaco-editor/esm/vs/basic-languages/sql/sql';
export const CodeEditor = memo(({
  value,
  onEditorChange,
  ...rest
}) => {
  const editorRef = useRef(null);
  const monacoRef = useRef(null);
  const decorationsRef = useRef([]);

  useEffect(() => {
    // Define custom styles for the decorations
    // const style = document.createElement('style');
    // style.innerHTML = `
    //   .myAfterContentDecoration::after {
    //     content: ' // 备注';
    //     color: green;
    //     font-weight: bold;
    //   }
    // `;
    // document.head.appendChild(style);
  }, []);

  const editorDidMount = useCallback((editor, monaco) => {
    editorRef.current = editor;
    monacoRef.current = monaco;

    // Add an event listener for cursor position changes
    editor.onDidChangeCursorSelection(() => {
      const selection = editor.getSelection();
      // if (selection.isEmpty()) {
      //   // Remove decorations if selection is empty
      //   editor.deltaDecorations(decorationsRef.current, []);
      //   return;
      // }

      const lineNumber = selection.positionLineNumber;
      const lineContent = editor.getModel().getLineContent(lineNumber);

      if (lineContent !== "") {
        decorationsRef.current = editor.deltaDecorations(decorationsRef.current, [
          {
            range: new monaco.Range(lineNumber, 1, lineNumber, 1),
            options: {
              isWholeLine: true,
              afterContentClassName: 'myAfterContentDecoration'
            }
          }
        ]);

      } else {
        // Remove decorations if the line does not start with 'var'
        editor.deltaDecorations(decorationsRef.current, []);
      }
    });
  },[])

  const editorWillMount = useCallback(
    editor => {
      editor.languages.register({ id: 'sql' });
      editor.languages.setMonarchTokensProvider('sql', language);
    },
    [],
  );

  return (
    <EditorWrapper>
      <MonacoEditor
        width="100%"
        height="600"
        language="sql"
        theme="vs-light"
        value={value}
        options={""}
        editorDidMount={editorDidMount}
        editorWillMount={editorWillMount}
        onChange={onEditorChange}
        {...rest}
      />
    </EditorWrapper>
  )
});

const EditorWrapper = styled.div`
  border: 1px solid ${p=>p.theme.colorBorder};
  padding-right: 1px;
`
