import { useMemo } from "react";
import { useSelector } from "react-redux";

import { useAccounts } from "@hooks/useAccounts";
import { useMappedChainData } from "@hooks/useMappedChainData";
import { useSupportedChains } from "@hooks/useSupportedChains";
import { useSupportedTokens } from "@hooks/useSupportedTokens";
import type { TokenSelectorParams } from "@store/tokenSelectorSlice";
import type { ReduxStateType } from "@store/types";
import { getFormattedTokenList } from "@utils/getFormattedTokenList";

/** Token Selector Data for Input Token Modal */
export const useInputTokenSelectorData = () => {
	const mappedChainData = useMappedChainData();
	const { supportedChains: chains } = useSupportedChains({ input: true });
	const tokens = useSupportedTokens({ input: true });

	const { accounts } = useAccounts();

	const activeChainId = useSelector(
		(state: ReduxStateType) => state.quoteParams.fromChainId,
	);
	const activeChain = mappedChainData?.[activeChainId || 1] ?? chains?.[0];

	const activeTokens = useSelector(
		(state: ReduxStateType) => state.quoteParams.fromTokens,
	);

	const data: TokenSelectorParams = useMemo(() => {
		let _isBalanceAvailable = false;
		if (accounts.length > 0) {
			const formattedTokens = getFormattedTokenList(tokens);
			// _isBalanceAvailable = Boolean(formattedTokens?.[0]?.balance);
			_isBalanceAvailable = Boolean(
				formattedTokens.find((token) => Number(token.balance) > 0),
			);
		}

		return {
			isVisible: true,
			data: {
				id: 0,
				chains,
				activeChain: _isBalanceAvailable ? "all" : activeChain,
				activeToken: activeTokens?.[0],
				tokens,
				isSourceTokenSelector: true,
			},
		};
	}, [chains, activeChain, activeTokens, tokens, accounts]);

	return {
		data: data,
		isLoading: !Object.keys(tokens)?.length || !chains?.length,
	};
};
