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

import {useBottomSheetToolboxInternalContext} from "../context"
import {CLOSED_SNAP_POINT} from "../utils"

export function useBottomSheetOnCloseDetection(onClose?: () => void) {
    const {isReadySharedValue, currentPositionSharedValue} = useBottomSheetToolboxInternalContext()
    const hasOpenedSharedValue = useSharedValue(false)

    useAnimatedReaction(
        () => currentPositionSharedValue.get(),
        (currentPosition) => {
            if (currentPosition === null || !isReadySharedValue.get()) return

            hasOpenedSharedValue.set(
                hasOpenedSharedValue.get() || currentPosition > CLOSED_SNAP_POINT
            )
            const didClose = hasOpenedSharedValue.get() && currentPosition === CLOSED_SNAP_POINT

            if (didClose) {
                hasOpenedSharedValue.set(false)
                if (onClose) runOnJS(onClose)()
            }
        },
        [currentPositionSharedValue]
    )
}
