import React from 'react'
import { Checkbox } from '@planview/pv-uikit'
import { useIntl, defineMessages } from 'react-intl'
import { useGridContext, useGridSelector } from '../context/grid-context/hook'
import styled, { css } from 'styled-components'
import { sizePx } from '@planview/pv-utilities'

export type GridHeaderCellCheckboxProps = {
    tabIndex: number
}

const messages = defineMessages({
    labelToggleAllRows: {
        id: 'pvds.grid.header.checkboxToggleAllRowsLabel',
        defaultMessage: 'Select all rows',
        description:
            'Screen reader text for the toggle all rows checkbox in header',
    },
})
const CheckboxWrap = styled.div<{ $extraSelectionSpace?: boolean }>`
    height: 100%;
    min-height: ${sizePx.small};
    display: flex;
    align-items: center;
    ${(props) =>
        props.$extraSelectionSpace &&
        css`
            padding-left: ${sizePx.smallCompact};
        `}

    * {
        outline: none;
    }
`

export const GridHeaderCellCheckbox = ({
    tabIndex,
}: GridHeaderCellCheckboxProps) => {
    const intl = useIntl()
    const grid = useGridContext()
    const checkBoxRef = React.useRef<HTMLInputElement>(null)
    const selectionState = useGridSelector(grid.selectors.selectSelectionStatus)

    const spreadsheetMode = useGridSelector(grid.selectors.selectIsSpreadsheet)
    const rowDragEnabled = useGridSelector(
        grid.selectors.selectIsDraggingEnabled
    )

    const handleChange = React.useCallback(
        (val: boolean) => {
            if (val) {
                grid.api.selection.selectAll()
            } else {
                grid.api.selection.selectNone()
            }
        },
        [grid]
    )

    const keyDownHandler = React.useCallback(
        (ev: React.KeyboardEvent) => {
            if (ev.key === 'Enter') {
                ev.preventDefault()
                const isInputChecked = checkBoxRef.current?.checked ?? false
                handleChange(!isInputChecked)
            }
        },
        [handleChange]
    )

    return (
        <CheckboxWrap $extraSelectionSpace={spreadsheetMode && rowDragEnabled}>
            <Checkbox
                aria-label={intl.formatMessage(messages.labelToggleAllRows)}
                ref={checkBoxRef}
                tabIndex={tabIndex}
                size="small"
                indeterminate={selectionState === 'some'}
                selected={selectionState === 'all'}
                onChange={handleChange}
                onKeyDown={keyDownHandler}
            />
        </CheckboxWrap>
    )
}
