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

import { SwitchChain } from "@components/common/SwitchChain";
import { useActiveRoute } from "@hooks/apis/common/quote/useActiveRoute";
import { isAutoQuote } from "@hooks/apis/common/quote/useQuote";
import { useIsChainSwitchRequired } from "@hooks/useIsChainSwitchRequired";
import { setApprovalData } from "@store/approvalSlice";
import type { ReduxStateType } from "@store/types";
import { CheckApproval } from "../Approval/CheckApproval";
import { AutoFlow } from "../Auto";
import { ManualFlow } from "../Manual";

export const ActionButton = () => {
	const dispatch = useDispatch();
	const { data: activeRoute } = useActiveRoute();
	const { isApprovalGiven } = useSelector(
		(state: ReduxStateType) => state.approval,
	);

	// reset on every mount
	useEffect(() => {
		setApprovalState(false);
	}, []);

	function setApprovalState(value: boolean) {
		dispatch(
			setApprovalData({
				isApprovalGiven: value,
			}),
		);
	}

	const isChainSwitchRequired = useIsChainSwitchRequired({
		activeRoute: activeRoute,
	});

	if (isApprovalGiven && activeRoute) {
		/** @todo - universal signature support pending */
		if (isChainSwitchRequired) {
			return <SwitchChain switchTo={activeRoute?.primaryInput?.token.chainId} />;
		}

		if (isAutoQuote(activeRoute)) {
			return <AutoFlow data={activeRoute} />;
		}

		return <ManualFlow data={activeRoute} />;
	}

	return <CheckApproval setIsApprovalGiven={setApprovalState} />;
};
