import React from 'react'
import { useGridComponents } from '../context/grid-components-context'
import { useGridContext, useGridSelector } from '../context/grid-context'
import { useIsFocusVisible } from '@planview/pv-utilities'
import { ROW_FOCUS_ID } from '../constants'
import { getHeaderRowIndex } from '../api/focus-utils'

export type GridHeaderRowProps = {
    children: React.ReactNode
    rowId: string
}

export const GridHeaderRow = ({ children, rowId }: GridHeaderRowProps) => {
    const { GridHeaderRowLayout } = useGridComponents()

    const { selectors, getState, api } = useGridContext()

    const hasFocus = useGridSelector((state) =>
        selectors.selectHasFocus(state, ROW_FOCUS_ID, 'header', rowId)
    )

    const rowIndex = useGridSelector((state) =>
        getHeaderRowIndex(selectors.selectHeaderRowIds(state), rowId)
    )

    const {
        innerRef: _innerRef,
        focusVisible,
        ...focusProps
    } = useIsFocusVisible()

    const onContextMenu = React.useCallback(
        (e: React.MouseEvent<HTMLElement>) => {
            const state = getState()
            const enabled = selectors.selectColumnMenuEnabled(state)
            if (enabled) {
                e.preventDefault()
                api.column.showMenu({ top: e.clientY, left: e.clientX })
            }
        },
        [api.column, getState, selectors]
    )

    return (
        <GridHeaderRowLayout
            {...focusProps}
            tabIndex={hasFocus ? 0 : -1}
            data-current-row={hasFocus ? 'true' : undefined}
            aria-rowindex={rowIndex + 1}
            $focusVisible={hasFocus && focusVisible}
            onContextMenu={onContextMenu}
            role="row"
        >
            {children}
        </GridHeaderRowLayout>
    )
}

export const GridHeaderRowMemo = React.memo(GridHeaderRow)
