import { Link, useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';

export default function Layout({ children }) {
  const { user, logout } = useAuth();
  const location = useLocation();
  const navigate = useNavigate();

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

  const navItems = [
    { path: '/dashboard', label: 'Dashboard', roles: ['receptionist', 'doctor'] },
    { path: '/patients', label: 'Patients', roles: ['receptionist'] },
    { path: '/appointments', label: 'Appointments', roles: ['receptionist', 'doctor'] },
    { path: '/medical-reports', label: 'Medical Reports', roles: ['doctor'] },
    { path: '/reports', label: 'Reports', roles: ['receptionist', 'doctor'] },
  ];

  const visibleNav = navItems.filter((item) => item.roles.includes(user?.role));

  return (
    <div className="app-layout">
      <aside className="sidebar">
        <div className="sidebar-brand">
          <span className="brand-icon">+</span>
          <div>
            <h1>KFH Rwanda</h1>
            <p>Hospital Management</p>
          </div>
        </div>
        <nav className="sidebar-nav">
          {visibleNav.map((item) => (
            <Link
              key={item.path}
              to={item.path}
              className={location.pathname === item.path ? 'active' : ''}
            >
              {item.label}
            </Link>
          ))}
        </nav>
        <div className="sidebar-footer">
          <div className="user-info">
            <strong>{user?.full_name}</strong>
            <span className={`role-badge role-${user?.role}`}>{user?.role}</span>
          </div>
          <button type="button" className="btn btn-outline btn-sm" onClick={handleLogout}>
            Logout
          </button>
        </div>
      </aside>
      <main className="main-content">{children}</main>
    </div>
  );
}
