import { Link, useLocation, useNavigate } from 'react-router-dom'
import { authAPI } from '../services/api'

const navLinks = [
  { to: '/', label: 'Dashboard' },
  { to: '/employees', label: 'Employees' },
  { to: '/departments', label: 'Departments' },
  { to: '/positions', label: 'Positions' },
  { to: '/users', label: 'Users' },
  { to: '/status-report', label: 'Report' },
]

function Sidebar({ user, onLogout }) {
  const location = useLocation()
  const navigate = useNavigate()

  const isActive = (path) => {
    if (path === '/') return location.pathname === '/'
    return location.pathname.startsWith(path)
  }

  const handleLogout = async () => {
    try {
      await authAPI.logout()
      onLogout()
      navigate('/login')
    } catch (error) {
      console.error('Logout failed:', error)
    }
  }

  const linkClass = (path) =>
    `block px-4 py-2 rounded text-sm ${isActive(path) ? 'bg-teal-600 text-white' : 'text-slate-300 hover:bg-slate-700 hover:text-white'}`

  return (
    <aside className="fixed inset-y-0 left-0 w-56 bg-slate-900 flex flex-col z-30">
      <div className="px-4 py-4 border-b border-slate-700">
        <Link to="/" className="text-lg font-bold text-white tracking-tight">HRMS</Link>
      </div>

      <nav className="flex-1 p-3 space-y-1 overflow-y-auto">
        {navLinks
          .filter(link => {
            // regular users should not see Users and Report
            if (user?.role !== 'admin' && (link.to === '/users' || link.to === '/status-report')) return false
            return true
          })
          .map(link => (
            <Link key={link.to} to={link.to} className={linkClass(link.to)}>
              {link.label}
            </Link>
          ))}
      </nav>

      <div className="p-3 border-t border-slate-700 flex items-center justify-between">
        <span className="text-sm text-slate-400 truncate max-w-[100px]">{user?.UserName}</span>
        <button onClick={handleLogout} className="text-sm text-slate-500 hover:text-red-400">
          Logout
        </button>
      </div>
    </aside>
  )
}

export default Sidebar
