import { useState, useContext } 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 } from '@fortawesome/free-solid-svg-icons'
import { Permission } from '../../gql'
import theme from '../../styles/theme'

const UserNav = () => {
  const [menu, setMenu] = useState(false)
  const { user } = useContext(UserContext)

  return (
    <>
      {user?.data?.currentUser.permissions.includes(Permission.Admin) && (
        <li>
          <Link href='admin'>
            <a>Admin</a>
          </Link>
        </li>
      )}
      <li className='menupoint'>
        <a
          href=''
          onClick={(ev) => {
            ev.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 {
          position: absolute;
          right: 0;
          top: 100%;

          color: ${theme.colors.offWhite};
          background-color: ${theme.colors.nav};
          align-content: end;
        }
        .usermenu :global(a) {
          color: ${theme.colors.offWhite};
        }
      `}</style>
    </>
  )
}

export default UserNav
