import { getBooleanOrDefault } from '../../utils'
import type { SwitchControlInstance, SwitchControlProps } from './types'
import { isProdMode } from '/@/utils/env'

/**
 * 前后切换组件响应式 Hook
 * @param props 组件参数
 * @returns 组件响应式数据
 */
export function useSwitchControlWidget<T extends SwitchControlInstance>(
    props: SwitchControlProps,
): [(instance: T) => void, T] {
    const instanceRef = ref<Nullable<T>>(null)

    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('前后切换小部件还未加载完成')
        }
        return instance as T
    }

    return [
        register,
        {
            setProps: (props: SwitchControlProps) => {
                getInstance()?.setProps(props)
            },
            toggleShow: (show?: boolean) => {
                getInstance()?.toggleShow(getBooleanOrDefault(show))
            },
            prev: () => {
                getInstance()?.prev()
            },
            next: () => {
                getInstance()?.next()
            },
        } as T,
    ]
}
