import {useDerivedValue} from "react-native-reanimated"

import {useBottomSheetToolboxInternalContext} from "../context"
import {normalizeSheetPosition, type SheetPosition} from "../utils"

/**
 * Normalizes an array of SnapPoints to a SharedValue array of positions represented as numbers.
 */
export function useNormalizedSnapPoints(snapPoints: readonly SheetPosition[]) {
    const {childrenHeightSharedValue, wrapperHeightSharedValue, footerHeightSharedValue} =
        useBottomSheetToolboxInternalContext()

    return useDerivedValue(() => {
        const unsorted = snapPoints.map((sp) =>
            normalizeSheetPosition({
                sheetPosition: sp,
                childrenHeightSharedValue,
                wrapperHeightSharedValue,
                footerHeightSharedValue,
            })
        )

        const isPrepared = unsorted.every((snapPoint) => snapPoint !== null)
        if (!isPrepared) return null
        const prepared = unsorted as number[]

        prepared.sort((a, b) => a - b)

        // TODO: these should probably be clamped to the sheets bounds.

        return prepared
    }, [childrenHeightSharedValue, wrapperHeightSharedValue, footerHeightSharedValue, snapPoints])
}
