import React from "react"
import {runOnJS, useAnimatedReaction} from "react-native-reanimated"

import type {BottomSheetToolboxDevToolsMessageFromRN} from "../../utils/dev-tools-adapter"
import {useBottomSheetToolboxInternalContext} from "../../context"
import {BOTTOM_SHEET_DEV_TOOLS} from "../../utils"

export function useBottomSheetDevToolsUpsertSheet() {
    const {
        currentPositionSharedValue,
        normalizedSnapPointsSharedValue,
        wrapperHeightSharedValue,
        isReadySharedValue,
        debugId,
    } = useBottomSheetToolboxInternalContext()

    const sendSheetMessage = React.useCallback(
        (
            payload: Omit<
                Extract<BottomSheetToolboxDevToolsMessageFromRN, {type: "upsert-sheet"}>["payload"],
                "sheetId"
            >
        ) => {
            BOTTOM_SHEET_DEV_TOOLS.sendMessage("upsert-sheet", {
                ...payload,
                sheetId: debugId,
            })
        },
        [debugId]
    )

    useAnimatedReaction(
        () => ({
            currentPosition: currentPositionSharedValue.get(),
            snapPoints: normalizedSnapPointsSharedValue.get(),
            wrapperHeight: wrapperHeightSharedValue.get(),
            isReady: isReadySharedValue.get(),
        }),
        ({currentPosition, snapPoints, wrapperHeight, isReady}) => {
            runOnJS(sendSheetMessage)({currentPosition, snapPoints, wrapperHeight, isReady})
        },
        [
            currentPositionSharedValue,
            normalizedSnapPointsSharedValue,
            wrapperHeightSharedValue,
            isReadySharedValue,
        ]
    )
}
