import {nanoid} from "nanoid"
import * as React from "react"

import {useBottomSheetActions} from "./use-bottom-sheet-actions"

// biome-ignore lint/suspicious/noExplicitAny: not useful to type
export function useBottomSheetCallbackAfterClose<T extends (...args: any) => any>(callback: T) {
    const [id] = React.useState(() => `useBottomSheetCallbackAfterClose:${nanoid()}`)
    const {close} = useBottomSheetActions(id)

    // biome-ignore lint/suspicious/noExplicitAny: not useful to type
    const givenArgsRef = React.useRef<{args: any[]} | null>(null)

    const lastCallbackRef = React.useRef(callback)
    lastCallbackRef.current = callback
    React.useEffect(() => {
        return () => {
            if (givenArgsRef.current === null) return

            if (givenArgsRef.current) {
                lastCallbackRef.current(...givenArgsRef.current.args)
            } else {
                lastCallbackRef.current()
            }
        }
    }, [])

    // biome-ignore lint/suspicious/noExplicitAny: not useful to type
    return (...args: any[]) => {
        givenArgsRef.current = {args}
        close()
    }
}
