import { useConfig } from "@hooks/useConfig";
import type { Chain } from "@store/globalSlice";
import { useQuery } from "@tanstack/react-query";
import { bungeeApiFetcher } from "@utils/fetcher";
import { useMemo } from "react";

export const useChains = () => {
	const { baseUrl, apiKey, affiliateId } = useConfig();
	const query = `${baseUrl}/supported-chains`;

	const { data } = useQuery({
		queryKey: ["supported-chains", query, apiKey],
		queryFn: () =>
			bungeeApiFetcher({
				query,
				apiKey,
				affiliateId,
			}),
		refetchOnWindowFocus: false,
		refetchOnMount: false,
		retry: 2,
		staleTime: 300000, // 5 minutes
	});

	const chains = data?.result ?? [];

	// Memoize the return value to prevent infinite loops when used in effects
	return useMemo(() => {
		if (!chains?.length) return undefined;

		// Check if monad chain is already in the array to avoid duplicates
		const hasMonadChain = chains.some(
			(chain: Chain) => chain.chainId === monadChain.chainId,
		);

		if (hasMonadChain) {
			return chains as Chain[];
		}

		return [...chains, monadChain] as Chain[];
	}, [chains]);
};

// temporary monad chain
const monadChain: Chain = {
	chainId: 143,
	name: "Monad",
	icon: "https://assets.coingecko.com/coins/images/38927/standard/monad.jpg",
	isL1: true,
	sendingEnabled: true,
	receivingEnabled: true,
	currency: {
		address: "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
		name: "Monad",
		symbol: "MON",
		decimals: 18,
		logoURI:
			"https://assets.coingecko.com/coins/images/38927/standard/monad.jpg",
		minNativeCurrencyForGas: "10000000000000000", // 0.1 MON
		chainId: 143,
	},
	rpcs: ["https://rpc.monad.xyz"],
	explorers: ["https://monadscan.com"],
};
