import React, {ReactNode, useEffect, useState} from 'react';
import {createPortal} from "react-dom";
import './floating-widget.scss'

type FloatingWidgetProps = {
    children?: ReactNode
    title: string
    icon: any
    urgent?: boolean
    forceClose?: number
}


/**
 *  This Component is Wrapper for Widgets.
 *
 *  Widgets appear on the right side of the screen dn you open close them
 *  They use a portal to get positioned properly
 *
 *  The wrapped component can have whatever functionality you want
 *
 *  e.g.
 *  The calendar when you create a new invitation,
 *  The Active Visits widget where you see your visitors that have checked-in
 *  The navigation menu on your Personal Folder
 */
const FloatingWidget = ({children, title, icon , forceClose, urgent = false}: FloatingWidgetProps) => {

    const [isOpen, setIsOpen] = useState(false)

    const widgetBodyClass = document.querySelector('.personal-folder-nav') ?? null;

    if (widgetBodyClass) {
        const targetLinks = document.querySelectorAll('#targetLink li a');
        targetLinks.forEach (function (link) {
            link.addEventListener('click', function classManipulator () {
                setIsOpen(false);
            })
        })
    }

    useEffect(()=>{

        isOpen && setIsOpen(false)
// eslint-disable-next-line react-hooks/exhaustive-deps
    }, [forceClose])

    return createPortal(
        <div className={`floating-widget ${isOpen && 'open'}`}>
            <div className="floating-widget--head" onClick={()=>setIsOpen(!isOpen)}>
                {urgent && <div className={'urgent'}></div>}
                <img src={icon} alt="calendar" width={32} height={32}/>
                <p>{title}</p>
                <span className={'close'}>x</span>
            </div>
            <div className="floating-widget--body" >
                {children}
            </div>
        </div>,
        document.querySelector('#floating-widgets-container') || document.body
    );

}

export default FloatingWidget;
