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

import { USER_OPERATIONS, useLogError } from "@hooks/useLogError";
import { useWalletCapabilities } from "@hooks/useWalletCapabilities";
import type { ReduxStateType } from "@store/types";
import { NATIVE_TOKEN_ADDRESS, PERMIT2_ADDRESS } from "@utils/constants";
import { useSelector } from "react-redux";

export const useCheckPermit2Approval = ({
	tokenAddress,
	tokenChainId,
	amount,
	sender,
}: {
	tokenAddress?: string;
	tokenChainId?: number;
	amount?: string;
	sender?: string;
}) => {
	const { logError } = useLogError();
	const { smartBatching } = useSelector(
		(state: ReduxStateType) => state.settings,
	);

	const isNativeToken = useMemo(
		() => tokenAddress?.toLowerCase() === NATIVE_TOKEN_ADDRESS,
		[tokenAddress],
	);

	const { supportsAtomicBatching } = useWalletCapabilities(
		tokenChainId ?? undefined,
	);

	const shouldCheckPermit2 = useMemo(() => {
		return Boolean(
			supportsAtomicBatching &&
				smartBatching &&
				sender &&
				tokenAddress &&
				!isNativeToken &&
				amount,
		);
	}, [
		supportsAtomicBatching,
		smartBatching,
		sender,
		tokenAddress,
		isNativeToken,
		amount,
	]);

	const { data, isLoading, refetch, isRefetching, error } = useReadContract({
		abi: erc20Abi,
		address: tokenAddress as Address,
		functionName: "allowance",
		args: [sender as Address, PERMIT2_ADDRESS],
		chainId: tokenChainId,
		query: {
			enabled: shouldCheckPermit2,
		},
	});

	const hasPermit2Approval = useMemo(() => {
		if (!data || !amount) return false;
		return data >= BigInt(amount);
	}, [data, amount]);

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

	return {
		data,
		hasPermit2Approval,
		isCheckingPermit2Approval: isLoading,
		isRefetchingPermit2Approval: isRefetching,
		refetchPermit2Approval: refetch,
		shouldCheckPermit2,
	};
};
