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 = localStorage.getItem('user')
    const response = await axios.get(`/users/${userId}`)
    console.log(response.data.username)

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

  useEffect((user) => {
    if (localStorage.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} 님 환영합니다</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
