import { useQuery } from "@tanstack/react-query";
import { Link, useRouter, useRouterState } from "@tanstack/react-router";
import {
	ArrowLeft,
	Film,
	Folder,
	FolderTree,
	Home,
	Image,
	LayoutDashboard,
	Menu,
	Search,
	ShieldCheck,
	Tv,
} from "lucide-react";
import type { PropsWithChildren } from "react";
import { memo, useCallback, useState } from "react";

import logoSrc from "@/assets/logo.png";
import { Button } from "@/components/ui/button";
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
import { useTRPC } from "@/utils/trpc";
import { ThemeModeSwitcher } from "./ThemeModeSwitcher";
import UserMenu from "./UserMenu";

type NavigationSheetContentProps = {
	onNavigate?: () => void;
};

const NavigationSheetContent = memo(function NavigationSheetContent({
	onNavigate,
}: NavigationSheetContentProps) {
	const trpc = useTRPC();
	const { data: libraries, isLoading } = useQuery(
		trpc.library.getAll.queryOptions(),
	);

	return (
		<div className="flex h-full flex-col bg-background">
			<div className="flex items-center gap-2 border-border border-b px-4 py-3">
				<img
					src={logoSrc}
					alt="Nontara logo"
					className="h-10 w-auto select-none"
					loading="eager"
					fetchPriority="high"
					decoding="async"
					draggable={false}
				/>
			</div>
			<nav className="flex-1 overflow-y-auto px-2 py-4">
				<div className="space-y-6">
					<section>
						<ul className="grid gap-1">
							<li>
								<Button
									asChild
									variant="ghost"
									className="w-full justify-start gap-2 px-3 py-2 font-medium text-sm"
								>
									<Link to="/home" onClick={onNavigate}>
										<Home className="size-4" aria-hidden="true" />
										<span>Home</span>
									</Link>
								</Button>
							</li>
						</ul>
					</section>

					<section>
						<div className="flex items-center gap-2 px-3 pb-1 font-semibold text-muted-foreground text-xs uppercase tracking-wide">
							<FolderTree className="size-4" aria-hidden="true" />
							<span>Media</span>
						</div>
						<div className="space-y-1.5">
							<div className="flex items-center gap-2 rounded-md px-3 py-2 font-medium text-sm">
								<Image className="size-4" aria-hidden="true" />
								<span>Media Library</span>
							</div>
							{isLoading ? (
								<div className="ml-6 border-border border-l pl-3">
									<div className="px-2 py-1.5 text-muted-foreground text-sm">
										Loading...
									</div>
								</div>
							) : libraries && libraries.length > 0 ? (
								<ul className="ml-6 space-y-0.5 border-border border-l pl-3">
									{libraries.map((library) => {
										const LibraryIcon =
											library.type === "MOVIE"
												? Film
												: library.type === "SERIES"
													? Tv
													: Folder;
										return (
											<li key={library.id}>
												<Button
													asChild
													variant="ghost"
													className="flex w-full justify-start gap-2 rounded-md px-2 py-1.5 text-muted-foreground text-sm transition-colors hover:bg-muted hover:text-foreground"
												>
													<Link
														to="/home/library/$id"
														params={{ id: library.id.toString() }}
														onClick={onNavigate}
													>
														<LibraryIcon
															className="size-4"
															aria-hidden="true"
														/>
														<span>{library.name}</span>
													</Link>
												</Button>
											</li>
										);
									})}
								</ul>
							) : (
								<div className="ml-6 border-border border-l pl-3">
									<div className="px-2 py-1.5 text-muted-foreground text-sm">
										No libraries found
									</div>
								</div>
							)}
						</div>
					</section>

					<section>
						<div className="flex items-center gap-2 px-3 pb-1 font-semibold text-muted-foreground text-xs uppercase tracking-wide">
							<ShieldCheck className="size-4" aria-hidden="true" />
							<span>Administration</span>
						</div>
						<ul className="grid gap-1">
							<li>
								<Button
									asChild
									variant="ghost"
									className="w-full justify-start gap-2 px-3 py-2 font-medium text-sm"
								>
									<Link to="/dashboard">
										<LayoutDashboard className="size-4" aria-hidden="true" />
										<span>Dashboard</span>
									</Link>
								</Button>
							</li>
						</ul>
					</section>
				</div>
			</nav>
		</div>
	);
});

NavigationSheetContent.displayName = "NavigationSheetContent";

function HeaderBar() {
	const [open, setOpen] = useState(false);
	const handleNavigate = useCallback(() => setOpen(false), []);
	const router = useRouter();
	const routerState = useRouterState();
	const pathname = routerState.location.pathname;

	return (
		<header className="sticky top-0 z-50 flex items-center justify-between border-border border-b bg-muted/95 px-5 py-3 shadow-sm backdrop-blur supports-[backdrop-filter]:bg-muted/80">
			<div className="flex items-center gap-3">
				{pathname !== "/home" && (
					<>
						<Button
							type="button"
							variant="ghost"
							size="icon"
							aria-label="Go back"
							onClick={() => router.history.back()}
						>
							<ArrowLeft className="size-5" aria-hidden="true" />
						</Button>
						<Button
							type="button"
							variant="ghost"
							size="icon"
							aria-label="Go to home"
							asChild
						>
							<Link to="/home">
								<Home className="size-5" aria-hidden="true" />
							</Link>
						</Button>
					</>
				)}
				<Sheet open={open} onOpenChange={setOpen}>
					<SheetTrigger asChild>
						<Button
							type="button"
							variant="ghost"
							size="lg"
							className="px-3"
							aria-label="Open navigation menu"
						>
							<Menu className="size-5" aria-hidden="true" />
						</Button>
					</SheetTrigger>
					<SheetContent side="left" className="w-[18rem] p-0 sm:w-[20rem]">
						<NavigationSheetContent onNavigate={handleNavigate} />
					</SheetContent>
				</Sheet>
				{pathname === "/home" && (
					<Link to="/home" className="flex items-center">
						<img
							src={logoSrc}
							alt="Nontara logo"
							className="h-9 w-auto select-none"
							loading="eager"
							fetchPriority="high"
							decoding="async"
							draggable={false}
						/>
					</Link>
				)}
			</div>
			<div className="flex items-center gap-2">
				<Button
					type="button"
					variant="ghost"
					size="icon"
					aria-label="Search"
					asChild
				>
					<Link to="/home/search">
						<Search className="size-5" aria-hidden="true" />
					</Link>
				</Button>
				<ThemeModeSwitcher />
				<UserMenu />
			</div>
		</header>
	);
}

const Header = memo(function Header({ children }: PropsWithChildren) {
	return (
		<div className="flex min-h-svh w-full flex-1 flex-col bg-background">
			<HeaderBar />
			{children}
		</div>
	);
});

Header.displayName = "Header";

export default Header;
