import { Box } from '@tidbcloud/uikit'
import { useEffect, useLayoutEffect, useRef } from 'react'

import { getEditor, addEditor, clearEditors } from './editor-cache'
import { CreateEditorOptions, createEditor } from './editor-instance'

type SQLCodeEditorProps = CreateEditorOptions & { fileId: string }

export default function SQLCodeEditor({ fileId, theme, sqlConfig, ...rest }: SQLCodeEditorProps) {
  const editorContainerRef = useRef<HTMLDivElement>(null)

  useLayoutEffect(() => {
    if (!editorContainerRef.current) return

    let editorInst = getEditor(fileId)
    if (!editorInst) {
      editorInst = createEditor({ theme, sqlConfig, extraData: { fileId }, ...rest })
      addEditor(fileId, editorInst)
    }

    editorContainerRef.current.appendChild(editorInst.editor.dom)
    editorInst.editor.focus()

    return () => {
      if (editorContainerRef.current && editorInst) {
        editorContainerRef.current.removeChild(editorInst.editor.dom)
      }
    }
  }, [fileId])

  // use `useLayoutEffect` to avoid flicker
  useLayoutEffect(() => {
    getEditor(fileId)?.changeTheme(theme ?? [])
  }, [fileId, theme])

  useEffect(() => {
    getEditor(fileId)?.changeSQLConfig(sqlConfig ?? {})
  }, [fileId, sqlConfig])

  useEffect(() => {
    return () => {
      clearEditors()
    }
  }, [])

  return <Box h="100%" ref={editorContainerRef} />
}
