import React from 'react'
import { useGridComponents } from '../context/grid-components-context/hook'
import { useGridContext, useGridSelector } from '../context/grid-context/hook'
import { createSelector } from '../state/utils'
import { SkeletonLoader } from '@planview/pv-uikit'
import type { GridCellProps } from './grid-cell'
import type { GridRowMeta } from '../types'
import { useCellStickySizing } from '../hooks'
import styled from 'styled-components'
import { calculateIndent } from '../utils/indent'

const LoaderLayout = styled.div`
    height: 100%;
    width: 100%;
    box-sizing: border-box;
`

export const GridCellLoading = ({
    columnId,
    rowId,
    virtualStart,
}: GridCellProps) => {
    const { GridCellLayout } = useGridComponents()
    const grid = useGridContext()

    const { selectColumn, selectColumnIds } = grid.selectors

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

    const meta: GridRowMeta = useGridSelector((state) =>
        grid.selectors.selectRowMeta(state, rowId)
    )

    const isTreeColumn = !!column.tree
    const level = useGridSelector((state) =>
        isTreeColumn ? grid.selectors.selectRowLevel(state, rowId) : -1
    )

    const align = column.header?.align || 'left'

    const selectColumnIndex = React.useMemo(
        () =>
            createSelector([selectColumnIds], (columnIds) =>
                columnIds.indexOf(columnId)
            ),
        [columnId, selectColumnIds]
    )

    const columnIndex = useGridSelector(selectColumnIndex)
    const treeIndentSize = useGridSelector(grid.selectors.selectTreeIndentSize)

    const elRef = React.useRef<HTMLTableCellElement>(null)

    const paddingLeft = isTreeColumn
        ? calculateIndent(
              level,
              treeIndentSize,
              !meta.type || meta.type === 'leaf'
          )
        : 0

    const { sticky, style } = useCellStickySizing({
        columnId,
        column,
        virtualStart,
        actualWidth,
    })

    return (
        <GridCellLayout
            ref={elRef}
            aria-colindex={columnIndex}
            role="gridcell"
            style={style}
            $sticky={!!sticky}
        >
            <LoaderLayout style={{ paddingLeft }}>
                <SkeletonLoader alignment={align} varied />
            </LoaderLayout>
        </GridCellLayout>
    )
}

export const GridCellLoadingMemo = React.memo(
    GridCellLoading
) as typeof GridCellLoading
