import React, {useEffect, useState} from "react";
import {Link} from "react-router-dom";
import './Nav.scss';
import {useStateValue} from '../services/State'
import {getUser} from "../services/user_service";
import {capitalize} from "../services/utils";

export const Nav = (props) => {
  const context = useStateValue()[0];
  const [user, setUser] = useState(null);

  const showLogin = () => {
    return context.user.auth === false || user === null;
  }

  useEffect(() => {
    if (context.user.auth === false) return;
    getUser(context.user.access_token).then((response) => {
      setUser(response);
    })
  }, [context])

  const registration_link = () =>{
    const params = {next: `${process.env.REACT_APP_CLIENT_HOST}/login`}
    const encoded_params = new URLSearchParams(params).toString();
    return `${process.env.REACT_APP_API_SERVER }/auth/register?${encoded_params}`;
  }

  const buttons = () => {
    if (showLogin()) {
      return <ul className='nav-links'>
        <li className='link'>
          <Link to='/login'>Iniciar Sesión</Link>
        </li>
        <li className='link'>
          <a href={registration_link()}>Registrate</a>
        </li>
      </ul>
    } else {
      return <ul className='nav-links'>
        <li><a href={`/user/${user.id}`}>{capitalize(user.username)}</a></li>
        <li className='link'>
          <Link to='/logout'>Cerrar Sesión</Link>
        </li>
      </ul>
    }
  }

  return (
    <nav className='nav'>
      <Link to='/'><h1 className='branding'>MusicList</h1></Link>
      {buttons()}
    </nav>
  )
}
