import {runOnJS, useAnimatedReaction} from "react-native-reanimated"

import {useBottomSheetToolboxInternalContext} from "../context"

export function useBottomSheetOnSnapDetection(
    onSnapChange?: (currentSnapIndex: number, lastSnapIndex: number | null) => void
) {
    const {isReadySharedValue, normalizedSnapPointsSharedValue, currentPositionSharedValue} =
        useBottomSheetToolboxInternalContext()

    useAnimatedReaction(
        () => {
            const normalizedSnapPoints = normalizedSnapPointsSharedValue.get()
            if (!isReadySharedValue.get() || normalizedSnapPoints === null) return null

            const snapPointIndex = normalizedSnapPoints.indexOf(currentPositionSharedValue.get())

            return snapPointIndex === -1 ? null : snapPointIndex
        },
        (currentSnapIndex, lastSnapIndex) => {
            if (currentSnapIndex === null) return
            if (onSnapChange) runOnJS(onSnapChange)(currentSnapIndex, lastSnapIndex)
        },
        [isReadySharedValue, normalizedSnapPointsSharedValue, currentPositionSharedValue]
    )
}
