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

const navItems = [
  { to: '/dashboard', end: true, label: 'Overview' },
  { to: '/dashboard/employee', label: 'Employees' },
  { to: '/dashboard/department', label: 'Departments' },
  { to: '/dashboard/salary', label: 'Salary' },
  { 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-gray-100">
      <aside className="fixed inset-y-0 left-0 flex w-56 flex-col bg-teal-900 text-white">
        <div className="border-b border-teal-800 px-4 py-4">
          <h1 className="text-lg font-bold">EPMS</h1>
          <p className="text-sm text-teal-200">Payroll System</p>
        </div>

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

        <div className="border-t border-teal-800 px-4 py-4">
          {error && <p className="mb-2 text-xs text-red-300">{error}</p>}
          {user && <p className="text-sm">{user.name}</p>}
          {user && <p className="text-xs text-teal-200">{user.email}</p>}
          <button type="button" onClick={handleLogout} className="mt-3 w-full btn-secondary text-sm">
            Log out
          </button>
        </div>
      </aside>

      <div className="ml-56 min-h-screen">
        <header className="border-b border-gray-300 bg-white px-6 py-4">
          <h2 className="text-lg font-semibold">
            {user ? `Hello, ${user.name}` : 'Dashboard'}
          </h2>
        </header>

        <main className="p-6">
          <Outlet />
        </main>
      </div>
    </div>
  );
}

export default DashboardLayout;
