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

import {useBottomSheetToolboxInternalContext} from "../context"
import {useLastSharedValue} from "./use-last-shared-value"

/**
 * Returns a shared value holding the last value seen of the input shared value
 * prior to a current position lock being engaged.
 */
export function useLastSharedValueBeforeLock<T>(sharedValue: SharedValue<T>) {
    const {currentPositionLockSharedValue} = useBottomSheetToolboxInternalContext()

    const lastSharedValue = useLastSharedValue(sharedValue)

    const sharedValueBeforeLock = useSharedValue<T | null>(null)
    useAnimatedReaction(
        () => currentPositionLockSharedValue.get(),
        (currentPositionLock, lastCurrentPositionLock) => {
            const didJustLock =
                currentPositionLock !== null && currentPositionLock !== lastCurrentPositionLock

            if (didJustLock) {
                const lastValue = lastSharedValue.get()
                sharedValueBeforeLock.set(lastValue)
            } else {
                sharedValueBeforeLock.set(null)

                /**
                 * When a lock ends take most recent value.
                 */
                lastSharedValue.set(sharedValue.get())
            }
        },
        [currentPositionLockSharedValue.get]
    )

    return sharedValueBeforeLock
}
