import { useState } from "react"
import { css, cx } from "@emotion/css"
import { type ControlledMenuProps, useMenuState } from "@szhsin/react-menu"
import { useAutoMemo } from "hooks.macro"
import { useEvent } from "@aet/hooks"
import { token, vars } from "~/options/theme"

export function useDropdownMenu(className?: string) {
  const [menuState, toggleMenu] = useMenuState({})
  const [anchorPoint, setAnchorPoint] = useState({ x: 0, y: 0 })

  const onMouse = useEvent((e: React.MouseEvent<Element>) => {
    e.preventDefault()
    setAnchorPoint({ x: e.clientX, y: e.clientY })
    toggleMenu()
  })

  const menuProps = useAutoMemo<ControlledMenuProps>({
    ...menuState,
    portal: true,
    anchorPoint,
    direction: "right",
    onClose: () => toggleMenu(false),
    className: cx(menuClassName, className),
  })

  return useAutoMemo({
    menuProps,
    toggleMenu,
    onMouse,
  })
}

export const menuClassName = css`
  .szh-menu--state-open {
    background-color: ${token.canvas.overlay};
    border: 1px solid ${token.border.default};
    border-radius: 5px;
    box-shadow: ${token.shadow.large};
    list-style: none;
    padding-inline-start: 0;
    padding: 5px;
    z-index: 5;
  }
  .szh-menu__item {
    align-items: center;
    border-radius: 3px;
    cursor: pointer;
    display: flex;
    line-height: 1.45em;
    min-width: 100px;
    outline: none;
    padding: 5px 8px;
    padding-right: 15px;
    user-select: none;
    white-space: nowrap;
    > svg {
      margin-right: 6px;
      margin-left: -1px;
      font-size: 1.2em;
    }
    &:hover,
    &:focus {
      background-color: ${vars.backgroundActive};
    }
    &.szh-menu__item--disabled {
      opacity: 0.5;
      cursor: default;
      &:hover {
        background: unset;
      }
    }
  }
`
