import { css } from '@emotion/css'
import type { Placement } from '@floating-ui/react'
import {
  FloatingFocusManager,
  FloatingPortal,
  useDismiss,
  useInteractions,
} from '@floating-ui/react'
import type { ReactNode } from 'react'
import PopoverContainer from '../PopoverContainer'
import usePopover from '../usePopover'

interface PopoverProps {
  placement?: Placement
  open: boolean
  setOpen: (value: boolean) => void
  children: ReactNode
}

const float = css`
  z-index: 9999;
  box-shadow: 0 0 0.75rem 0.25rem rgba(141, 141, 141, 0.25);
  max-width: min(95vw, 30rem);
  &:focus {
    outline: none;
  }
`

const usePopoverElement = ({
  placement = 'bottom',
  open,
  setOpen,
  children,
}: PopoverProps) => {
  const { refs, floatingStyles, context } = usePopover(open, setOpen, placement)

  const dismiss = useDismiss(context)
  const { getReferenceProps, getFloatingProps } = useInteractions([dismiss])

  getReferenceProps({
    // for a native <button>
    onClick() {
      setOpen(false)
    },
  })

  return {
    getReferenceProps,
    setReference: refs.setReference,
    children: open && (
      <FloatingFocusManager context={context}>
        <FloatingPortal>
          <div
            ref={refs.setFloating}
            className={float}
            style={floatingStyles}
            {...getFloatingProps}
          >
            <PopoverContainer>{children}</PopoverContainer>
          </div>
        </FloatingPortal>
      </FloatingFocusManager>
    ),
  }
}

export default usePopoverElement
