import React, {ReactNode, useContext, useEffect, useRef, useState} from 'react';
import notify from "../../../assets/images/notify.svg";
import NotificationPopup from "../Notification/NotificationPopup";
import {useLocation} from "react-router-dom";
import NotificationsContext from "../../../context/notifications-context";

type NotificationsBellProps = {
    children?: ReactNode
}

const NotificationsBell = ({children}: NotificationsBellProps) => {

    const [notificationModal, setNotificationModal] = useState(false);
    const notificationsRef = useRef<HTMLButtonElement>(null);
    const isMessagesPage = useLocation().pathname === '/messages';
    const {unread} = useContext(NotificationsContext);


    useEffect(() => {
        const handleClick = (e: any) => {
            if (notificationModal && !(e.source && e.source.current === notificationsRef.current)) {
                setNotificationModal(false)
            }

        }
        window.addEventListener('click', handleClick)
        return () => window.removeEventListener('click', handleClick)
    }, [notificationModal]);

    return (
        <div className="parent-state notifications-btn">
            <div
                title={unread === 0 ? 'Δεν υπάρχουν Νέα Μηνύματα' :''}
                className={`profile--dd d-flex flex-column ${notificationModal && 'open-notifications'} ${(isMessagesPage || unread === 0) && 'inactive'}`}

            >
                <button
                    ref={notificationsRef}
                    className="profile--dd--notification align-items-end d-flex justify-content-end"
                    onClick={(e) => {
                        // @ts-ignore
                        e.nativeEvent.source = notificationsRef
                        setNotificationModal(!notificationModal);

                    }}
                >
                    <img

                        width="18"
                        height="18"
                        src={notify}
                        alt="notifications toggle"
                    />
                    {unread > 0 && (
                        <span className="profile--dd--notification--number">
										{unread}
									</span>
                    )}
                </button>
                {notificationModal && unread > 0 && !isMessagesPage && (
                    <NotificationPopup close={()=>setNotificationModal(false)}/>
                )}
            </div>
        </div>
    );
}

export default NotificationsBell;