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

const DraggingLine = styled.div<{ $error: boolean }>`
    background-color: ${(props) =>
        props.$error ? theme.borderError : theme.borderActive};
    height: 2px;
    position: absolute;
    display: block;
    z-index: 15;
    pointer-events: none;

    &::before {
        position: absolute;
        content: '';
        left: 0;
        top: -2px;
        width: 6px;
        height: 6px;
        border-radius: 3px;
        background-color: inherit;
    }
`

export type GridDragLineIndicatorProps = {
    prevId: null | GridRowId
    level: number
    width: number
}

export const GridDragLineIndicator: React.FC<GridDragLineIndicatorProps> = ({
    prevId,
    level,
    width,
}) => {
    const grid = useGridContext()
    const rowIds = useGridSelector(grid.selectors.selectRowIds)
    const rowHeight = useGridSelector(grid.selectors.selectRowHeight)
    const isTreeGrid = useGridSelector(grid.selectors.selectIsTreeGrid)
    const treeIndentSize = useGridSelector(grid.selectors.selectTreeIndentSize)
    const previewLeftOffset = useGridSelector(
        grid.selectors.selectPreviewLeftOffset
    )
    const dropAllowed = useGridSelector(grid.selectors.selectDropIsAllowed)
    const message = useGridSelector(grid.selectors.selectDragMessage)

    const startIndex = prevId === null ? 0 : rowIds.indexOf(prevId) + 1

    const headerHeight = useGridSelector(grid.selectors.selectHeaderHeight)
    const offset = startIndex * rowHeight - 1

    const leftOffset = isTreeGrid
        ? calculateIndent(level, treeIndentSize, true)
        : 0

    if (!dropAllowed && !message) {
        return null
    }

    return (
        <DraggingLine
            data-testid="pvds-grid-drop-indicator"
            $error={dropAllowed === false}
            style={{
                top: headerHeight + offset,
                left: previewLeftOffset + leftOffset,
                width: `calc(max(100%,${width}px) - ${
                    previewLeftOffset + leftOffset
                }px)`,
            }}
        />
    )
}
