import { Menu } from 'antd'
import React from 'react'
import style from './style.module.css'

export type MenuItem<T> = { label: string, value: T, key?: any }
export type Menus<T> = MenuItem<T>[]
export type Position = { x: number, y: number }
export type props<T> = {
  event: React.MouseEvent | null,
  menus: Menus<T>,
  onExit: () => void
  onSelect: (value: T, pos: Position) => void
}

export function AuxMenus<T>(props: props<T>) {
  if (!props.event) {
    return null
  }
  const selectHandler = (item: MenuItem<T>, pos) => {
    props.onSelect(item.value, pos)
    props.onExit()
  }

  const pos = {
    x: props.event.nativeEvent.offsetX,
    y: props.event.nativeEvent.offsetY
  }
  const items = props.menus.map((item, index) => ({
    key: index,
    label: (
      <span onClick={() => selectHandler(item, pos)}>
        {item.label}
      </span>
    )
  }))

  return (
    <div 
      onClick={ev => ev.stopPropagation()}
      style={{left: pos.x + 'px', top: pos.y + 'px'}} 
      className={style['menu-layer']}>
      <Menu
        style={{ width: 256 }}
        defaultSelectedKeys={['1']}
        defaultOpenKeys={['sub1']}
        mode="inline"
        items={items}
      />
    </div>
  )
}

export default AuxMenus