import { useState, useContext, FunctionComponent, useRef } from 'react'
import Link from 'next/link'
import LogoutButton from './LogoutButton'
import LoginForm from './LoginForm'
import { UserContext } from '../hooks'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faUser, faUserNinja } from '@fortawesome/free-solid-svg-icons'
import { Permission } from '../../gql'
import theme from '../../styles/theme'
import { useOnClickOutside } from '../../lib/onClickOutside'

const UserNav = () => {
  const [menu, setMenu] = useState(false)
  const ref = useRef<HTMLLIElement>(null)
  const { user } = useContext(UserContext)
  useOnClickOutside(ref, () => {
    setMenu(false)
  })

  return (
    <>
      {user?.data?.currentUser.permissions.includes(Permission.Admin) && (
        <li>
          <Link href='/admin'>
            <a>
              <FontAwesomeIcon icon={faUserNinja} />
              Admin
            </a>
          </Link>
        </li>
      )}
      <li ref={ref} className='menupoint'>
        <a
          href=''
          onClick={(event) => {
            event.preventDefault()
            setMenu(!menu)
          }}
        >
          <FontAwesomeIcon icon={faUser} />
          {user?.data ? user.data.currentUser.name : 'Login'}
        </a>

        {menu ? (
          <section className='usermenu'>
            {user?.data && (
              <>
                <h2>Welcome, {user.data.currentUser.name}</h2>
                <Link href={{ pathname: 'user' }}>
                  <a>Edit user data</a>
                </Link>
                <LogoutButton />
              </>
            )}
            {user?.error && <LoginForm />}
          </section>
        ) : null}
      </li>

      <style jsx>{`
        .usermenu {
          padding: 1em 0.3em;
          color: ${theme.colors.mobileNav};
          background-color: ${theme.colors.mobileNavBackground};
          align-content: end;
        }
        .usermenu :global(a) {
          color: ${theme.colors.mobileNav};
        }
        @media (min-width: ${theme.fullsize}) {
          .usermenu {
            position: absolute;
            right: 0;
            top: 100%;
            padding: 1em;
          }
        }
      `}</style>
    </>
  )
}

export default UserNav
