import type { ReduxStateType } from "@store/types";
import { useEffect } from "react";
import { useSelector } from "react-redux";

import { useConfig } from "./useConfig";
import { useMappedChainData } from "./useMappedChainData";

export const useRegisterEventHandlers = () => {
	const mappedChainData = useMappedChainData();
	const bungeeConfig = useConfig();
	const { fromChainId, fromTokens, toChainId, toTokens } = useSelector(
		(state: ReduxStateType) => state.quoteParams,
	);

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		const token = fromTokens?.[0];
		token && bungeeConfig?.eventHandlers?.onFromTokenChange?.(token);
	}, [fromTokens]);

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		const token = toTokens?.[0];
		token && bungeeConfig?.eventHandlers?.onToTokenChange?.(token);
	}, [toTokens]);

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		if (fromChainId && mappedChainData) {
			const chain = mappedChainData[fromChainId];
			bungeeConfig?.eventHandlers?.onFromChainChange?.(chain);
		}
	}, [fromChainId]);

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		if (toChainId && mappedChainData) {
			const chain = mappedChainData[toChainId];
			bungeeConfig?.eventHandlers?.onToChainChange?.(chain);
		}
	}, [toChainId]);
};
