
import Link from 'next/link'
import Footer from "./footer"
import Sidebar from "./sidebar"
import type { ReactNode } from "react"
import { useRouter } from 'next/router'
import { useEffect, useState } from "react";
import Body from 'next/document'

import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { set } from "date-fns"
import ErrorBoundary from "./ErrorBoundary";

export default function Layout({ children }) {
  const router = useRouter();

  // Assuming that during SSR, we don't want the sidebar to be open.
  const [isSmallScreen, setIsSmallScreen] = useState(true);
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);

  useEffect(() => {
    // This function determines if we're on a small screen
    const checkIfSmallScreen = () => window.innerWidth < 768;

    // Set the initial screen size and sidebar state
    const initialSmallScreenCheck = checkIfSmallScreen();
    setIsSmallScreen(initialSmallScreenCheck);
    setIsSidebarOpen(!initialSmallScreenCheck);

    const handleResize = () => {
      const smallScreenCheck = checkIfSmallScreen();
      setIsSmallScreen(smallScreenCheck);

      // On small screens, we want to ensure the sidebar is not open by default when resizing
      if (smallScreenCheck) {
        setIsSidebarOpen(false);
      }
    };

    // Add event listener
    window.addEventListener('resize', handleResize);

    // Cleanup event listener on component unmount
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // Toggle the sidebar only when the button is clicked
  const toggleSidebar = () => {
    setIsSidebarOpen(!isSidebarOpen);
  };

  // We use `isSmallScreen` to determine the margin-left on small screens
  // and use `isSidebarOpen` to determine if we need to push the content on large screens.
  const marginLeftClass = isSmallScreen ? 'ml-0' : isSidebarOpen ? 'ml-60' : 'ml-6';

  return (
    <div className="">
      <div className="flex flex-col ">
        <div className="flex flex-row min-h-screen w-screen pr-8">
          <ToastContainer position="top-center" style={{ zIndex: 9999 }} />
          <Sidebar isSidebarOpen={isSidebarOpen} toggleSidebar={toggleSidebar} />
          <main className={`flex-1 transition-all duration-300 ${marginLeftClass}`}>
            <div className="">
              <ErrorBoundary>
                {children}
              </ErrorBoundary>
            </div>
            <div id="modal-root"></div>  {/* Modal container */}
          </main>
        </div>
      </div>
    </div>
  );
}

