import { useState, useRef, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Link } from 'react-router-dom';

import { useLogoutMutation } from '/src/api/apiSlice'

export const UserBurger = () => {
  const username = useSelector( s => s.auth.username );
  const [ logout ] = useLogoutMutation()

  const [open, setOpen] = useState(false);
  const toggleRef = useRef(null);
  const menuRef   = useRef(null);

  useEffect(() => {
    const handleOutside = e => {
      if (
        menuRef.current &&
        !menuRef.current.contains(e.target) &&
        toggleRef.current &&
        !toggleRef.current.contains(e.target)
      ) {
        setOpen(false)
      }
    }
    document.addEventListener('mousedown', handleOutside)
    return () => document.removeEventListener('mousedown', handleOutside)
  }, []);

  return (
    <ul className="navbar-nav ml-auto">
      <li className="nav-item dropdown no-arrow">
        <button
          ref={toggleRef}
          className="nav-link dropdown-toggle btn btn-link p-0"
          onClick={() => setOpen(o => !o)}
          aria-haspopup="true"
          aria-expanded={open}
        >
          <i className="fas fa-user-circle fa-fw"></i>
          <span className="ml-2 d-none d-lg-inline text-gray-600 small">
            {username}
          </span>
        </button>

        {open && (
          <div
            ref={menuRef}
            className="dropdown-menu dropdown-menu-right shadow animated--grow-in show"
            aria-labelledby="userMenu"
          >
            <Link
              className="dropdown-item"
              to="/user"
              onClick={() => setOpen(false)}
            >
              <i className="fas fa-user fa-sm fa-fw mr-2 text-gray-400"></i>
              Профиль
            </Link>
            <div className="dropdown-divider"></div>
            <button
              className="dropdown-item"
              onClick={() => { setOpen(false); logout() }}
            >
              <i className="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
              Выйти
            </button>
          </div>
        )}
      </li>
    </ul>
  )
}
