import { useEffect, useState } from 'react';
import { Link, Outlet, useNavigate } from 'react-router-dom';
import { api, getStoredUser } from '../api';

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

  useEffect(() => {
    const loadUser = async () => {
      try {
        const response = await api.get('/auth/me');
        setUser(response.data.user);
        localStorage.setItem('user', JSON.stringify(response.data.user));
      } catch (err) {
        if (!getStoredUser()) {
          setError(err.response?.data?.message || 'Could not load user');
        }
      }
    };
    loadUser();
  }, []);

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

  const isReceptionist = user?.role === 'receptionist';
  const isDoctor = user?.role === 'doctor';

  const linkClass =
    'block rounded-lg px-3 py-2.5 text-sm font-medium text-slate-300 hover:bg-slate-800 hover:text-white transition-colors';

  return (
    <div className="min-h-screen bg-slate-100">
      <aside className="fixed inset-y-0 left-0 w-64 bg-slate-900 text-slate-100 flex flex-col">
        <div className="px-5 py-6 border-b border-slate-700">
          <p className="text-xs font-semibold uppercase tracking-wider text-teal-400">
            King Faisal Hospital
          </p>
          <h1 className="text-lg font-bold text-white mt-1">Rwanda</h1>
        </div>

        <nav className="flex-1 px-3 py-4 space-y-1">
          <Link to="/dashboard" className={linkClass}>
            Dashboard
          </Link>
          {isReceptionist && (
            <>
              <Link to="/dashboard/patients" className={linkClass}>
                Patients
              </Link>
              <Link to="/dashboard/appointments" className={linkClass}>
                Appointments
              </Link>
            </>
          )}
          {isDoctor && (
            <>
              <Link to="/dashboard/appointments" className={linkClass}>
                My appointments
              </Link>
              <Link to="/dashboard/medical-reports" className={linkClass}>
                Medical reports
              </Link>
            </>
          )}
          <Link to="/dashboard/report" className={linkClass}>
            Reports
          </Link>
          <Link to="/dashboard/profile" className={linkClass}>
            Profile
          </Link>
        </nav>

        <div className="px-4 py-4 border-t border-slate-700">
          {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-teal-400 capitalize mt-0.5">{user.role}</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-slate-600 rounded-lg px-3 py-2 hover:bg-slate-800 transition-colors"
          >
            Log out
          </button>
        </div>
      </aside>

      <div className="ml-64 flex min-h-screen flex-col">
        <header className="bg-white border-b border-slate-200 px-6 py-4">
          <p className="text-sm text-slate-500">Hospital management system</p>
          <h2 className="text-xl font-semibold text-slate-800">
            {user ? `Welcome, ${user.name}` : 'Dashboard'}
          </h2>
        </header>

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

export default DashboardLayout;
