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

import { Button } from "@components/common/Button";
import { useActiveRoute } from "@hooks/apis/common/quote/useActiveRoute";
import { isAutoQuote, isManualQuote } from "@hooks/apis/common/quote/useQuote";
import { useWalletCapabilities } from "@hooks/useWalletCapabilities";
import { setApprovalData } from "@store/approvalSlice";
import type { ReduxStateType } from "@store/types";
import { isSolana } from "@utils/isSolana";
import {
	CheckApproval,
	useIsApprovalRequired,
} 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.isApprovalGiven,
	);

	const setApprovalState = useCallback(
		(value: boolean) => {
			dispatch(
				setApprovalData({
					isApprovalGiven: value,
				}),
			);
		},
		[dispatch],
	);

	const isApprovalRequired = useIsApprovalRequired();

	const { supportsAtomicBatching, isLoading } = useWalletCapabilities(
		activeRoute?.primaryInput?.token?.chainId,
	);

	// enabling batching only for manual routes; temporarily disabling batching for auto routes
	const enableBatching = useMemo(
		() => Boolean(supportsAtomicBatching && isManualQuote(activeRoute)),
		[supportsAtomicBatching, activeRoute],
	);

	// Auto-approve for batching
	useEffect(() => {
		if (!isLoading && enableBatching) {
			setApprovalState(true);
		}
	}, [enableBatching, setApprovalState, isLoading]);

	// Reset approval on mount
	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		setApprovalState(false);
	}, []);

	const isSolanaTx = isSolana(activeRoute?.primaryInput?.token?.chainId ?? 0);

	if (isLoading) return <Button label="Loading" isLoading disabled />;

	// Show approval for classic flow
	if (!enableBatching && isApprovalRequired && !isApprovalGiven && !isSolanaTx) {
		return <CheckApproval setIsApprovalGiven={setApprovalState} />;
	}

	// Proceed to flow
	if (activeRoute) {
		if (isAutoQuote(activeRoute)) return <AutoFlow data={activeRoute} />;
		return <ManualFlow data={activeRoute} />;
	}

	return null;
};
