"use client";

import React from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import {
	FolderOpen,
	Search as SearchIcon,
	TriangleAlert,
	CornerDownLeft,
} from "lucide-react";

import { useAuth } from "@/components/auth/authContext";
import { getBranches } from "@/lib/frontend/apiClient";
import { branchPath, searchPath } from "@/lib/frontend/routes";
import { isValidBranchParam } from "@/lib/frontend/params";
import {
	buildNextUrlForBranchSwitch,
	readRouteBranchFromPathname,
	safeReadLocalStorageBranch,
	safeWriteLocalStorageBranch,
} from "@/lib/frontend/quickNav/branchSwitch";
import {
	getPrimaryNavFromPathname,
	PRIMARY_NAV,
} from "@/lib/frontend/nav/activeRoute";
import { isAdminLike as isAdminLikeRole } from "@/lib/frontend/auth/roles";

import { Button } from "@/components/ui/button";
import {
	DropdownMenu,
	DropdownMenuContent,
	DropdownMenuItem,
	DropdownMenuLabel,
	DropdownMenuRadioGroup,
	DropdownMenuRadioItem,
	DropdownMenuSeparator,
	DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
	Tooltip,
	TooltipContent,
	TooltipTrigger,
} from "@/components/ui/tooltip";

const STORAGE_KEY_LAST_BRANCH = "rhl_last_branch";

const BRANCH_LIST_STATE = Object.freeze({
	IDLE: "idle",
	LOADING: "loading",
	READY: "ready",
	ERROR: "error",
});

// Header polish:
// - remove subtle outline shadow (crisp header UI)
// - normalize padding when an icon is present
const TOPNAV_BUTTON_CLASS = "shadow-none has-[>svg]:px-3";

// Active nav style (blue like multi-branch selection)
const ACTIVE_NAV_BUTTON_CLASS =
	"border-blue-600 bg-blue-50 text-blue-900 hover:bg-blue-50 " +
	"dark:border-blue-900 dark:bg-blue-950 dark:text-blue-50 dark:hover:bg-blue-950";

