import type { Token } from "@/types/index";
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") {
			return formattedTokenList
				?.filter((token) => token?.balance !== "0")
				?.sort((tokenA, tokenB) => {
					// If tokenA has balanceInUsd, sort descending (higher value first)
					if (tokenA?.balanceInUsd !== undefined) {
						return tokenB?.balanceInUsd === undefined
							? -1
							: tokenB?.balanceInUsd - tokenA?.balanceInUsd;
					}
					// If tokenA doesn't have valueInUsd, sort ascending (any value comes after)
					return 1;
				});
		}
		return allTokens[activeNetwork];
	}, [activeNetwork, formattedTokenList, allTokens]);

	return filteredTokens;
};
