import { getBooleanOrDefault } from '../../utils'
import type { BottomBarInstance, BottomBarProps } from './types'
import { isProdMode } from '/@/utils/env'

/**
 * 底部交互/展示小部件响应式 Hook
 * @param props 组件参数
 * @returns 组件响应式数据
 */
export function useBottomBarWidget<T extends BottomBarInstance>(props: BottomBarProps): [(instance: T) => void, T] {
    const instanceRef = ref<Nullable<T>>(null)
    const height = computed(() => instanceRef?.value?.height)

    function register(instance: T) {
        if (isProdMode()) {
            if (instance === unref(instanceRef)) {
                return
            }

            onUnmounted(() => {
                instanceRef.value = null
            })
        }

        instanceRef.value = instance
        props && instance.setProps(props)
    }

    function getInstance(): T {
        const instance = unref(instanceRef)
        if (!instance) {
            console.warn('BottomBar 小部件还未加载完成')
        }
        return instance as T
    }

    return [
        register,
        {
            height,
            setProps: (props: BottomBarProps) => {
                getInstance()?.setProps(props)
            },
            toggleShow: (show?: boolean) => {
                getInstance()?.toggleShow(getBooleanOrDefault(show))
            },
            toggleExpand: (expand?: boolean) => {
                getInstance()?.toggleExpand(getBooleanOrDefault(expand))
            },
        } as T,
    ]
}
