import { Outlet, NavLink, useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import './Layout.css';

const Layout = () => {
  const { user, logout } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();

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

  const navItems = [
    { path: '/', label: 'Dashboard' },
    { path: '/products', label: 'Products' },
    { path: '/customers', label: 'Customers' },
    { path: '/sales', label: 'Sales' },
    { path: '/reports', label: 'Reports' },
  ];

  const pageTitles = {
    '/': 'Dashboard',
    '/products': 'Products',
    '/customers': 'Customers',
    '/sales': 'Sales',
    '/reports': 'Reports',
  };

  const currentTitle = pageTitles[location.pathname] || 'SmartShop';

  return (
    <div className="layout">
      <aside className="sidebar">
        <div className="sidebar-brand">
          <div className="brand-mark">S</div>
          <div>
            <h2>SmartShop</h2>
            <p>Ltd · Electronics</p>
          </div>
        </div>

        <div className="nav-section-label">Main Menu</div>
        <nav className="sidebar-nav">
          {navItems.map(({ path, label }) => (
            <NavLink
              key={path}
              to={path}
              end={path === '/'}
              className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}
            >
              <span className="nav-label">{label}</span>
              <span className="nav-indicator" />
            </NavLink>
          ))}
        </nav>

        <div className="sidebar-footer">
          <div className="user-card">
            <div className="user-avatar">{user?.username?.charAt(0).toUpperCase()}</div>
            <div className="user-details">
              <span className="user-name">{user?.username}</span>
              <span className="user-role">Administrator</span>
            </div>
          </div>
          <button className="logout-btn" onClick={handleLogout} type="button">
            Sign out
          </button>
        </div>
      </aside>

      <div className="layout-main">
        <header className="top-bar">
          <div className="top-bar-title">{currentTitle}</div>
          <div className="top-bar-date">
            {new Date().toLocaleDateString('en-US', {
              weekday: 'long',
              year: 'numeric',
              month: 'long',
              day: 'numeric',
            })}
          </div>
        </header>
        <main className="main-content">
          <Outlet />
        </main>
      </div>
    </div>
  );
};

export default Layout;
