import { useCallback } from "react";
import { type Address, erc20Abi } from "viem";
import { useSendCalls } from "wagmi";

import type { ApprovalData, TxData } from "@hooks/apis/common/quote/types";

export function useBatchingTransaction({
	approvalData,
	txData,
	chainId,
	isApprovalRequired,
}: {
	txData: TxData;
	chainId: number;
	isApprovalRequired: boolean;
	approvalData?: ApprovalData;
}) {
	const {
		sendCalls,
		sendCallsAsync,
		data: callsData,
		isSuccess,
		isError,
		error,
	} = useSendCalls();

	const trigger = useCallback(() => {
		const calls = [];

		if (isApprovalRequired && approvalData) {
			calls.push({
				address: approvalData.tokenAddress as Address,
				abi: erc20Abi,
				functionName: "approve",
				args: [approvalData.spenderAddress as Address, BigInt(approvalData.amount)],
				chainId,
				to: approvalData.tokenAddress as Address,
			});
		}

		calls.push({
			data: txData.data as Address,
			to: txData.to as Address,
			value: BigInt(txData.value),
		});

		sendCalls({ calls });
	}, [chainId, txData, approvalData, isApprovalRequired, sendCalls]);

	const triggerAsync = useCallback(() => {
		const calls = [];

		if (isApprovalRequired && approvalData) {
			calls.push({
				address: approvalData.tokenAddress as Address,
				abi: erc20Abi,
				functionName: "approve",
				args: [approvalData.spenderAddress as Address, BigInt(approvalData.amount)],
				chainId,
				to: approvalData.tokenAddress as Address,
			});
		}

		calls.push({
			data: txData.data as Address,
			to: txData.to as Address,
			value: BigInt(txData.value),
		});

		return sendCallsAsync({ calls });
	}, [chainId, isApprovalRequired, sendCallsAsync, approvalData, txData]);

	return {
		trigger,
		triggerAsync,
		isSuccess,
		isError,
		txData: callsData,
		error,
	};
}
