import React from 'react'
import type { GridRowId } from '../../types'
import styled, { keyframes } from 'styled-components'
import { theme } from '@planview/pv-utilities'
import { useGridContext, useGridSelector } from '../../context/grid-context'

const droppedAnimation = keyframes`
    0% { opacity: 1; }
    80% { opacity: 1; }
    100% { opacity: 0; }
`

const DroppedBox = styled.div`
    pointer-events: none;
    background-color: ${theme.backgroundTranslucentActive};
    position: absolute;
    left: 0;
    display: block;
    z-index: 2;
    animation-name: ${droppedAnimation};
    animation-duration: 2s;
    animation-fill-mode: forwards;
`

export type GridDragDroppedIndicatorProps = {
    ids: Set<GridRowId>
    width: number
}

export const GridDragDroppedIndicator: React.FC<
    GridDragDroppedIndicatorProps
> = ({ ids, width }) => {
    const grid = useGridContext()
    const rowIds = useGridSelector(grid.selectors.selectRowIds)
    const rowHeight = useGridSelector(grid.selectors.selectRowHeight)
    const selection = useGridSelector(grid.selectors.selectSelection)

    const boxes = React.useMemo(() => {
        const _boxes: { id: GridRowId; top: number; height: number }[] = []

        rowIds.forEach((rowId, index) => {
            if (ids.has(rowId) && !selection.has(rowId)) {
                _boxes.push({
                    id: rowId,
                    top: index * rowHeight,
                    height: rowHeight,
                })
            }
        })

        return _boxes
    }, [rowIds, ids, selection, rowHeight])

    const headerHeight = useGridSelector(grid.selectors.selectHeaderHeight)

    return (
        <>
            {boxes.map((bx) => (
                <DroppedBox
                    key={bx.id}
                    style={{
                        top: headerHeight + bx.top,
                        height: bx.height,
                        width: `max(100%,${width}px)`,
                    }}
                />
            ))}
        </>
    )
}
