import { useState, useEffect, type ReactNode } from "react";
import { Sidebar } from "@/app/providers/layout/sidebar/sidebar";
import {
  Navigation,
  BottomNav,
} from "@/app/providers/layout/navigation/navigation";
import { useAgentStore } from "@/app/providers/layout/store/agent.store";

export const Layout = ({ children }: { children: ReactNode }) => {
  const [mobileOpen, setMobileOpen] = useState(false);
  const [isMobile, setIsMobile] = useState(() =>
    typeof window !== "undefined" ? window.innerWidth < 856 : false,
  );
  const [isVerySmall, setIsVerySmall] = useState(() =>
    typeof window !== "undefined" ? window.innerWidth < 600 : false,
  );
  const { fetchAgents } = useAgentStore();

  const sidebarOpen = isMobile ? mobileOpen : true;

  useEffect(() => {
    const handleResize = () => {
      const mobile = window.innerWidth < 856;
      setIsMobile(mobile);
      if (!mobile) {
        setMobileOpen(false);
      }
      setIsVerySmall(window.innerWidth < 600);
    };

    window.addEventListener("resize", handleResize);
    handleResize();
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  const toggleSidebar = () => {
    if (isMobile) {
      setMobileOpen((prev) => !prev);
    }
  };

  useEffect(() => {
    fetchAgents();
  }, [fetchAgents]);

  useEffect(() => {
    const interval = setInterval(() => {
      fetchAgents();
    }, 30000);

    return () => clearInterval(interval);
  }, [fetchAgents]);

  return (
    <div
      className="flex h-screen overflow-hidden"
      style={{ backgroundColor: "var(--bg-primary)" }}
    >
      <Sidebar
        isOpen={sidebarOpen}
        onToggle={toggleSidebar}
        isMobile={isMobile}
      />
      <div className="flex-1 flex flex-col min-w-0 overflow-hidden">
        <Navigation
          onToggleSidebar={toggleSidebar}
          isMobile={isMobile}
          isVerySmall={isVerySmall}
        />
        <div className="flex-1 overflow-auto p-4">{children}</div>
        {isVerySmall && <BottomNav />}
      </div>
    </div>
  );
};
