import React, { ReactElement } from 'react'
import { DraggableProvided, DraggableStateSnapshot } from 'react-beautiful-dnd'
import ReactDOM from 'react-dom'
import classNames from 'classnames'
import useBreakpoint from 'antd/lib/grid/hooks/useBreakpoint'
import { isMobile } from 'react-device-detect'

// create portal
const portal: HTMLElement = document.createElement('div')
portal.classList.add('my-super-cool-component-portal')
if (!document.body) {
  throw new Error('body not ready for portal creation!')
}
document.body.appendChild(portal)

interface PortalComponentProps {
  enableDropComponent?: boolean
  namespaceClass: string
  single?: boolean
  provided: DraggableProvided
  snapshot: DraggableStateSnapshot
  children: ReactElement
  innerRef?: any
}

const PortalComponent: React.FC<PortalComponentProps> = ({
  provided,
  snapshot,
  namespaceClass,
  enableDropComponent = false,
  children,
  single,
  innerRef
}) => {
  const screens = useBreakpoint()
  const mobile = isMobile || screens['xs']
  const usePortal: boolean = snapshot.isDragging

  const itemWrapperClassname = classNames({
    [`${namespaceClass}__item`]: true,
    [`${namespaceClass}__item--dragging`]: snapshot.isDragging,
    [`${namespaceClass}__single`]: single
  })

  const propsComponentDragable = enableDropComponent
    ? provided.dragHandleProps
    : {}

  const child: JSX.Element = (
    <div
      style={provided.draggableProps.style}
      className={itemWrapperClassname}
      ref={innerRef || provided.innerRef}
      {...provided.draggableProps}
      {...propsComponentDragable}
    >
      {children}
    </div>
  )

  if (!usePortal || mobile) {
    return child
  }

  // if dragging - put the item in a portal
  return ReactDOM.createPortal(child, portal)
}

export default React.memo(PortalComponent)
