import { useEffect, useState } from 'react';
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom';
import axios from 'axios';

const navItems = [
  { to: '/dashboard', label: 'Overview', end: true },
  { to: '/dashboard/customers', label: 'Customers' },
  { to: '/dashboard/products', label: 'Products' },
  { to: '/dashboard/sales', label: 'Sales' },
  { to: '/dashboard/reports', label: 'Reports' },
  { to: '/dashboard/profile', label: 'Profile' },
];

function Layout() {
  const [user, setUser] = useState(null);
  const [error, setError] = useState('');
  const navigate = useNavigate();
  const location = useLocation();

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

  useEffect(() => {
    const storedUser = localStorage.getItem('user');
    if (storedUser) setUser(JSON.parse(storedUser));

    axios
      .get('http://localhost:5001/api/auth/me', {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
      })
      .then((res) => {
        setUser(res.data.user);
        localStorage.setItem('user', JSON.stringify(res.data.user));
      })
      .catch((err) => {
        if (!storedUser) setError(err.response?.data?.message || 'Could not load user');
      });
  }, []);

  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    navigate('/login');
  };

  return (
    <div className="min-h-screen bg-surface">
      <aside className="fixed inset-y-0 left-0 w-60 bg-brand-900 text-white flex flex-col border-r border-brand-800">
        <div className="px-5 py-5 border-b border-brand-800">
          <p className="text-[11px] font-semibold uppercase tracking-wider text-brand-500">
            SalesPro SRMS
          </p>
          <h1 className="text-base font-semibold mt-1">Sales Records</h1>
        </div>

        <nav className="flex-1 px-3 py-4 space-y-0.5">
          {navItems.map(({ to, label, end }) => (
            <Link
              key={to}
              to={to}
              className={`block rounded-md px-3 py-2 text-sm transition-colors ${
                isActive(to, end)
                  ? 'bg-brand-800 text-white font-medium'
                  : 'text-slate-300 hover:bg-brand-800/60 hover:text-white'
              }`}
            >
              {label}
            </Link>
          ))}
        </nav>

        <div className="px-4 py-4 border-t border-brand-800">
          {error && <p className="text-xs text-red-300 mb-2">{error}</p>}
          {user && (
            <>
              <p className="text-sm font-medium truncate">{user.name}</p>
              <p className="text-xs text-slate-400 truncate mt-0.5">{user.email}</p>
            </>
          )}
          <button type="button" onClick={handleLogout} className="btn-secondary mt-3 w-full text-slate-200 border-brand-700 hover:bg-brand-800 hover:text-white">
            Log out
          </button>
        </div>
      </aside>

      <div className="ml-60 flex min-h-screen flex-col">
        <header className="bg-white border-b border-slate-200/80 px-6 py-4">
          <p className="text-xs text-slate-500">Welcome back</p>
          <h2 className="text-lg font-semibold text-brand-900">
            {user ? `Hello, ${user.name}` : 'Dashboard'}
          </h2>
        </header>

        <main className="flex-1 p-6 overflow-auto">
          <Outlet />
        </main>
      </div>
    </div>
  );
}

export default Layout;
