import { useState, useEffect } from 'react'
import Link from 'next/link'
import { useQuery } from '@apollo/client'
import { CURRENT_USER } from './graphql'
import LogoutButton from './components/LogoutButton'
import LoginForm from './components/LoginForm'

const UserNav = props => {
  const [menu, setMenu] = useState(false)

  return (
    <>
      <a
        href='' onClick={ev => {
          ev.preventDefault()
          setMenu(!menu)
        }}
      >sali
      </a>
      {menu ? (
        <UserNavMenu />
      ) : null}
    </>
  )
}

const UserNavMenu = props => {
  const { data, loading, error } = useQuery(CURRENT_USER, { fetchPolicy: 'cache-and-network' })
  console.log('UserNav', data, loading, error && error.message)
  const user = data && data.me

  if (loading) return <p>Loading user data...</p>
  if (error) return <p>Error loading user data.</p>

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

      <style jsx>
        {`
          section.usermenu {
          position: absolute;
          background: rgba(127,0,0,0.5);
          }
        `}
      </style>
    </section>
  )
}

const User = props => <a />

export { UserNav }
export default User
