import React from 'react'
import { useGridComponents } from '../context/grid-components-context/hook'
import { useGridContext, useGridSelector } from '../context/grid-context'
import { useAggregations } from '../hooks/'
import { size, useIsFocusVisible } from '@planview/pv-utilities'
import { ROW_FOCUS_ID } from '../constants'

export type GridFooterRowProps = {
    height: number
}

const GridFooterRowImpl = ({ height }: GridFooterRowProps) => {
    const { GridFooterRowLayout, GridFooterCell } = useGridComponents()
    const grid = useGridContext()
    const { selectors } = grid
    const columnIds = useGridSelector(selectors.selectColumnIds)
    const hasFocus = useGridSelector((state) =>
        selectors.selectHasFocus(state, ROW_FOCUS_ID, 'footer', '0')
    )
    const {
        innerRef: _innerRef,
        focusVisible,
        ...focusProps
    } = useIsFocusVisible()
    const aggregations = useAggregations()

    return (
        <GridFooterRowLayout
            {...focusProps}
            tabIndex={hasFocus ? 0 : -1}
            data-current-row={hasFocus ? 'true' : undefined}
            role="row"
            $compact={height < size.medium}
            $focusVisible={hasFocus && focusVisible}
        >
            {columnIds.map((columnId) => (
                <GridFooterCell
                    key={columnId}
                    columnId={columnId}
                    value={aggregations.get(columnId)?.result}
                />
            ))}
        </GridFooterRowLayout>
    )
}

export const GridFooterRow = React.memo(GridFooterRowImpl)
