import axios from 'axios';
import React, { useState, useEffect } from 'react';
import { Navbar, Nav, Button } from 'react-bootstrap';
import { handleLogout, isAuthenticated } from '../utils/auth';

function Menu() {
  const user = isAuthenticated()
  const [userName, setUsername] = useState('')

  async function getLoginedUser() {
    const userid = sessionStorage.getItem('user')
    const response = await axios.get(`/users/${userid}`, { '_id': userid })
    console.log(response.data)

    const resName = response.data
    //const resName = JSON.stringify(response.data.username)
    console.log(resName)
    setUsername(resName)
  }
  console.log(userName.username)

  useEffect((user) => {
    if (sessionStorage.getItem('user')) {
      getLoginedUser(user)
    }
  }, [])


  return (
    <Navbar bg="dark" variant="dark">
      <Navbar.Brand href="/home">YDK Messenger</Navbar.Brand>

      {user ?
        <>
          <div className='ml-1 mr-2' style={{ color: 'white' }}>{userName.username} 님 환영합니다</div>
          <Nav className="mr-auto">
            <Nav.Link href="/home">Home</Nav.Link>
            <Nav.Link href="/profile">Profile</Nav.Link>
            <Nav.Link href="/hello">Hello</Nav.Link>
          </Nav>
          <Button className="ml-auto" onClick={() => handleLogout()} variant="light" className="ml-3">Logout</Button>
        </>
        : <Nav className="ml-auto">
          <Nav.Link href='/login'>로그인</Nav.Link>
          <Nav.Link href='/signup'>회원가입</Nav.Link>
        </Nav>}

    </Navbar>
  )
}

export default Menu
