"use client";
import React, { type ReactElement, useEffect, useRef } from 'react'
import { JSONEditor, type JSONEditorPropsOptional } from 'vanilla-jsoneditor'

interface JSONEditorComponent extends JSONEditorPropsOptional {
  className?: string
}

export default function SvelteJSONEditor(props: JSONEditorComponent): ReactElement {
  const refContainer = useRef(null)
  const refEditor = useRef<JSONEditor | null>(null)
  // const [editor, setEditor] = useState<JSONEditor | null>(null)
  console.log('--- JSON ---')

  useEffect(() => {
    // create editor
    console.log('creating')

    const el: HTMLElement = refContainer.current as unknown as HTMLElement
    const newEditor = new JSONEditor({
      target: el,
      props: {}
    })
    refEditor.current = newEditor
    // setEditor(newEditor)

    return () => {
      // destroy editor
      if (refEditor.current != null) {
        console.log('destroy editor')
        refEditor.current.destroy().then(() => {
          refEditor.current = null
        }).catch(e => {
          console.log(e)
        })
      }
    }

    /* return () => {
      // destroy editor
      if (refEditor.current !== null) {
        void (async () => {
          console.log('destroy editor')

          // setEditor(null)
          try {
            if (refEditor.current !== null) {
              await refEditor.current.destroy()
              refEditor.current = null
            }
          } catch (e) {
            console.log('Error destroying editor')
            console.log(e)
          }
        })()
      }
    } */
  }, [])

  // update props
  useEffect(() => {
    if (refEditor.current != null) {
      refEditor.current.updateProps(props).then(() => {
        console.log('updated')
      }).catch(e => {
        console.log(e)
      })
      // }
    }
  }, [props])

  return (<div className={props.className} ref={refContainer}></div>)
}
