import {FlashList, type FlashListProps} from "@shopify/flash-list"
import * as React from "react"
import {useSharedValue} from "react-native-reanimated"

import {BottomSheetListWrapper} from "@attio/react-native-bottom-sheet-toolbox"

import {
    FlashListScrollComponent,
    InvertedFlashListScrollComponent,
} from "./flash-list-scroll-component"

export type BottomSheetFlashListProps<T> = Omit<
    FlashListProps<T>,
    "bounces" | "renderScrollComponent"
> & {
    ref?: React.ForwardedRef<FlashList<T>>
}

export function BottomSheetFlashList<T>({
    ref,
    inverted = false,
    onContentSizeChange,
    ...rest
}: BottomSheetFlashListProps<T>) {
    const contentHeightSharedValue = useSharedValue<number | null>(null)

    const innerOnContentSizeChange = React.useCallback(
        (w: number, h: number) => {
            onContentSizeChange?.(w, h)
            contentHeightSharedValue.set(h)
        },
        [onContentSizeChange]
    )

    return (
        <BottomSheetListWrapper contentHeightSharedValue={contentHeightSharedValue}>
            <FlashList
                ref={ref}
                bounces={false}
                renderScrollComponent={
                    inverted ? InvertedFlashListScrollComponent : FlashListScrollComponent
                }
                onContentSizeChange={innerOnContentSizeChange}
                inverted={inverted}
                {...rest}
            />
        </BottomSheetListWrapper>
    )
}
