import {Platform} from "react-native"
import {useDerivedValue} from "react-native-reanimated"
import {useSafeAreaInsets} from "react-native-safe-area-context"

import {useKeyboardHeightSharedValue} from "../context"

export function useKeyboardAwareSafeAreaBottomInset(fallbackInset: number) {
    const insets = useSafeAreaInsets()
    const keyboardHeightSharedValue = useKeyboardHeightSharedValue()

    return useDerivedValue(() => {
        switch (Platform.OS) {
            case "android":
                return insets.bottom + Math.min(keyboardHeightSharedValue.get(), fallbackInset)

            case "ios":
                return (
                    insets.bottom -
                    Math.min(keyboardHeightSharedValue.get(), insets.bottom - fallbackInset)
                )
        }

        return fallbackInset
    }, [insets.bottom, keyboardHeightSharedValue, fallbackInset])
}
