import React from 'react'
import { useGridContext, useGridSelector } from '../context/grid-context'
import type { GridRowId } from '../types'
import type { GridFocusArea } from '../state/types'

export function useFocusHandler(
    columnId: string,
    area: GridFocusArea,
    rowId: GridRowId = ''
) {
    const grid = useGridContext()

    const onFocus = React.useCallback(() => {
        if (
            !grid.selectors.selectHasFocus(
                grid.getState(),
                columnId,
                area,
                rowId
            )
        ) {
            grid.api.focus.set(rowId, columnId, area)
        }
    }, [grid, columnId, area, rowId])

    const hasFocus = useGridSelector((state) =>
        grid.selectors.selectHasFocus(state, columnId, area, rowId)
    )

    return [hasFocus, onFocus] as const
}
