'use client'
import * as React from 'react'
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api'
import { createConfiguredEditor } from 'vscode/monaco'
import './setup'
import 'monaco-editor/esm/vs/language/typescript/monaco.contribution'
import MonacoEditorCopilot from './copilot';

const config = [  
  {
    testName: 'example with dispose'
  },
]

monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
  jsx: monaco.languages.typescript.JsxEmit.Preserve,
})

export default function Editor({ defaultValue }: { defaultValue: string }) {
  const ref = React.useRef<HTMLDivElement>(null)

  React.useLayoutEffect(() => {
    const model = monaco.editor.createModel(
      defaultValue,
      'typescript',
      monaco.Uri.file('index.ts')
    )
    const editor = createConfiguredEditor(ref.current!, {
      model,
      automaticLayout: true,
    })

    const initialValue = editor.getValue();
    const encodedJs = encodeURIComponent(initialValue);
    const dataUri = "data:text/javascript;charset=utf-8," + encodedJs;
    import(dataUri);

    const dispose = MonacoEditorCopilot(editor, { testName: 'basic example'} as any);
    if (config[0]?.testName === 'example with dispose') {
      setTimeout(() => {
        dispose();
      }, 1000);
    }

    return () => {
      model.dispose()
      editor.dispose()
    }
  }, [])

  return (
    <>
      <div id="editor" ref={ref} style={{ height: "100vh" }} />
    </>
  )
}
