import { useCallback, useEffect, useState } from "react";

import type { Token } from "@/types/index";
import { useSupportedTokens } from "@hooks/useSupportedTokens";
import { NATIVE_TOKEN_ADDRESS } from "@utils/constants";

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

	const fallbackTokenGetter = useCallback(
		(tokenA: Token, tokenB: Token) => {
			const sameNetworks = tokenA.chainId === tokenB.chainId;
			// If cross chain swaps, return;
			if (!sameNetworks) return;

			const sourceTokenAddress = tokenA?.address?.toLowerCase();
			const destinationTokenAddress = tokenB?.address?.toLowerCase();

			const sameTokens = sourceTokenAddress === destinationTokenAddress;

			if (sameTokens) {
				return getFallbackToken(tokens?.[tokenB.chainId], tokenA);
			}
		},
		[tokens],
	);

	useEffect(() => {
		if (!tokenA || !tokenB) return;

		const fallbackToken = fallbackTokenGetter(tokenA, tokenB);
		setFallbackToken(fallbackToken);
	}, [tokenA, tokenB, fallbackTokenGetter]);

	return [fallbackToken, fallbackTokenGetter] as const;
};

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

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

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

	return fallbackToken;
}
