import { useEffect, useState } from "react";

import { useSupportedTokens } from "@hooks/useSupportedTokens";
import type { Token } from "@providers/ConfigProvider";
import { NATIVE_TOKEN_ADDRESS } from "@utils/constants";

export const useFallbackToken = ({
	sourceToken,
	destToken,
}: { sourceToken: Token; destToken: Token }) => {
	const [fallbackToken, setFallbackToken] = useState<Token | undefined>();
	const tokens = useSupportedTokens({ input: false });

	useEffect(() => {
		if (!sourceToken || !destToken) return;

		const sameNetworks = sourceToken.chainId === destToken?.chainId;
		if (!sameNetworks) return;

		const sourceTokenAddress = sourceToken?.address?.toLowerCase();
		const destinationTokenAddress = destToken?.address?.toLowerCase();

		const sameTokens = sourceTokenAddress === destinationTokenAddress;

		if (sameTokens) {
			setFallbackToken(getFallbackToken(tokens?.[destToken.chainId], sourceToken));
		}
	}, [sourceToken, destToken, tokens]);

	return fallbackToken;
};

function getFallbackToken(tokens: Token[], sourceToken: Token) {
	if (!tokens || !sourceToken) return {} as Token;

	const fallbackToken = tokens.find((token) => {
		const tokenAddress = token.address.toLowerCase();
		const sourceTokenAddress = sourceToken.address.toLowerCase();

		const notSourceToken = tokenAddress !== sourceTokenAddress;
		if (notSourceToken) {
			return (
				token.symbol.toLowerCase() === "usdc" || tokenAddress === NATIVE_TOKEN_ADDRESS
			);
		}
	});

	return fallbackToken;
}