export default function QuickNav() {
	const router = useRouter();
	const pathname = usePathname() || "/";

	const { status, user, retry } = useAuth();

	const isAuthenticated = status === "authenticated" && user;
	const isAdminLike = isAuthenticated && isAdminLikeRole(user.role);
	const isBranchUser = isAuthenticated && user.role === "branch";
	const canRevalidate = typeof retry === "function";

	// Persisted selection for admin-like users:
	const [selectedBranch, setSelectedBranch] = React.useState(null);

	// Init gate: prevent “localStorage sync” from running on every state change
	const initRef = React.useRef({ userId: null });

	const [branchList, setBranchList] = React.useState({
		status: BRANCH_LIST_STATE.IDLE,
		branches: null,
	});

	const activePrimaryNav = React.useMemo(() => {
		return getPrimaryNavFromPathname(pathname);
	}, [pathname]);

	const isExplorerActive = activePrimaryNav?.active === PRIMARY_NAV.EXPLORER;
	const isSearchActive = activePrimaryNav?.active === PRIMARY_NAV.SEARCH;

	const routeBranch = React.useMemo(() => {
		return readRouteBranchFromPathname(pathname);
	}, [pathname]);

	const knownBranches =
		branchList.status === BRANCH_LIST_STATE.READY &&
		Array.isArray(branchList.branches)
			? branchList.branches
			: null;

	const hasInvalidRouteBranch = Boolean(
		isAdminLike &&
		routeBranch &&
		knownBranches &&
		!knownBranches.includes(routeBranch),
	);

	// A) Initialize selectedBranch once per authenticated admin-like user
	React.useEffect(() => {
		if (!isAuthenticated) {
			initRef.current.userId = null;
			setSelectedBranch(null);
			return;
		}

		if (isBranchUser) {
			const own = user.branchId;
			setSelectedBranch(own && isValidBranchParam(own) ? own : null);
			return;
		}

		if (!isAdminLike) return;

		const uid = String(user.userId || "");
		if (!uid) return;

		if (initRef.current.userId === uid) return;
		initRef.current.userId = uid;

		const fromStorage = safeReadLocalStorageBranch(STORAGE_KEY_LAST_BRANCH);
		setSelectedBranch(fromStorage || null);
	}, [
		isAuthenticated,
		isBranchUser,
		isAdminLike,
		user?.userId,
		user?.branchId,
	]);

	// B) Fetch branch list once for admin-like users
	React.useEffect(() => {
		if (!isAdminLike) return;

		let cancelled = false;

		setBranchList({ status: BRANCH_LIST_STATE.LOADING, branches: null });

		(async () => {
			try {
				const res = await getBranches();
				if (cancelled) return;

				const branches = Array.isArray(res?.branches) ? res.branches : [];
				setBranchList({ status: BRANCH_LIST_STATE.READY, branches });
			} catch (err) {
				if (cancelled) return;
				console.error("[QuickNav] getBranches failed:", err);
				setBranchList({ status: BRANCH_LIST_STATE.ERROR, branches: null });
			}
		})();

		return () => {
			cancelled = true;
		};
	}, [isAdminLike, user?.userId]);

	// C) Ensure selectedBranch is valid once we have the list
	React.useEffect(() => {
		if (!isAdminLike) return;
		if (!knownBranches || knownBranches.length === 0) return;

		if (selectedBranch && knownBranches.includes(selectedBranch)) return;

		const next = knownBranches[0];
		setSelectedBranch(next);
		safeWriteLocalStorageBranch(STORAGE_KEY_LAST_BRANCH, next);
	}, [isAdminLike, knownBranches, selectedBranch]);

	// D) Sync selectedBranch to the current route branch ONLY if it exists
	React.useEffect(() => {
		if (!isAdminLike) return;
		if (!routeBranch) return;
		if (!knownBranches) return;

		if (!knownBranches.includes(routeBranch)) return;
		if (routeBranch === selectedBranch) return;

		setSelectedBranch(routeBranch);
		safeWriteLocalStorageBranch(STORAGE_KEY_LAST_BRANCH, routeBranch);
	}, [isAdminLike, routeBranch, knownBranches, selectedBranch]);

	if (!isAuthenticated) return null;

	const effectiveBranch = isBranchUser ? user.branchId : selectedBranch;

	const canNavigate = Boolean(
		effectiveBranch && isValidBranchParam(effectiveBranch),
	);

	function navigateToBranchKeepingContext(nextBranch) {
		if (!isValidBranchParam(nextBranch)) return;

		const currentPathname =
			typeof window !== "undefined"
				? window.location.pathname || pathname
				: pathname;

		const currentSearch =
			typeof window !== "undefined" ? window.location.search || "" : "";

		const nextUrl = buildNextUrlForBranchSwitch({
			pathname: currentPathname,
			search: currentSearch,
			nextBranch,
		});

		if (!nextUrl) return;

		if (canRevalidate) retry();
		router.push(nextUrl);
	}

	const branchTooltipText = hasInvalidRouteBranch
		? `Achtung: ${routeBranch} existiert nicht. Bitte eine gültige Niederlassung wählen.`
		: "Niederlassung auswählen";

	return (
		<div className="hidden items-center gap-2 md:flex">
			{isAdminLike ? (
				<DropdownMenu>
					<Tooltip>
						<TooltipTrigger asChild>
							<DropdownMenuTrigger asChild>
								<Button
									variant="outline"
									size="sm"
									type="button"
									className={TOPNAV_BUTTON_CLASS}
									aria-label={branchTooltipText}
								>
									{canNavigate ? effectiveBranch : "Niederlassung wählen"}
									{hasInvalidRouteBranch ? (
										<TriangleAlert
											className="h-4 w-4 text-destructive"
											aria-hidden="true"
										/>
									) : null}
								</Button>
							</DropdownMenuTrigger>
						</TooltipTrigger>

						<TooltipContent side="bottom">{branchTooltipText}</TooltipContent>
					</Tooltip>

					<DropdownMenuContent align="end" className="min-w-64">
						<DropdownMenuLabel>Niederlassung</DropdownMenuLabel>
						<DropdownMenuSeparator />

						{hasInvalidRouteBranch ? (
							<>
								<div className="px-2 py-2 text-xs text-destructive">
									Die URL-Niederlassung <strong>{routeBranch}</strong> existiert
									nicht. Bitte wählen Sie eine gültige Niederlassung aus.
								</div>

								<DropdownMenuItem
									disabled={!canNavigate}
									onSelect={(e) => {
										e.preventDefault();
										if (!canNavigate) return;
										navigateToBranchKeepingContext(effectiveBranch);
									}}
								>
									<CornerDownLeft className="h-4 w-4" aria-hidden="true" />
									Zur letzten gültigen Niederlassung
									<span className="ml-auto text-xs text-muted-foreground">
										{canNavigate ? effectiveBranch : ""}
									</span>
								</DropdownMenuItem>

								<DropdownMenuSeparator />
							</>
						) : null}

						{branchList.status === BRANCH_LIST_STATE.ERROR ? (
							<div className="px-2 py-2 text-xs text-muted-foreground">
								Konnte nicht geladen werden.
							</div>
						) : (
							<DropdownMenuRadioGroup
								value={canNavigate ? effectiveBranch : ""}
								onValueChange={(value) => {
									if (!value) return;
									if (!isValidBranchParam(value)) return;

									setSelectedBranch(value);
									safeWriteLocalStorageBranch(STORAGE_KEY_LAST_BRANCH, value);
									navigateToBranchKeepingContext(value);
								}}
							>
								{(Array.isArray(branchList.branches)
									? branchList.branches
									: []
								).map((b) => (
									<DropdownMenuRadioItem key={b} value={b}>
										{b}
									</DropdownMenuRadioItem>
								))}
							</DropdownMenuRadioGroup>
						)}
					</DropdownMenuContent>
				</DropdownMenu>
			) : null}

			<Tooltip>
				<TooltipTrigger asChild>
					<Button
						variant="outline"
						size="sm"
						asChild
						disabled={!canNavigate}
						className={[
							TOPNAV_BUTTON_CLASS,
							isExplorerActive ? ACTIVE_NAV_BUTTON_CLASS : "",
						].join(" ")}
						aria-label="Explorer öffnen"
					>
						<Link
							href={canNavigate ? branchPath(effectiveBranch) : "#"}
							aria-current={isExplorerActive ? "page" : undefined}
						>
							<FolderOpen className="h-4 w-4" />
							Explorer
						</Link>
					</Button>
				</TooltipTrigger>

				<TooltipContent side="bottom">Explorer öffnen</TooltipContent>
			</Tooltip>

			<Tooltip>
				<TooltipTrigger asChild>
					<Button
						variant="outline"
						size="sm"
						asChild
						disabled={!canNavigate}
						className={[
							TOPNAV_BUTTON_CLASS,
							isSearchActive ? ACTIVE_NAV_BUTTON_CLASS : "",
						].join(" ")}
						aria-label="Suche öffnen"
					>
						<Link
							href={canNavigate ? searchPath(effectiveBranch) : "#"}
							aria-current={isSearchActive ? "page" : undefined}
						>
							<SearchIcon className="h-4 w-4" />
							Suche
						</Link>
					</Button>
				</TooltipTrigger>

				<TooltipContent side="bottom">Suche öffnen</TooltipContent>
			</Tooltip>
		</div>
	);
}
