import React, { useMemo } from 'react'
import { GridActionsMenuContext } from './context'
import type { GridActionsMenu } from '../../types'
import type { GridActionsMenuContextType } from './types'

export type GridActionsMenuProviderProps = {
    children: React.ReactNode
    actionsMenu?: GridActionsMenu
}

const standardizeActionsMenu = (actionsMenu: GridActionsMenu | undefined) => {
    if (typeof actionsMenu === 'function') {
        return { MenuItems: actionsMenu }
    }

    return {
        MenuItems: actionsMenu?.MenuItems ?? actionsMenu?.Component,
        Menu: actionsMenu?.Menu,
        visible: actionsMenu?.visible,
    }
}

export const GridActionsMenuProvider = ({
    children,
    actionsMenu: actionsMenuIncoming,
}: GridActionsMenuProviderProps) => {
    const { Menu, MenuItems, visible } =
        standardizeActionsMenu(actionsMenuIncoming)

    // This optimization allows the object version of actionsMenu to change
    // between renders without causing the context to update
    const actionsMenu: undefined | GridActionsMenuContextType['actionsMenu'] =
        React.useMemo(
            () =>
                MenuItems || Menu ? { MenuItems, Menu, visible } : undefined,
            [Menu, MenuItems, visible]
        )

    const state = useMemo(() => ({ actionsMenu }), [actionsMenu])
    return (
        <GridActionsMenuContext.Provider value={state}>
            {children}
        </GridActionsMenuContext.Provider>
    )
}
