import { useEffect, useRef } from "react";
import { useDispatch } from "react-redux";

import type { Token } from "@providers/ConfigProvider";
import {
	type QuoteParams,
	addOutputToken,
	setFromChainId,
	setFromTokens,
	setToChainId,
} from "@store/quoteParamSlice";
import { useConfig } from "./useConfig";
import { useSupportedChains } from "./useSupportedChains";
import { useSupportedTokens } from "./useSupportedTokens";

export const useSetInitialValues = () => {
	const config = useConfig();
	const dispatch = useDispatch();

	// Getting supported assets
	const supportedFromTokens = useSupportedTokens({ input: true });
	const supportedToTokens = useSupportedTokens({ input: false });
	const { supportedChains } = useSupportedChains({ input: true });

	const firstRender = useRef(true);

	const setChainId = (
		chainId: number | undefined,
		setChainIdAction: (chainId: number) => {
			type: string;
			payload: QuoteParams["fromChainId"];
		},
	) => {
		if (chainId) dispatch(setChainIdAction(chainId));
	};

	const setTokens = (
		chainId: number | undefined,
		tokenAddresses: string[] | undefined,
		supportedTokens: { [x: number]: Token[] },
		id?: number,
	) => {
		if (typeof chainId === "number" && tokenAddresses) {
			const token = supportedTokens?.[chainId]?.find(
				(token) => token.address?.toLowerCase() === tokenAddresses[0].toLowerCase(),
			);

			if (token) {
				if (typeof id === "number") {
					dispatch(addOutputToken({ id, token })); // for output token
				} else dispatch(setFromTokens(token));
			}
		}
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		if (
			firstRender.current &&
			config?.apiKey &&
			supportedChains &&
			Object.keys(supportedFromTokens)?.length !== 0 &&
			Object.keys(supportedToTokens)?.length !== 0
		) {
			const { fromChain, toChain, inputTokens, outputTokens } =
				config.initialValues || {};

			// SET INITIAL CHAINS
			setChainId(fromChain, setFromChainId);
			setChainId(toChain, setToChainId);

			// SET INITIAL TOKENS
			setTokens(fromChain, inputTokens, supportedFromTokens);
			setTokens(toChain, outputTokens, supportedToTokens, 0); // passing id for output token

			firstRender.current = false;
		}
	}, [config, supportedFromTokens, supportedToTokens, supportedChains]);
};
