import React from "react"

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

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

export interface BottomSheetToolboxStackSheetProps extends React.PropsWithChildren {
    name: string
    sheetRef: React.RefObject<BottomSheetToolboxRef | null>
    isReady: boolean
}

export function BottomSheetToolboxStackSheet({
    name,
    children,
    sheetRef,
    isReady,
}: BottomSheetToolboxStackSheetProps) {
    const {sheetStack, activeSheet, sheetRefsRef} = useBottomSheetToolboxStackContext()

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

    const lastKnownSnapIndex = React.useRef<number | null>(null)

    if (sheetRefsRef.current !== null && sheetRef.current !== null) {
        sheetRefsRef.current[name] = sheetRef.current
    }

    React.useEffect(() => {
        if (isMounted) return
        lastKnownSnapIndex.current = null
    }, [isMounted])

    const lastIsActiveRef = React.useRef<boolean>(isActive)
    React.useEffect(() => {
        if (!isReady) return

        const lastIsActive = lastIsActiveRef.current
        if (lastIsActive && !isActive) {
            const snapIndex = sheetRef.current?.getCurrentSnapIndex() || null
            lastKnownSnapIndex.current = snapIndex
            sheetRef.current?.close()
        } else if (!lastIsActive && isActive) {
            if (lastKnownSnapIndex.current !== null) {
                if (lastKnownSnapIndex.current === 0) {
                    sheetRef.current?.expand()
                } else {
                    sheetRef.current?.snapToIndex(lastKnownSnapIndex.current)
                }
            }
        }

        lastIsActiveRef.current = isActive
    }, [isActive, sheetRef, isReady])

    return isMounted ? (
        <BottomSheetToolboxBackdropProvider hide={!isActive}>
            <BottomSheetToolboxInternalProvider reset>
                {children}
            </BottomSheetToolboxInternalProvider>
        </BottomSheetToolboxBackdropProvider>
    ) : null
}
