import React, { useState } from "react";
import { useLocation } from "react-router-dom";
import AdminNavbar from "components/Navbars/AdminNavbar.js";
import AdminFooter from "components/Footers/AdminFooter.js";
import Sidebar from "components/Sidebar/Sidebar.js";
import { useSystemParameters } from "../context/SystemParameterContext";
import { Outlet } from "react-router-dom"; // Import Outlet for nested routing
import routes from "routes.js";

const Admin = (props) => {
  const mainContent = React.useRef(null);
  const location = useLocation();
  // Add state for sidebar collapse
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);

  // Scroll to top on location change
  React.useEffect(() => {
    document.documentElement.scrollTop = 0;
    document.scrollingElement.scrollTop = 0;
    mainContent.current.scrollTop = 0;
  }, [location]);

  // Get the current page's brand text
  const getBrandText = (path) => {
    for (let i = 0; i < routes.length; i++) {
      if (
        path.indexOf(routes[i].layout + routes[i].path) !== -1
      ) {
        return routes[i].name;
      }
    }
    return "Brand";
  };

  // Handle sidebar toggle
  const handleSidebarToggle = (collapsed) => {
    setSidebarCollapsed(collapsed);
  };

  // Check if the current page is an admin page
  const isAdminPage = location.pathname.startsWith("/admin");
  const { systemParameters, loading, error } = useSystemParameters();
  return (
    <>
    {/* Render Navbar only on admin pages */}
    {isAdminPage && (
          <div className="navbar-container">
            <AdminNavbar
              {...props}
              brandText={systemParameters ? systemParameters.company_Display_Name : "Loading..."}
            />
          </div>
        )}
      {/* Render Sidebar only on admin pages */}
      {isAdminPage && (
        <Sidebar
          {...props}
          routes={routes}
          onSidebarToggle={handleSidebarToggle}
          logo={{
            innerLink: "/admin/index",
            imgSrc: require("../assets/img/brand/argon-react.png"),
            imgAlt: "Logo",
          }}
        />
      )}
      <div 
        className={`main-content ${sidebarCollapsed ? 'sidebar-collapsed-main' : ''}`} 
        ref={mainContent}
      >
        
        {/* This is where the nested routes will render */}
        <div className="px-0" style={{ marginTop: "100px" }}>
          <Outlet />
        </div>

        {/* Render Footer only on admin pages */}
        {/* {isAdminPage && <AdminFooter />} */}
      </div>
    </>
  );
};

export default Admin;