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

import {useBottomSheetToolboxInternalContext} from "../context"

/**
 * An internal check to determine if the bottom-sheet has been initialized and
 * is ready to display.
 *
 * The argument outerIsReady is offered as a way to allow the consumer to extend
 * the check to include other conditions.
 */
export function useBottomSheetIsReady(outerIsReady: SharedValue<boolean> | boolean) {
    const {
        normalizedSnapPointsSharedValue,
        wrapperHeightSharedValue,
        childrenHeightSharedValue,
        isReadySharedValue,
    } = useBottomSheetToolboxInternalContext()

    useAnimatedReaction(
        () => {
            const isOuterReady =
                typeof outerIsReady === "boolean" ? outerIsReady : outerIsReady.get()
            const isNormalizedSnapPointsReady = normalizedSnapPointsSharedValue.get() !== null
            const isWrapperHeightReady = wrapperHeightSharedValue.get() !== null
            const isChildrenHeightReady = childrenHeightSharedValue.get() !== null

            return (
                isOuterReady &&
                isNormalizedSnapPointsReady &&
                isWrapperHeightReady &&
                isChildrenHeightReady
            )
        },
        (newIsReady) => {
            if (newIsReady === isReadySharedValue.get()) return
            isReadySharedValue.set(newIsReady)
        },
        [
            outerIsReady,
            childrenHeightSharedValue,
            wrapperHeightSharedValue,
            normalizedSnapPointsSharedValue,
        ]
    )
}
