import React from "react"

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

import {useBottomSheetToolboxStackContext} from "./context/bottom-sheet-toolbox-stack-context"

export interface SheetProps<T extends BottomSheetToolboxRef> {
    ref: React.RefObject<T | null>
    onClose: () => void
    onReadyChange: (ready: boolean) => void
}

export function useBottomSheetToolboxStackSheet<T extends BottomSheetToolboxRef>(name: string) {
    const {notifyClosed, sheetStack, activeSheet} = useBottomSheetToolboxStackContext()
    const sheetRef = React.useRef<T>(null)

    const [isReady, setIsReady] = React.useState(false)

    const isActive = activeSheet === name
    const isMounted = sheetStack.includes(name)

    React.useEffect(() => {
        if (!isMounted) {
            setIsReady(false)
        }
    }, [isMounted])

    return React.useMemo(
        () => ({
            wrapperProps: {
                sheetRef,
                name,
                isReady,
            },
            sheetProps: {
                ref: sheetRef,
                onClose() {
                    notifyClosed(name)
                },
                onReadyChange(ready: boolean) {
                    setIsReady(ready)
                },
            },
            isActive,
            isMounted,
        }),
        [isActive, isMounted, isReady, name, notifyClosed]
    )
}
