import React from 'react'
import { useGridRow, useGridRowMeta } from '../context/grid-context'
import { GridCellDropdownMenu } from '../components/cell-dropdown-menu'
import { DotsVertical } from '@planview/pv-icons'
import { defineMessages, useIntl } from 'react-intl'
import type { GridRowId } from '../types'
import { GridCellBase } from '../components'
import type { GridActionsMenuBridge } from '../context/grid-actions-menu-context'
import { useGridActionsMenu } from '../context/grid-actions-menu-context'

export const gridActionsMenuMessages = defineMessages({
    label: {
        id: 'pvds.grid.actionsMenu.label',
        defaultMessage: 'More actions',
        description:
            'An accessibility label and tooltip for the actions menu that appears on a grid row or on right click of a row',
    },
})

export type GridCellActionsMenuProps = {
    rowId: GridRowId
    tabIndex: number
}

export const GridCellActionsMenu = ({
    rowId,
    tabIndex,
}: GridCellActionsMenuProps) => {
    const { ActionsMenu, ActionsMenuItems, visible } = useGridActionsMenu()
    const intl = useIntl()
    const label = intl.formatMessage(gridActionsMenuMessages.label)
    const [open, setOpen] = React.useState(false)

    const row = useGridRow(rowId)
    const rowMeta = useGridRowMeta(rowId)

    const isButtonVisible = React.useMemo(
        () => visible({ row, rowMeta }),
        [row, rowMeta, visible]
    )
    const handleOpen = React.useCallback(() => setOpen(true), [])
    const handleClose = React.useCallback(() => setOpen(false), [])
    const trigger = React.useMemo(
        () => ({
            icon: <DotsVertical />,
            tooltip: label,
        }),
        [label]
    )
    const menuProps = React.useMemo<GridActionsMenuBridge<any, any>>(
        () => ({ label, filterMode: 'off', row, rowMeta }),
        [label, row, rowMeta]
    )

    if (!isButtonVisible) {
        return (
            <GridCellBase tabIndex={tabIndex}>
                <></>
            </GridCellBase>
        )
    }

    if (ActionsMenuItems) {
        return (
            <GridCellDropdownMenu
                tabIndex={tabIndex}
                label={label}
                alignRight
                onOpen={handleOpen}
                onClose={handleClose}
                trigger={trigger}
                filterMode="off"
            >
                {open && <ActionsMenuItems row={row} rowMeta={rowMeta} />}
            </GridCellDropdownMenu>
        )
    }

    if (ActionsMenu) {
        return (
            <GridCellDropdownMenu.Base
                tabIndex={tabIndex}
                trigger={trigger}
                onOpen={handleOpen}
                onClose={handleClose}
                MenuComponent={ActionsMenu}
                menuProps={menuProps}
            />
        )
    }

    return null
}

export const GridCellActionsMenuMemo = React.memo(
    GridCellActionsMenu
) as typeof GridCellActionsMenu
