import { NavLink } from "react-router-dom"
import { useNavigate } from "react-router-dom"
import styles from './Header.module.css'
import { Button, ClickAwayListener, Grow } from "@mui/material"
import Paper from '@mui/material/Paper';
import Popper from '@mui/material/Popper';
import MenuItem from '@mui/material/MenuItem';
import MenuList from '@mui/material/MenuList';
import { useRef, useState } from "react"
import { shallowEqual, useSelector } from "react-redux/es/exports"
import { AppDispatch, AppState, useAppDispatch } from "../../store/store";
import { setToInitState } from "../../store/user/user.slice";

const Header: React.FunctionComponent = (): React.ReactElement => {

    const {user, isAuth} = useSelector((state: AppState) => state.users, shallowEqual)

    const [open, setOpen] = useState<boolean>(false);

    const anchorRef = useRef<HTMLButtonElement>(null);

    const navigate = useNavigate()

    const dispatch: AppDispatch = useAppDispatch()

    const logoutHandler = () => {
        localStorage.removeItem('token')
        dispatch(setToInitState())
    }

    const navigateToPage = (page: string): void => {
        setOpen(false)
        navigate(`${page}`)
    }

    const handleClose = (event: Event | React.SyntheticEvent) => {
        if (
            anchorRef.current &&
            anchorRef.current.contains(event.target as HTMLElement)
        ) {
            return;
        }
    
        setOpen(false);
        };

    return(
        <div>
            <header className={styles.Header}>
            <div className={styles.Header_inner_container}>
                <div className={styles.LinksBlock}>
                    <NavLink to={'/'}>
                        Home
                    </NavLink>
                    {
                        isAuth  ?
                        <div style={{display: 'flex', alignItems: 'center'}}>
                            <h4 style={{margin: 0, color: 'black', marginRight: '40px'}}>
                                <span style={{fontWeight: 'normal', marginRight: '10px'}}>Hello,</span><NavLink to={`/user/${user?._id}`}>{user?.username}</NavLink>
                            </h4>
                            <button className={styles.Header_button} onClick={logoutHandler}>Logout</button>
                        </div> :
                        <div>
                            <button className={styles.Header_button} onClick={()=>{navigateToPage('authorize')}}>Authorize</button>
                        </div>
                    }
                </div>
            </div>
            </header>
        </div>
    )
}

export default Header