import React from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import axios from 'axios';

const Navbar = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const user = JSON.parse(localStorage.getItem('user') || '{}');

  const handleLogout = async () => {
    try {
      await axios.post('http://localhost:5000/api/auth/logout', {}, { withCredentials: true });
      localStorage.removeItem('user');
      navigate('/login');
    } catch (error) {
      console.error('Logout error:', error);
    }
  };

  const menuItems = [
    { path: '/', name: 'Dashboard'},
    { path: '/employees', name: 'Employee'},
    { path: '/departments', name: 'Department'},
    { path: '/salaries', name: 'Salary'},
    { path: '/reports', name: 'Reports'},
  ];

  return (
    <nav className="bg-blue-600 text-white shadow-lg">
      <div className="container mx-auto px-4">
        <div className="flex justify-between items-center py-3">
          <div className="flex items-center space-x-2">
            <span className="font-bold text-xl">SmartPark EPMS</span>
          </div>

          <div className="flex items-center space-x-1">
            {menuItems.map((item) => (
              <button
                key={item.path}
                onClick={() => navigate(item.path)}
                className={`px-4 py-2 rounded-md transition duration-200 flex items-center space-x-2
                  ${location.pathname === item.path 
                    ? 'bg-blue-700' 
                    : 'hover:bg-blue-500'}`}
              >
                <span>{item.icon}</span>
                <span>{item.name}</span>
              </button>
            ))}
            <button
              onClick={handleLogout}
              className="px-4 py-2 rounded-md hover:bg-red-500 transition duration-200 flex items-center space-x-2 ml-4"
            >
              <span>Logout</span>
            </button>
          </div>

          <div className="text-sm flex items-center space-x-2">
            <span>{user.username || 'User'}</span>
          </div>
        </div>
      </div>
    </nav>
  );
};

export default Navbar;