import { useQuery } from "@tanstack/react-query";
import client from "../honoClient";
import MenuItem from "./NavbarMenuItem";
import { useState, useEffect } from "react";
import { useLocation } from "@tanstack/react-router";
import { ScrollArea } from "@/shadcn/components/ui/scroll-area";
import AppHeader from "./AppHeader";

// import MenuItem from "./SidebarMenuItem";
// import { useAuth } from "@/modules/auth/contexts/AuthContext";

/**
 * `AppNavbar` is a React functional component that renders the application's navigation bar.
 * It utilizes data from `allMenu` to create a list of menu items displayed in a scrollable area.
 *
 * @returns A React element representing the application's navigation bar.
 */
export default function AppNavbar(){
	// const {user} = useAuth();

	const { pathname } = useLocation();

	const [isSidebarOpen, setSidebarOpen] = useState(true);
	const toggleSidebar = () => {
		setSidebarOpen(!isSidebarOpen);
	};

	const { data } = useQuery({
		queryKey: ["sidebarData"],
		queryFn: async () => {
		  const res = await client.dashboard.getSidebarItems.$get();
		  if (res.ok) {
			const data = await res.json();
			return data;
		  }
		  console.error("Error:", res.status, res.statusText);
		  throw new Error("Error fetching sidebar data");
		},
	});

	useEffect(() => {
		const handleResize = () => {
		  if (window.innerWidth < 768) { // Ganti 768 dengan breakpoint mobile Anda
			setSidebarOpen(false);
		  } else {
			setSidebarOpen(true);
		  }
		};
	
		window.addEventListener('resize', handleResize);
		handleResize(); // Initial check
	
		return () => window.removeEventListener('resize', handleResize);
	  }, []);
	
	const handleMenuItemClick = () => {
		if (window.innerWidth < 768) {
		  setSidebarOpen(false);
		}
	  };

	return (
		<>
		<div>
			{/* Header */}
			<AppHeader toggle={toggleSidebar} openNavbar={isSidebarOpen} />

			{/* Sidebar */}
			<div
			className={`fixed lg:relative w-64 bg-white top-[60px] left-0 h-full z-40 px-3 py-4 transition-transform border
				${isSidebarOpen ? 'translate-x-0' : '-translate-x-full'}`}
			>
				<ScrollArea className="flex flex-1 h-full">
					{data?.map((menu, i) => (
					<MenuItem
					key={i}
					menu={menu}
					isActive={pathname === menu.link}
					onClick={handleMenuItemClick}
				/>
					))}
				</ScrollArea>
			</div>

			{/* Overlay to close sidebar on mobile */}
			{isSidebarOpen && (
				<div
					className="fixed inset-0 bg-black bg-opacity-50 z-30 hidden lg:visible"
					onClick={toggleSidebar}
				/>
			)}
		</div>
		</>
	);
}
