import React from 'react'
import { SubNavigationContext } from '../context/grid-sub-navigation-context'

type UseSubNavigationProps = {
    /**
     * amount of indexes (stops) the renderer requires
     */
    indexes: number

    /**
     * flag to enable renderer to take care of any focus outlines
     */
    inlineFocusStylingEnabled?: boolean
}

/**
 *
 * Hook to use for in-cell-focus-management.
 *
 * Use `registerIndexes` to register the amount of stops the cell has and
 * `currentSubFocusIndex` (zero-based index) to determine which item in the cell that should have tabIndex=0 and thus be navigable.
 *
 *
 * ### Usage (inside Renderer function of column configuration)
 * ```
 *
 *  Renderer() {

        const { currentSubFocusIndex } = useSubNavigation({
            indexes: 3,
            inlineFocusStylingEnabled: true,
        })

        //Switch tab index to 0 on the current subIndex item (will be -1 is the cell is not in focus)
        return <div>
            <Input tabIndex={currentSubFocusIndex === 0 ? 0 : -1} />
            <Input tabIndex={currentSubFocusIndex === 1 ? 0 : -1} />
            <Input tabIndex={currentSubFocusIndex === 2 ? 0 : -1} />
        </div>
 * },
 *
 * ```
 */
export const useSubNavigation = ({
    indexes,
    inlineFocusStylingEnabled = false,
}: UseSubNavigationProps) => {
    const {
        registerIndexes,
        currentSubFocusIndex,
        registeredIndexes,
        setRendererWantsToDisplayFocusStyles,
        hasFocus,
        setCurrentSubFocusIndex,
    } = React.useContext(SubNavigationContext)

    React.useEffect(() => {
        registerIndexes(indexes)
    }, [indexes, registerIndexes])

    React.useEffect(() => {
        setRendererWantsToDisplayFocusStyles(inlineFocusStylingEnabled)
    }, [inlineFocusStylingEnabled, setRendererWantsToDisplayFocusStyles])

    return {
        /** the current index inside the component */
        currentSubFocusIndex: hasFocus
            ? Math.min(registeredIndexes - 1, currentSubFocusIndex)
            : -1,
        /** method to update the sub-focus index */
        setCurrentSubFocusIndex,
    }
}
