"use client";

import React from "react";
import { usePathname } from "next/navigation";

import { useAuth } from "@/components/auth/authContext";
import { getBranches } from "@/lib/frontend/apiClient";
import {
	canManageUsers as canManageUsersRole,
	isAdminLike as isAdminLikeRole,
} from "@/lib/frontend/auth/roles";
import { isValidBranchParam } from "@/lib/frontend/params";
import { branchPath, searchPath } from "@/lib/frontend/routes";
import {
	readRouteBranchFromPathname,
	safeReadLocalStorageBranch,
} from "@/lib/frontend/quickNav/branchSwitch";
import { resolveOverviewBranchTarget } from "@/lib/frontend/overview/homeBranchTarget";

const STORAGE_KEY_LAST_BRANCH = "rhl_last_branch";

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

export function useOverviewBranchTarget() {
	const pathname = usePathname() || "/";
	const { status, user } = useAuth();

	const isAuthenticated = status === "authenticated" && user;
	const isAdminLike = isAuthenticated && isAdminLikeRole(user.role);
	const canManageUsers = isAuthenticated && canManageUsersRole(user.role);

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

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

	React.useEffect(() => {
		if (!isAuthenticated || !isAdminLike) {
			setStoredBranch(null);
			return;
		}

		setStoredBranch(safeReadLocalStorageBranch(STORAGE_KEY_LAST_BRANCH));
	}, [isAuthenticated, isAdminLike, user?.userId]);

	const localResolution = React.useMemo(() => {
		return resolveOverviewBranchTarget({
			role: user?.role,
			userBranchId: user?.branchId,
			routeBranch,
			storedBranch,
		});
	}, [user?.role, user?.branchId, routeBranch, storedBranch]);

	React.useEffect(() => {
		if (
			!isAuthenticated ||
			!isAdminLike ||
			!localResolution.shouldFetchBranches
		) {
			setBranchList({ status: BRANCH_LIST_STATE.IDLE, branches: null });
			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("[useOverviewBranchTarget] getBranches failed:", err);
				setBranchList({ status: BRANCH_LIST_STATE.ERROR, branches: null });
			}
		})();

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

	const availableBranches =
		branchList.status === BRANCH_LIST_STATE.READY ? branchList.branches : null;

	const resolvedBranchTarget = React.useMemo(() => {
		return resolveOverviewBranchTarget({
			role: user?.role,
			userBranchId: user?.branchId,
			routeBranch,
			storedBranch,
			availableBranches,
		});
	}, [
		user?.role,
		user?.branchId,
		routeBranch,
		storedBranch,
		availableBranches,
	]);

	const targetBranch = isValidBranchParam(resolvedBranchTarget.branch)
		? resolvedBranchTarget.branch
		: null;

	const explorerHref = targetBranch ? branchPath(targetBranch) : null;
	const searchHref = targetBranch ? searchPath(targetBranch) : null;
	const disabledHint = "Bitte zuerst eine gültige Niederlassung wählen.";

	return {
		isAuthenticated,
		canManageUsers,
		explorerHref,
		searchHref,
		disabledHint,
	};
}
