import React from 'react'
import { useGridContext, useGridSelector } from '../context/grid-context'
import { useIntl } from 'react-intl'
import type { MenuProps } from '@planview/pv-uikit'
import { Menu } from '@planview/pv-uikit'
import { gridActionsMenuMessages } from './grid-cell-actions-menu'
import { useGridActionsMenu } from '../context/grid-actions-menu-context'

export const GridContextActionsMenu: React.FC = () => {
    const { ActionsMenu, ActionsMenuItems } = useGridActionsMenu()
    const intl = useIntl()
    const label = intl.formatMessage(gridActionsMenuMessages.label)

    const grid = useGridContext()
    const actionsMenuDetails = useGridSelector(
        grid.selectors.selectActionsMenuDetails
    )

    const { row, rowMeta } = useGridSelector((state) => {
        if (actionsMenuDetails.rowId != null) {
            return {
                row: grid.selectors.selectRow(state, actionsMenuDetails.rowId),
                rowMeta: grid.selectors.selectRowMeta(
                    state,
                    actionsMenuDetails.rowId
                ),
            }
        }
        return { row: null, rowMeta: null }
    })

    if (actionsMenuDetails.visible) {
        const menuProps = {
            filterMode: 'off',
            open: true,
            label,
            anchor: actionsMenuDetails.coordinates,
            onClose: grid.api.actionsMenu.hide,
        } satisfies Omit<MenuProps, 'children'>

        if (ActionsMenuItems) {
            return (
                <Menu {...menuProps}>
                    <ActionsMenuItems row={row} rowMeta={rowMeta} />
                </Menu>
            )
        }
        if (ActionsMenu) {
            return <ActionsMenu row={row} rowMeta={rowMeta} {...menuProps} />
        }
    }

    return null
}
