import {
  ReactElement,
  ForwardRefExoticComponent,
  Children,
  cloneElement,
  useContext,
} from 'react'

import { PopoutContext } from './Popout'

export interface PopoutBridgeProps {
  children: ReactElement
}

export type PopoutBridge = ForwardRefExoticComponent<PopoutBridgeProps>

export function PopoutBridge(props: PopoutBridgeProps) {
  const { children } = props

  const popoutContext = useContext(PopoutContext)

  try {
    const element = Children.only(children)
    return cloneElement(element, {
      ...element.props,
      onChange: (...args: any[]) => {
        popoutContext.setTmpChangeArgs(args)
        element.props.onChange?.(...args)
      },
    })
  } catch {
    return null
  }
}

export default PopoutBridge
