import { useQuery, useSuspenseQuery } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
import { LaptopMinimal } from "lucide-react";
import {
	Sidebar,
	SidebarContent,
	SidebarFooter,
	SidebarMenu,
	SidebarMenuButton,
	SidebarMenuItem,
	useSidebar,
} from "@/components/ui/sidebar";
import { useSession } from "@/lib/auth-client";
import { getSettings } from "../../lib/queries/getSettings";
import { permissionQuery } from "../../lib/queries/permsCheck";
import AdminSidebar from "./AdminBar";
import DocBar from "./DocBar";
import MobileBar from "./MobileBar";
import TransportationBar from "./TransportationBar";
import WarehouseBar from "./Warhouse";

export function AppSidebar() {
	const { data: session } = useSession();
	const { data: settings, isLoading } = useSuspenseQuery(getSettings());
	const { data: canReadOpenDock = false } = useQuery(
		permissionQuery({
			openDock: ["read"],
		}),
	);
	const { setOpen } = useSidebar();

	// const { data: canReadWarehouse = false } = useQuery(
	// 	permissionQuery({
	// 		warehouse: ["read"],
	// 	}),
	// );

	return (
		<Sidebar
			variant="sidebar"
			collapsible="offcanvas"
			className="top-(--header-height) h-[calc(100svh-var(--header-height))]!"
		>
			<SidebarContent>
				<SidebarMenu>
					<SidebarMenuItem>
						<SidebarContent>
							<DocBar />
							{!isLoading &&
								settings.filter((n: any) => n.name === "mobile")[0].active && (
									<MobileBar />
								)}

							{!isLoading &&
								settings.filter((n: any) => n.name === "opendock_sync")[0]
									?.active &&
								canReadOpenDock && <TransportationBar />}

							{!isLoading &&
								settings.filter((n: any) => n.name === "dockDoorScanning")[0]
									?.active && <WarehouseBar />}

							{session &&
								(session.user.role === "admin" ||
									session.user.role === "systemAdmin" ||
									session.user.role === "manager") && (
									<AdminSidebar session={session} />
								)}
						</SidebarContent>
					</SidebarMenuItem>
				</SidebarMenu>
			</SidebarContent>
			{session &&
				(session.user.role === "admin" ||
					session.user.role === "systemAdmin" ||
					session.user.role === "manager") && (
					<SidebarFooter>
						<SidebarMenu>
							<SidebarMenuItem>
								<SidebarMenuButton asChild>
									<Link to={"/apidocs"} onClick={() => setOpen(false)}>
										<LaptopMinimal />
										<span>Api docs</span>
									</Link>
								</SidebarMenuButton>
							</SidebarMenuItem>
						</SidebarMenu>
					</SidebarFooter>
				)}
		</Sidebar>
	);
}
