import React from 'react'
import { useIsFocusVisible } from '@planview/pv-utilities'
import { useGridComponents } from '../context/grid-components-context/hook'
import { useGridContext, useGridSelector } from '../context/grid-context/hook'
import { useFocusHandler } from '../hooks'
import type { Column } from '../types'
import { useColumnBorders } from '../hooks/use-column-borders'

export type GridFooterCellProps = {
    columnId: string
    value?: number | Date | null
}

const getCellLabel = (
    value: GridFooterCellProps['value'],
    column: Column<any>
): string | null => {
    if (column.footer?.label) {
        return column.footer.label(value ?? null)
    }
    return value === undefined || value === null ? null : value.toString()
}

export const GridFooterCellImpl = ({
    columnId,
    value,
}: GridFooterCellProps) => {
    const { GridFooterCellLayout, GridCellFocusLayout } = useGridComponents()
    const grid = useGridContext()

    const { selectColumn } = grid.selectors

    const { actualWidth, data: column } = useGridSelector((state) =>
        selectColumn(state, columnId)
    )

    const CellFooterComponent = column?.footer?.Renderer

    const sticky =
        column.sticky === 'left' || column.sticky === 'right'
            ? column.sticky
            : null

    const stickyOffset = useGridSelector((state) =>
        grid.selectors.selectColumnStickyOffset(state, columnId)
    )
    const { showLeftBorder, showRightBorder } = useColumnBorders(
        columnId,
        'footer'
    )

    const [hasFocus, handleFocus] = useFocusHandler(columnId, 'footer', '0')
    const focusProps = useIsFocusVisible()
    const handlePointerDown = React.useCallback<
        React.PointerEventHandler<HTMLElement>
    >(() => {
        handleFocus()
    }, [handleFocus])

    const extraStyle: Partial<React.CSSProperties> | null = sticky
        ? {
              [sticky]: stickyOffset,
          }
        : null

    const label = getCellLabel(value, column)
    return (
        <GridFooterCellLayout
            style={{
                ...extraStyle,
                width: actualWidth,
            }}
            onPointerDown={handlePointerDown}
            role="gridcell"
            $sticky={!!sticky}
            $leftBorder={showLeftBorder}
            $rightBorder={showRightBorder}
            onFocus={focusProps.onFocus}
            onBlur={focusProps.onBlur}
            data-current-cell={hasFocus ? 'true' : undefined}
            tabIndex={hasFocus ? 0 : -1}
        >
            <GridCellFocusLayout
                $focusVisible={hasFocus && focusProps.focusVisible}
            >
                {CellFooterComponent && label !== null ? (
                    <CellFooterComponent label={label} columnId={columnId} />
                ) : null}
            </GridCellFocusLayout>
        </GridFooterCellLayout>
    )
}

export const GridFooterCell = React.memo(
    GridFooterCellImpl
) as typeof GridFooterCellImpl
