import React, { useState, useEffect } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { authService } from '../services/auth';
import config from '../config';
import './Navigation.css';

function Navigation() {
  const [user, setUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const location = useLocation();

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const userData = await authService.getUser();
        setUser(userData);
      } catch (error) {
        console.error('Auth check failed:', error);
      } finally {
        setIsLoading(false);
      }
    };

    checkAuth();
  }, []);

  const handleLogin = () => {
    window.location.href = `${config.api.url}/login`;
  };

  const handleLogout = () => {
    window.location.href = `${config.api.url}/logout`;
  };

  const isActive = (path) => location.pathname === path;

  if (isLoading) {
    return (
      <nav className="navigation">
        <div className="nav-brand">
          <Link to="/">Container Mom</Link>
        </div>
        <div className="nav-loading">Loading...</div>
      </nav>
    );
  }

  return (
    <nav className="navigation">
      <div className="nav-brand">
        <Link to="/">Container Mom</Link>
      </div>
      
      <div className="nav-links">
        {user && (
          <>
            <Link 
              to="/deployments" 
              className={`nav-link ${isActive('/deployments') ? 'active' : ''}`}
            >
              Deployments
            </Link>
          </>
        )}
      </div>

      {user ? (
        <div className="nav-user">
          <div className="user-menu">
            <button className="user-button">
              {user.email}
              <span className="arrow">▼</span>
            </button>
            <div className="dropdown-menu">
              <Link to="/profile">Profile</Link>
              <button onClick={handleLogout}>
                Log Out
              </button>
            </div>
          </div>
        </div>
      ) : (
        <div className="nav-auth">
          <button onClick={handleLogin} className="login-btn">
            Log In
          </button>
          <button 
            onClick={handleLogin} 
            className="signup-btn"
          >
            Sign Up
          </button>
        </div>
      )}
    </nav>
  );
}

export default Navigation; 