import { forwardRef, useEffect, useImperativeHandle, useRef } from 'react'

export interface WebFrameHandle {
  reload: () => void
}

interface WebFrameProps {
  src: string
  className?: string
}

const WebFrame = forwardRef<WebFrameHandle, WebFrameProps>(function WebFrame(
  { src, className },
  ref
) {
  const hostRef = useRef<HTMLDivElement>(null)
  const wvRef = useRef<Electron.WebviewTag | null>(null)

  useImperativeHandle(ref, () => ({
    reload: () => wvRef.current?.reload()
  }))

  useEffect(() => {
    const host = hostRef.current
    if (!host) return
    const wv = document.createElement('webview') as Electron.WebviewTag
    wv.setAttribute('webpreferences', 'contextIsolation=yes,nodeIntegration=no')
    wv.setAttribute('class', 'webframe-webview')
    wv.style.display = 'flex'
    wv.style.width = '100%'
    wv.style.height = '100%'
    host.appendChild(wv)
    wvRef.current = wv
    wv.src = src
    return () => {
      wv.remove()
      wvRef.current = null
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  useEffect(() => {
    const wv = wvRef.current
    if (wv && wv.getAttribute('src') !== src) wv.setAttribute('src', src)
  }, [src])

  return <div ref={hostRef} className={'webframe' + (className ? ' ' + className : '')} />
})

export default WebFrame
