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

const navItems = [
  { to: '/dashboard', label: 'Overview', end: true },
  { to: '/dashboard/supplier', label: 'Supplier' },
  { to: '/dashboard/shipment', label: 'Shipment' },
  { to: '/dashboard/delivery', label: 'Delivery' },
  { to: '/dashboard/reports', label: 'Reports' },
  { to: '/dashboard/profile', label: 'Profile' },
];

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

  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((response) => {
        setUser(response.data.user);
        localStorage.setItem('user', JSON.stringify(response.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-brand-50">
      <aside className="fixed inset-y-0 left-0 w-60 bg-brand-950 text-slate-100 flex flex-col border-r border-brand-800">
        <div className="px-5 py-5 border-b border-brand-800">
          <p className="text-xs font-semibold uppercase tracking-wider text-brand-400">SCMS</p>
          <h1 className="text-base font-semibold text-white mt-0.5">Supply Chain</h1>
        </div>

        <nav className="flex-1 px-3 py-4 space-y-0.5">
          {navItems.map(({ to, label, end }) => (
            <NavLink
              key={to}
              to={to}
              end={end}
              className={({ isActive }) =>
                isActive ? `nav-link ${'nav-link-active'}` : 'nav-link'
              }
            >
              {label}
            </NavLink>
          ))}
        </nav>

        <div className="px-4 py-4 border-t border-brand-800">
          {error && <p className="text-xs text-red-400 mb-2">{error}</p>}
          {user && (
            <>
              <p className="text-sm font-medium text-white truncate">{user.name}</p>
              <p className="text-xs text-slate-400 truncate mt-0.5">{user.email}</p>
            </>
          )}
          <button
            type="button"
            onClick={handleLogout}
            className="mt-3 w-full text-sm font-medium text-slate-300 hover:text-white border border-brand-700 rounded-lg px-3 py-2 hover:bg-brand-800 transition-colors"
          >
            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-muted">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 DashboardLayout;
