import {Container, Nav, Navbar} from 'react-bootstrap';
import {LinkContainer} from 'react-router-bootstrap';
import {userData} from '../../recoilState/usersState';
import {logout} from '../../api/authenticationAPI';
import {useRecoilState} from 'recoil';
import {Link} from 'react-router-dom';

const NavBar = () => {
    const [user, setUser] = useRecoilState(userData);

    const logoutHandler = async () => {
        const success = await logout(user.jwtToken);
        if (success) setUser(undefined);
    }

    return (
        <Navbar bg='dark' variant='dark' expand='lg' className={"mb-4"}>
            <Container fluid>
                <LinkContainer to={'/'}>
                    <Navbar.Brand>Home</Navbar.Brand>
                </LinkContainer>
                <Navbar.Toggle aria-controls="navbar" />
                <Navbar.Collapse id="navbar">
                    <Nav className='me-auto'>
                        <LinkContainer to='/robots'>
                            <Nav.Link>Robots</Nav.Link>
                        </LinkContainer>
                        <LinkContainer to='/manufactures'>
                            <Nav.Link>Manufactures</Nav.Link>
                        </LinkContainer>
                        <LinkContainer to='/categories'>
                            <Nav.Link>Categories</Nav.Link>
                        </LinkContainer>
                    </Nav>
                    {user ? <Navbar.Text>
                        Welcome {user.username}&nbsp;
                        <span style={{color: 'white'}} onClick={logoutHandler}>(Log out)</span>
                    </Navbar.Text> : <Link to={'/login'} style={{color: 'white', textDecoration: 'none'}}>Login</Link>}
                </Navbar.Collapse>

            </Container>
        </Navbar>
    )
}

export default NavBar;
