import { useMemo } from "react";

import type { Token } from "@/types/index";
import {
	EUR_LIST,
	NATIVE_SOLANA_TOKEN_ADDRESS,
	NATIVE_TOKEN_ADDRESS,
	USDC_LIST,
	USDT_LIST,
} from "@utils/constants";
import { removeDuplicateTokens } from "@utils/getFormattedTokenList";

const USDC_LIST_LOWER = USDC_LIST.map((address) => address.toLowerCase());
const USDT_LIST_LOWER = USDT_LIST.map((address) => address.toLowerCase());
const EUR_LIST_LOWER = EUR_LIST.map((address) => address.toLowerCase());

export const useTrendingTokens = ({
	tokens,
}: {
	tokens: Token[] | undefined;
}) => {
	const trendingTokens = useMemo(() => {
		if (tokens?.length) {
			const filteredTokens = tokens?.filter((token) => {
				if (!token.isVerified) return false;

				const tokenAddressLower = token.address.toLowerCase();

				return (
					token.address === NATIVE_TOKEN_ADDRESS ||
					mostUsedTokensAddresses.includes(tokenAddressLower) ||
					USDC_LIST_LOWER.includes(tokenAddressLower) ||
					USDT_LIST_LOWER.includes(tokenAddressLower) ||
					EUR_LIST_LOWER.includes(tokenAddressLower)
				);
			});
			const dedupedTokens = removeDuplicateTokens(filteredTokens);

			// Sort and Keep to a max of 4 tokens
			return dedupedTokens.sort(tokenSortFn).slice(0, 4).filter(Boolean);
		}
	}, [tokens]);

	return trendingTokens;
};

// Sort Order: Native Tokens, USDC, USDT, Others
const tokenSortFn = (a: Token, b: Token) => {
	const aSymbolLower = a.symbol.toLowerCase();
	const bSymbolLower = b.symbol.toLowerCase();

	// Native tokens first (priority 1)
	const aIsNative =
		a.address === NATIVE_TOKEN_ADDRESS ||
		a.address === NATIVE_SOLANA_TOKEN_ADDRESS;
	const bIsNative =
		b.address === NATIVE_TOKEN_ADDRESS ||
		b.address === NATIVE_SOLANA_TOKEN_ADDRESS;

	if (aIsNative && !bIsNative) return -1;
	if (!aIsNative && bIsNative) return 1;

	// USDC second (priority 2)
	const aIsUSDC = aSymbolLower === "usdc";
	const bIsUSDC = bSymbolLower === "usdc";

	if (aIsUSDC && !bIsUSDC) return -1;
	if (!aIsUSDC && bIsUSDC) return 1;

	// USDT variants third (priority 3) - matches usdt, usdt0, etc.
	const aIsUSDT =
		aSymbolLower.includes("usdt") || aSymbolLower.includes("usd₮0");
	const bIsUSDT =
		bSymbolLower.includes("usdt") || bSymbolLower.includes("usd₮0");

	if (aIsUSDT && !bIsUSDT) return -1;
	if (!aIsUSDT && bIsUSDT) return 1;

	// Keep original order for others
	return 0;
};

// used for specific tokens - like op and arb
const mostUsedTokensAddresses = [
	"0x4200000000000000000000000000000000000042".toLowerCase(), // OP
	"0x912ce59144191c1204e64559fe8253a0e49e6548".toLowerCase(), // ARB
	NATIVE_TOKEN_ADDRESS,
	NATIVE_SOLANA_TOKEN_ADDRESS,
	"0x1789e0043623282d5dcc7f213d703c6d8bafbb04".toLowerCase(), // Linea
];
