import React, { Suspense, useCallback, useMemo } from 'react'
import LoadingPage from '../components/loading-page'
import { useAppContext } from '../app'
import PopupComponent from '../components/popup'

export default function usePopups() {
    const { flash } = useAppContext()
    const [popups, setPopups] = React.useState<(JSX.Element)[]>([])
    const [showClose, setShowClose] = React.useState(true)
    const removePopup = useCallback((all?: boolean) => {
        setPopups((popups) => all ? [] : popups.slice(1))
    }, [])
    const addPopup = useCallback((popup: string, options?: any) => {
        let element: JSX.Element | null = null
        switch (popup) {
            default: {
                console.error('Unknown popup: ' + popup)
                flash('Unknown popup: ' + popup)
                break
            }
        }
        if (element) {
            setPopups((popups) => {
                return [element, ...popups]
            })
        }
    }, [removePopup])
    const Popup = useMemo(() => {
        const PopupContent = popups.length > 0 ? popups[0] : null
        return PopupContent && <PopupComponent removePopup={showClose ? removePopup : undefined}>
            <Suspense fallback={<LoadingPage />}>
                {PopupContent}
            </Suspense></PopupComponent>
    }, [popups])
    return { addPopup, removePopup, Popup, setShowClose }
}