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

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

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

	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, error } = 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),
		},
	});

	useEffect(() => {
		if (error && logError) {
			logError(error, { operation: USER_OPERATIONS.APPROVAL_CHECK });
		}
	}, [error, logError]);

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