import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Link, Outlet, useNavigate } from "@tanstack/react-router";
import { useAuth } from "@/auth/store";
import InlineError from "@/lib/InlineError";
import { versionQuery } from "@/lib/queries";
import PauseWidget from "../features/pause/PauseWidget";
import ReadOnlyConfigBanner from "../features/settings/ReadOnlyConfigBanner";
import RestartBanner from "../features/settings/RestartBanner";
import { buttonClass, focusRing } from "@/ui/classes";

const NAV_ITEMS = [
	{ to: "/", label: "Dashboard" },
	{ to: "/queries", label: "Query Log" },
	{ to: "/live", label: "Live" },
	{ to: "/clients", label: "Clients" },
	{ to: "/groups", label: "Groups" },
	{ to: "/blocklists", label: "Blocklists" },
	{ to: "/rules", label: "Rules" },
	{ to: "/local-dns", label: "Local DNS" },
	{ to: "/upstreams", label: "Upstreams" },
	{ to: "/lookup", label: "Lookup" },
	{ to: "/settings", label: "Settings" },
] as const;

function NavLinks({ onNavigate }: { onNavigate?: () => void }) {
	return (
		<ul className="space-y-1">
			{NAV_ITEMS.map((item) => (
				<li key={item.to}>
					<Link
						to={item.to}
						onClick={onNavigate}
						activeOptions={{ exact: item.to === "/" }}
						activeProps={{
							"aria-current": "page",
							className: "bg-zinc-200 font-medium text-zinc-900 dark:bg-zinc-800 dark:text-zinc-50",
						}}
						inactiveProps={{
							className:
								"text-zinc-600 hover:bg-zinc-100 hover:text-zinc-900 dark:text-zinc-400 dark:hover:bg-zinc-900 dark:hover:text-zinc-100",
						}}
						className={`block rounded px-3 py-1.5 ${focusRing}`}
					>
						{item.label}
					</Link>
				</li>
			))}
		</ul>
	);
}

function VersionFooter() {
	const { data } = useQuery(versionQuery());
	return (
		<footer className="px-4 py-3 text-xs text-zinc-500">
			{data === undefined ? "nxdns" : `nxdns v${data.version} (${data.git_commit.slice(0, 7)})`}
		</footer>
	);
}

function LogoutButton() {
	const { authRequired, logout } = useAuth();
	const navigate = useNavigate();
	const [error, setError] = useState<unknown>(null);
	if (authRequired !== true) return null;
	return (
		<div className="flex items-center gap-2">
			<button
				type="button"
				onClick={() => {
					setError(null);
					void logout().then(
						() => navigate({ to: "/login" }),
						(logoutError: unknown) => setError(logoutError),
					);
				}}
				className={buttonClass}
			>
				Log out
			</button>
			{error !== null && <InlineError error={error} />}
		</div>
	);
}

export default function AppShell() {
	const [drawerOpen, setDrawerOpen] = useState(false);
	return (
		<div className="min-h-dvh bg-zinc-50 text-zinc-900 md:grid md:grid-cols-[14rem_1fr] dark:bg-zinc-950 dark:text-zinc-100">
			<aside className="hidden border-r border-zinc-200 md:flex md:flex-col dark:border-zinc-800">
				<div className="px-4 py-4 text-lg font-semibold">nxdns</div>
				<nav aria-label="Main" className="flex-1 px-2">
					<NavLinks />
				</nav>
				<VersionFooter />
			</aside>
			<div className="flex min-h-dvh flex-col">
				<header className="flex items-center gap-3 border-b border-zinc-200 px-4 py-2 dark:border-zinc-800">
					<button
						type="button"
						className={`${buttonClass} md:hidden`}
						aria-expanded={drawerOpen}
						aria-controls="mobile-nav"
						onClick={() => setDrawerOpen((open) => !open)}
					>
						Menu
					</button>
					<span className="text-lg font-semibold md:hidden">nxdns</span>
					<div className="ml-auto flex items-center gap-3">
						<PauseWidget />
						<LogoutButton />
					</div>
				</header>
				<RestartBanner />
				<ReadOnlyConfigBanner />
				{drawerOpen && (
					<div id="mobile-nav" className="border-b border-zinc-200 md:hidden dark:border-zinc-800">
						<nav aria-label="Main" className="px-2 py-2">
							<NavLinks onNavigate={() => setDrawerOpen(false)} />
						</nav>
						<VersionFooter />
					</div>
				)}
				<main className="flex-1 p-4">
					<Outlet />
				</main>
			</div>
		</div>
	);
}
