import React, { useLayoutEffect } from "react"
import cx from "classnames"
import CKIcon from "../ck-icon"
import Portal from "../portal"
import { Popper } from "react-popper"

function MenuItem({ active, selected, children, ...props }, ref) {
  const className = cx(
      "px-3 py-2 text-sm whitespace-no-wrap rounded leading-6",
      {
        "bg-gray-50 cursor-pointer": active,
      }
  )

  return (
      <li ref={ref} className={className} {...props}>
        {children}
      </li>
  )
}
MenuItem = React.forwardRef(MenuItem)

const modifiers = {
  flip: { enabled: true, behavior: ["top-start", "bottom-start"] },
}

function MenuListContainer({ active, popper, children }) {
  // Updates popper to ensure proper positioning when items are added/removed
  const updatePopper = () => {
    popper.update()
  }

  // Updates popper to ensure proper initial positioning when menu is opened
  useLayoutEffect(() => {
    popper.update()
  }, [active])

  return (
      <div ref={popper.ref} onClick={updatePopper} style={{ ...popper.style, zIndex: 10000, paddingTop: "8px" }}>
        {children}
      </div>
  )
}

function MenuList({ active, popper, children, style, ...props }, ref) {
  const className = cx(
      "bg-white p-2 shadow-lg outline-none list-none overflow-auto border border-gray-200 rounded",
      {
        hidden: !active,
      }
  )

  return (
      <Portal>
        <Popper placement="bottom-start" modifiers={modifiers}>
          {(popper) => (
              <MenuListContainer active={active} popper={popper}>
                <ul
                    ref={ref}
                    style={{ maxHeight: "300px", top: "4px", ...style }}
                    className={className}
                    {...props}
                >
                  {children}
                </ul>
              </MenuListContainer>
          )}
        </Popper>
      </Portal>
  )
}
MenuList = React.forwardRef(MenuList)

function ToggleButton({ children, className, ...props }, ref) {
  return (
      <button ref={ref} type="button" className={className} {...props}>
        {children}
        <CKIcon name="down" />
      </button>
  )
}
ToggleButton = React.forwardRef(ToggleButton)

export { MenuItem, MenuList, ToggleButton }