import { NavLink, useNavigate } from 'react-router-dom'
import { Shield, LayoutDashboard, AlertTriangle, BrainCircuit, LogOut } from 'lucide-react'

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000'

export default function Navbar() {
  const navigate = useNavigate()
  const username = localStorage.getItem('idps_user') || 'admin'

  async function handleLogout() {
    const token = localStorage.getItem('idps_token')
    try {
      await fetch(`${API_URL}/api/logout`, {
        method: 'POST',
        headers: { Authorization: `Bearer ${token}` }
      })
    } catch {
      // ignore network errors on logout
    }
    localStorage.removeItem('idps_token')
    localStorage.removeItem('idps_user')
    navigate('/login')
  }

  return (
    <nav className="navbar">
      <div className="navbar-brand">
        <Shield size={20} />
        <span>Smart IDPS</span>
      </div>

      <div className="navbar-links">
        <NavLink to="/overview" className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}>
          <LayoutDashboard size={16} /> Overview
        </NavLink>
        <NavLink to="/threats" className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}>
          <AlertTriangle size={16} /> Threats
        </NavLink>
        <NavLink to="/model" className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}>
          <BrainCircuit size={16} /> Model Performance
        </NavLink>
      </div>

      <div className="navbar-user">
        <span className="username">{username}</span>
        <button className="btn-logout" onClick={handleLogout}>
          <LogOut size={15} /> Logout
        </button>
      </div>
    </nav>
  )
}
