import type {LayoutChangeEvent} from "react-native"
import * as React from "react"
import Animated, {type SharedValue, useAnimatedStyle, useSharedValue} from "react-native-reanimated"

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

interface BottomSheetListWrapperProps extends React.PropsWithChildren {
    contentHeightSharedValue: SharedValue<number | null>
}

export function BottomSheetListWrapper({
    children,
    contentHeightSharedValue,
}: BottomSheetListWrapperProps) {
    const containerYSharedValue = useSharedValue<number | null>(null)
    const {wrapperHeightSharedValue, footerHeightSharedValue} =
        useBottomSheetToolboxInternalContext()

    const flashListContainerStyle = useAnimatedStyle(() => {
        const wrapperHeight = wrapperHeightSharedValue.get()
        const containerY = containerYSharedValue.get()
        const contentHeight = contentHeightSharedValue.get()
        const footerHeight = footerHeightSharedValue.get()

        return {
            flexGrow: 1,
            height: contentHeight || undefined,
            minHeight: 10, // Prevent FlashList warning as we initialize
            maxHeight:
                wrapperHeight !== null && containerY !== null
                    ? wrapperHeight - containerY - (footerHeight ?? 0)
                    : undefined,
            width: "100%",
        }
    }, [contentHeightSharedValue, wrapperHeightSharedValue, footerHeightSharedValue])

    const onLayout = React.useCallback((evt: LayoutChangeEvent) => {
        containerYSharedValue.set(evt.nativeEvent.layout.y)
    }, [])

    return (
        <Animated.View style={flashListContainerStyle} onLayout={onLayout}>
            {children}
        </Animated.View>
    )
}
