import { useMemo } from "react";
import { type Address, erc20Abi } from "viem";
import { useReadContract } from "wagmi";

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

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

	const { primaryInput, sender, approvalData } = activeRoute || {};

	const targetAddress = approvalData?.spenderAddress;

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

	const { data, isLoading, refetch, isRefetching } = useReadContract({
		abi: erc20Abi,
		address: primaryInput?.token?.address as Address,
		functionName: "allowance",
		args: [sender as Address, targetAddress as Address],
		chainId: primaryInput?.token.chainId,
		query: {
			enabled:
				Boolean(sender) &&
				Boolean(targetAddress) &&
				!isNativeToken &&
				!isWrapUnwrapCase(activeRoute),
		},
	});

	return {
		data,
		isCheckingApproval: isLoading,
		isRefetchingApproval: isRefetching,
		refetchApproval: refetch,
	};
};
