import React, { FC, useEffect, useRef } from 'react'
import { connectToChild, Methods } from 'penpal'
import { chakra } from '@chakra-ui/react'

export interface IframedContentProps {
  src: string
  getUserToken: () => Promise<string> | string
  methods?: Methods
}

export const IframedContent: FC<IframedContentProps> = ({ src, getUserToken, methods }) => {
  const ref = useRef<HTMLIFrameElement>(null)

  useEffect(() => {
    if (!ref.current) {
      return
    }

    const connection = connectToChild({
      // The iframe to which a connection should be made
      iframe: ref.current,
      // Methods the parent is exposing to the child
      methods: {
        getUserToken,
        ...methods,
      },
    })

    connection.promise.then(() => {})

    return () => {
      if (connection) {
        connection.destroy()
      }
    }
  }, [getUserToken, methods])

  return <chakra.iframe w="100%" h="100%" overflowX="hidden" src={src} ref={ref} />
}
