import React, { useEffect } from 'react'
import { useGridContext } from '../context/grid-context/hook'

export const useColumnResize = (id: string, actualWidth: number) => {
    const { events, api } = useGridContext()

    const [resizing, setResizing] = React.useState<{
        initialWidth: number
        initialX: number
    } | null>(null)

    const onPointerDown = React.useCallback(
        (e: React.PointerEvent<HTMLDivElement>) => {
            e.preventDefault()
            e.stopPropagation()
            setResizing({
                initialWidth: actualWidth,
                initialX: e.clientX,
            })
            const target = e.target as HTMLDivElement
            target.setPointerCapture(e.pointerId)
        },
        [actualWidth]
    )

    const animationRef = React.useRef<number | null>(null)

    const onPointerMove = React.useCallback(
        (e: React.PointerEvent<HTMLDivElement>) => {
            const { initialWidth, initialX } = resizing!
            const newWidth = Math.floor(initialWidth + e.clientX - initialX)

            if (animationRef.current) {
                window.cancelAnimationFrame(animationRef.current)
            }
            animationRef.current = window.requestAnimationFrame(() => {
                api.column.resizeColumn(id, newWidth)
            })
        },
        [id, resizing, api]
    )

    useEffect(
        () => () => {
            if (animationRef.current) {
                window.cancelAnimationFrame(animationRef.current)
            }
        },
        []
    )

    const onLostPointerCapture = React.useCallback(() => {
        setResizing(null)
        events.emit('onColumnStateChange')
    }, [events])

    return [
        resizing,
        {
            onPointerDown,
            onPointerMove: resizing ? onPointerMove : undefined,
            onLostPointerCapture,
        },
    ]
}
