import React from 'react'
import { GridActionsMenuContext } from './context'
import type { MenuProps } from '@planview/pv-uikit'
import type { GridRowData, GridRowMeta } from '../../types'

const visibleTrue = () => true
const visibleFalse = () => false

export type GridActionsMenuBridge<
    TDataModel extends GridRowData = GridRowData,
    TMetaModel extends GridRowMeta = GridRowMeta<GridRowData>,
> = Omit<MenuProps, 'children'> & {
    row: TDataModel
    rowMeta: TMetaModel
}

export const useGridActionsMenu = () => {
    const { actionsMenu } = React.useContext(GridActionsMenuContext)

    const WrappedActionsMenu = React.useMemo(() => {
        const MenuComp = actionsMenu?.Menu

        if (!MenuComp) {
            return undefined
        }

        const ActionsMenuComp = ({
            row,
            rowMeta,
            ...rest
        }: GridActionsMenuBridge<any, any>) => (
            <MenuComp row={row} rowMeta={rowMeta} menuProps={rest} />
        )
        return ActionsMenuComp
    }, [actionsMenu?.Menu])

    if (actionsMenu === undefined) {
        return {
            ActionsMenuItems: undefined,
            ActionsMenu: undefined,
            visible: visibleFalse,
        }
    }
    return {
        ActionsMenuItems: actionsMenu.MenuItems,
        ActionsMenu: WrappedActionsMenu,
        visible: actionsMenu.visible || visibleTrue,
    }
}
