import { useSelector } from "react-redux";

import type { Chain } from "@store/globalSlice";
import type { ReduxStateType } from "@store/types";
import { useMemo } from "react";
import { useConfig } from "./useConfig";

/** This hook returns sending/receiving chains based on config */
export const useSupportedChains = ({ input = true }: { input: boolean }) => {
	const config = useConfig();
	const allChains = useSelector(
		(state: ReduxStateType) => state.global.supportedChains,
	);

	const enabledChains = useMemo(
		() =>
			allChains?.filter((chain: Chain) =>
				input ? chain.sendingEnabled : chain.receivingEnabled,
			),
		[allChains, input],
	);

	// Filtering out config chains if provided
	const chainsFromConfig = useMemo(
		() => (input ? config?.supportedChains?.from : config?.supportedChains?.to),
		[config, input],
	);

	const supportedChains = useMemo(
		() =>
			chainsFromConfig
				? enabledChains
						.filter((chain: Chain) => chainsFromConfig.includes(chain.chainId))
						.sort(
							(a, b) =>
								chainsFromConfig.indexOf(a.chainId) - chainsFromConfig.indexOf(b.chainId),
						)
				: enabledChains,
		[enabledChains, chainsFromConfig],
	);

	return {
		supportedChains,
		supportedChainIds: chainsFromConfig,
	};
};
