import React, {useContext, useEffect, useMemo, useRef, useState} from 'react';
import {Link, NavLink, useParams, useLocation} from 'react-router-dom';
import {getProfilePicture, logout} from '../../../API/user';
import Breadcrumbs from './Breadcrumbs';
import ServiceHeader from './ServiceHeader';
import NotificationPopup from '../Notification/NotificationPopup';
import notify from '../../../assets/images/notify.svg';
import avatarD from '../../../assets/images/avatar.png';
import close from '../../../assets/images/close.png';
import down_arrow from '../../../assets/images/down_arrow.png';
import MessagesReadContext from '../../../context/messagesRead-context';
import './header.scss';
import AuthContext from "../../../context/auth-context";
import SettingsHeader from "./SettingsHeader";

const Header: React.FC = () => {
    let location = useLocation();
    const {application, service, settings_cat} = useParams();
    const {currentUser, logoutUser, userAvatar} = useContext(AuthContext);
    const [profileModal, setProfileModal] = useState(false);
    const [notificationModal, setNotificationModal] = useState(false);
    const {unread} = useContext(MessagesReadContext);
    const profileRef = useRef<HTMLButtonElement>(null);
    const notificationsRef = useRef<HTMLButtonElement>(null);
    const isMessagesPage = useLocation().pathname === '/messages';
    // const isSettingsPage = location.pathname.split(/[/]/)[1] === 'settings';
    const stateToggle =
        notificationModal && unread > 0 && !isMessagesPage ? 'openToggle' : 'closedToggle';
    const messagesLength = unread > 0;


    useEffect(() => {
        const handleClick = (e: any) => {
            if (notificationModal && !(e.source && e.source.current === notificationsRef.current)) {
                setNotificationModal(false)
            }
            if (profileModal && !(e.source && e.source.current === profileRef.current)) {
                setProfileModal(false)
            }
        }
        window.addEventListener('click', handleClick)
        return () => window.removeEventListener('click', handleClick)
        // window.addEventListener("click", () => {
        //
        // 	setProfileModal(false);
        // 	setNotificationModal(false);
        // });
    }, [profileModal, notificationModal]);



    return useMemo(() => {
        return (
            // header left side - header greet - breadcrumb
            <div id={"header"} className={"d-flex flex-column"}>
                <div className={"d-flex  top-header"}> {/* header - header greet */}

                    <Breadcrumbs/>

                    {/* header right side - dd notifications - dd user menu */}
                    <div className="profile d-flex justify-content-between">
                        {/* header right side - dd notifications */}
                        <div className="parent-state">
                            <div
                                className="profile--dd d-flex flex-column"
                                id={stateToggle}
                            >
                                <button
                                    ref={notificationsRef}
                                    className="profile--dd--notification align-items-end d-flex justify-content-end"
                                    id={
                                        isMessagesPage || unread == 0
                                            ? "zero-notification"
                                            : "has-notification"
                                    }
                                    onClick={(e) => {
                                        // @ts-ignore
                                        e.nativeEvent.source = notificationsRef
                                        setNotificationModal(!notificationModal);
                                        // setProfileModal(false);
                                    }}
                                >
                                    <img
                                        width="18"
                                        height="18"
                                        src={notify}
                                        className={
                                            isMessagesPage || unread == 0
                                                ? "inactive-icon"
                                                : ""
                                        }
                                        alt="notifications toggle"
                                    />
                                    {messagesLength && (
                                        <span className="profile--dd--notification--number">
										{unread}
									</span>
                                    )}
                                </button>
                                {notificationModal && unread > 0 && !isMessagesPage && (
                                    <NotificationPopup/>
                                )}
                            </div>
                        </div>
                        {/* header right side - dd user menu */}
                        <div
                            className="profile--dmenu"
                            id={profileModal ? "fixedHeight" : "closed"}
                        >
                            <button
                                ref={profileRef}
                                className="dropdown-toggle-profile d-flex justify-content-between"
                                type="button"
                                id="menuRightDd"
                                title={`${currentUser?.lastname} ${currentUser?.firstname}`}
                                onClick={(e) => {
                                    // e.stopPropagation();
                                    // @ts-ignore
                                    e.nativeEvent.source = profileRef
                                    setProfileModal(!profileModal);
                                    // setNotificationModal(false);
                                    // /setIsOpen(false);
                                }}
                            >
                                <p className="profile--dmenu--userName text-ellipsis">
                                    {currentUser?.lastname} {currentUser?.firstname}
                                </p>

                                <img className={'avatar'} width="35" height="33"
                                     src={userAvatar ? URL.createObjectURL(userAvatar) : avatarD} alt="avatar"/>

                                <div className="dd-image">
                                    {profileModal ? (
                                        <img
                                            className="dd-image-close"
                                            src={close}
                                            alt="x-btn"
                                        />
                                    ) : (
                                        <img
                                            className="dd-image-open"
                                            src={down_arrow}
                                            alt="down_arrow-btn"
                                        />
                                    )}
                                </div>
                            </button>
                            {profileModal && (
                                <ul
                                    className="dropdown-menu-profile"
                                    aria-labelledby="menuRightDd"
                                    id={profileModal ? "show" : ""}
                                >
                                    <li>
                                        <Link className="dropdown-item" to="/settings">
                                            Ρυθμίσεις D.U.A.
                                        </Link>
                                    </li>

                                    <li>
									<span
                                        className="dropdown-item"
                                        id="logout"
                                        onClick={logoutUser}
                                    >
										Logout
									</span>
                                    </li>
                                </ul>
                            )}
                        </div>
                    </div>
                </div>


                {application  && <ServiceHeader/>}
                {settings_cat && <SettingsHeader/>}
            </div>
        );
    }, [unread, profileModal, notificationModal, application, currentUser, logoutUser])
};
export default Header;