import React, { useState } from 'react';
import { NavLink, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';

const navItems = [
  { to: '/vehicles', label: 'Vehicle', icon: '🚛' },
  { to: '/trips', label: 'Trip', icon: '🗺️' },
  { to: '/maintenance', label: 'Maintenance', icon: '🔧' },
  { to: '/reports', label: 'Reports', icon: '📈' },
];

export default function Navbar() {
  const { logout, user } = useAuth();
  const navigate = useNavigate();
  const [open, setOpen] = useState(false);

  const handleLogout = async () => {
    await logout();
    navigate('/login');
  };

  return (
    <div className="bg-white border-b border-gray-200">
      <div className="mx-auto flex max-w-7xl items-center justify-between px-4 py-4 md:px-6">
        <div className="flex items-center gap-3">
          <div className="text-3xl">🚛</div>
          <div>
            <h1 className="text-xl font-bold text-gray-900">FMS</h1>
            <p className="text-sm text-gray-500">Fleet Management System</p>
          </div>
        </div>
        <div className="flex items-center gap-3 lg:hidden">
          <button type="button" onClick={() => setOpen((prev) => !prev)} className="rounded-lg border border-gray-200 bg-white px-3 py-2 text-gray-600 hover:bg-gray-50">
            {open ? 'Close' : 'Menu'}
          </button>
        </div>
        <div className="hidden items-center gap-3 lg:flex">
          {navItems.map((item) => (
            <NavLink key={item.to} to={item.to} className={({ isActive }) => `rounded-lg px-3 py-2 text-sm font-medium transition ${isActive ? 'bg-blue-600 text-white' : 'text-gray-600 hover:bg-gray-100'}`}>
              <span className="mr-2">{item.icon}</span>
              {item.label}
            </NavLink>
          ))}
          <button onClick={handleLogout} className="rounded-lg bg-red-600 px-3 py-2 text-sm font-medium text-white hover:bg-red-700">
            Logout
          </button>
        </div>
      </div>
      {open && (
        <div className="border-t border-gray-200 bg-gray-50 lg:hidden">
          <div className="space-y-1 px-4 py-4">
            {navItems.map((item) => (
              <NavLink key={item.to} to={item.to} onClick={() => setOpen(false)} className={({ isActive }) => `block rounded-lg px-3 py-2 text-sm font-medium transition ${isActive ? 'bg-blue-600 text-white' : 'text-gray-700 hover:bg-gray-100'}`}>
                <span className="mr-2">{item.icon}</span>
                {item.label}
              </NavLink>
            ))}
            <button onClick={handleLogout} className="w-full rounded-lg bg-red-600 px-3 py-2 text-sm font-medium text-white hover:bg-red-700">
              Logout
            </button>
          </div>
        </div>
      )}
      <div className="bg-gray-50 px-4 py-3 text-sm text-gray-600 md:px-6">
        Signed in as <strong>{user?.username}</strong>
      </div>
    </div>
  );
}
