import { useEffect, useMemo } from "react";

import { useActiveRoute } from "@hooks/apis/common/quote/useActiveRoute";
import { NATIVE_TOKEN_ADDRESS } from "@utils/constants";
import { ApproveToken } from "./ApproveToken";
import { useCheckApproval } from "./useCheckApproval";

export const CheckApproval = ({
	setIsApprovalGiven,
}: { setIsApprovalGiven: (value: boolean) => void }) => {
	const { data, isCheckingApproval, isRefetchingApproval } = useCheckApproval();
	const { data: activeRoute } = useActiveRoute();

	const { primaryInput } = activeRoute || {};

	const isNativeToken = useMemo(
		() => primaryInput?.token?.address?.toLowerCase() === NATIVE_TOKEN_ADDRESS,
		[primaryInput],
	);

	useEffect(() => {
		// for native tokens
		if (isNativeToken) setIsApprovalGiven(true);

		// for erc20
		if (!!data?.toString() && primaryInput?.amount) {
			setIsApprovalGiven(data >= BigInt(primaryInput.amount));
		}
	}, [data, primaryInput, isNativeToken, setIsApprovalGiven]);

	return (
		<ApproveToken
			checkingApproval={isCheckingApproval}
			isLoading={isCheckingApproval || isRefetchingApproval}
		/>
	);
};

export const useIsApprovalRequired = () => {
	const { data: activeRoute } = useActiveRoute();
	const { data: approvalData } = useCheckApproval();

	const { primaryInput } = activeRoute || {};

	const isNativeToken = useMemo(
		() => primaryInput?.token?.address?.toLowerCase() === NATIVE_TOKEN_ADDRESS,
		[primaryInput],
	);

	// does unwrap need approval?

	if (isNativeToken) return false;

	if (approvalData && primaryInput?.amount) {
		if (BigInt(approvalData) >= BigInt(primaryInput?.amount)) return false;
	}

	return true;
};
