import React, { useEffect } from 'react';
import { Outlet, useLocation, Navigate } from 'react-router-dom';
import AdminSidebar from './AdminSidebar';
import { useAuth } from '../../contexts/AuthContext';
import { canManageSystem } from '../../utils/permissions';

const AdminLayout = () => {
  const { user, isInitialized } = useAuth();
  const location = useLocation();

  useEffect(() => {
    console.log('AdminLayout - Location changed:', location.pathname);
  }, [location]);

  console.log('AdminLayout - Current location:', location.pathname);
  console.log('AdminLayout - User:', user);

  if (!isInitialized) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-campfire-dark">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-campfire-amber"></div>
      </div>
    );
  }

  if (!canManageSystem(user)) {
    console.log('AdminLayout - User does not have system management rights, redirecting to home');
    return <Navigate to="/" replace />;
  }

  console.log('AdminLayout - Rendering layout with Outlet');
  return (
    <div className="min-h-screen bg-campfire-dark pt-16">
      <div className="flex">
        <AdminSidebar />
        <main className="flex-1 p-8">
          <div className="bg-campfire-darker rounded-lg p-6 shadow-lg">
            <Outlet />
        </div>
        </main>
      </div>
    </div>
  );
};

export default AdminLayout;
