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

import { SelectTokenButton } from "@components/common/SelectTokenButton";
import { TokenChip } from "@components/common/TokenChip";
import { setTokenSelectorData } from "@store/tokenSelectorSlice";
import type { ReduxStateType } from "@store/types";
import { useInputTokenSelectorData } from "./useInputTokenSelectorData";

export const InputToken = () => {
	const dispatch = useDispatch();

	const tokenSelectorDataFromStore = useSelector(
		(state: ReduxStateType) => state.tokenSelector,
	);

	const fromTokens = useSelector(
		(state: ReduxStateType) => state.quoteParams.fromTokens,
	);
	const activeToken = fromTokens?.[0];

	const { data: tokenSelectorData, isLoading } = useInputTokenSelectorData();

	const openSourceTokenSelector = useCallback(() => {
		dispatch(setTokenSelectorData(tokenSelectorData));
	}, [dispatch, tokenSelectorData]);

	const prevTokenSelectorData = useRef(tokenSelectorData);

	// to update token selector data when the tokens are changed due to wallet/account switch
	// to be updated only when the source token selector data is visible
	useEffect(() => {
		if (
			tokenSelectorData &&
			tokenSelectorData !== prevTokenSelectorData.current &&
			tokenSelectorDataFromStore?.isVisible &&
			tokenSelectorDataFromStore?.data?.isSourceTokenSelector
		) {
			dispatch(
				setTokenSelectorData({
					...tokenSelectorDataFromStore,
					data: {
						...tokenSelectorDataFromStore.data,
						tokens: tokenSelectorData?.data?.tokens,
					},
				}),
			);
		}
		prevTokenSelectorData.current = tokenSelectorData;
	}, [tokenSelectorData, tokenSelectorDataFromStore, dispatch]);

	return (
		<>
			{activeToken ? (
				<TokenChip
					token={activeToken}
					onClick={openSourceTokenSelector}
					showChain
					classNames="bn-bg-layer-3"
					big
				/>
			) : (
				<SelectTokenButton onClick={openSourceTokenSelector} isLoading={isLoading} />
			)}
		</>
	);
};
