import type { Token } from "@/types/index";
import { sortTokens } from "@utils/sortTokens";
import { useMemo } from "react";

/**
 * This hook returns the tokens for each chain
 * Tokens with balance are returned in case "all networks" is selected
 */
export const useFilteredTokens = ({
	allTokens,
	formattedTokenList,
	activeNetwork,
}: {
	allTokens: { [chainId: string]: Token[] };
	formattedTokenList: Token[];
	activeNetwork: number | "all";
}) => {
	const filteredTokens = useMemo(() => {
		if (activeNetwork === "all") {
			const tokensWithBalance = formattedTokenList?.filter(
				(token) => token?.balance !== "0",
			);

			if (!tokensWithBalance) return undefined;

			// Use unified sort function - prioritize by balanceInUsd (descending)
			// This maintains the same behavior as the previous inline sort
			return sortTokens(tokensWithBalance, {
				activeNetwork: "all",
			});
		}
		return allTokens[activeNetwork];
	}, [activeNetwork, formattedTokenList, allTokens]);

	return filteredTokens;
};
