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

const navItems = [
  { to: '/dashboard', label: 'Overview', end: true },
  { to: '/dashboard/products', label: 'Products' },
  { to: '/dashboard/warehouse', label: 'Warehouse' },
  { to: '/dashboard/transactions', label: 'Transactions' },
  { to: '/dashboard/reports', label: 'Reports' },
  { to: '/dashboard/profile', label: 'Profile' },
];

function AppLayout({ title, subtitle, children }) {
  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:1000/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');
  };

  const navClass = ({ isActive }) =>
    `block rounded-md px-3 py-2 text-sm font-medium transition-colors ${
      isActive
        ? 'bg-brand-800/80 text-white'
        : 'text-teal-100/80 hover:bg-brand-800/50 hover:text-white'
    }`;

  return (
    <div className="min-h-screen bg-surface">
      <aside className="fixed inset-y-0 left-0 flex w-56 flex-col bg-brand-950 text-teal-50">
        <div className="border-b border-brand-800/60 px-4 py-5">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-teal-300/70">
            Stock SMS
          </p>
          <h1 className="mt-1 text-base font-semibold text-white">Management</h1>
        </div>

        <nav className="flex-1 space-y-0.5 px-2 py-4">
          {navItems.map((item) => (
            <NavLink key={item.to} to={item.to} end={item.end} className={navClass}>
              {item.label}
            </NavLink>
          ))}
        </nav>

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

      <div className="ml-56 flex min-h-screen flex-col">
        <header className="border-b border-slate-200/80 bg-white px-6 py-4">
          {subtitle && <p className="text-xs text-slate-500">{subtitle}</p>}
          <h2 className="text-lg font-semibold text-slate-800">{title}</h2>
        </header>

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

export default AppLayout;
