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

const navItems = [
  { to: '/supplier', label: 'Supplier' },
  { to: '/shipment', label: 'Shipment' },
  { to: '/delivery', label: 'Delivery' },
  { to: '/reports', label: 'Reports' },
];

export default function Sidebar({ open, onClose }) {
  const { user, logout } = useAuth();

  const content = (
    <div className="flex h-full flex-col">
      <div className="border-b border-white/10 px-4 py-4">
        <h1 className="text-sm font-bold text-white">SupplyNet SCMS</h1>
        <p className="text-[10px] text-slate-400">Musanze, Rwanda</p>
      </div>

      <nav className="flex-1 space-y-0.5 p-3">
        {navItems.map((item) => (
          <NavLink
            key={item.to}
            to={item.to}
            onClick={onClose}
            className={({ isActive }) =>
              `block rounded-lg px-3 py-2 text-sm font-medium transition ${
                isActive
                  ? 'bg-primary-600 text-white shadow-md'
                  : 'text-slate-300 hover:bg-sidebar-hover hover:text-white'
              }`
            }
          >
            {item.label}
          </NavLink>
        ))}
      </nav>

      <div className="border-t border-white/10 p-3">
        {user && (
          <p className="mb-2 truncate px-3 text-xs text-slate-400">
            {user.username}
          </p>
        )}
        <button
          type="button"
          onClick={() => { onClose(); logout(); }}
          className="w-full rounded-lg px-3 py-2 text-left text-sm font-medium text-red-300 transition hover:bg-red-500/20 hover:text-red-200"
        >
          Logout
        </button>
      </div>
    </div>
  );

  return (
    <>
      {open && (
        <div className="fixed inset-0 z-40 bg-black/40 lg:hidden" onClick={onClose} />
      )}
      <aside
        className={`fixed inset-y-0 left-0 z-50 w-56 bg-sidebar shadow-sidebar transition-transform lg:translate-x-0 ${
          open ? 'translate-x-0' : '-translate-x-full'
        }`}
      >
        {content}
      </aside>
    </>
  );
}
