import type { Address } from "viem";
import { useBytecode } from "wagmi";

export interface AccountType {
	isEOA: boolean;
	isSmartContract: boolean;
	isEIP7702: boolean;
	delegatedTo?: string; // For EIP-7702, the target contract address
}

export function useSmartAccountType(
	address: string,
	chainId: number,
): AccountType {
	const { data: bytecode } = useBytecode({
		address: address?.toLowerCase() as Address,
		chainId,
	});

	if (!bytecode || bytecode === "0x" || bytecode.length === 0) {
		return {
			isEOA: true,
			isSmartContract: false,
			isEIP7702: false,
		};
	}

	// Check for EIP-7702 delegation designator
	if (bytecode.startsWith("0xef0100")) {
		// Extract the delegated address (next 20 bytes after the prefix)
		const delegatedTo =
			bytecode.length >= 46 ? `0x${bytecode.slice(6, 46)}` : undefined;

		return {
			isEOA: false, // Acts like a smart contract when delegated
			isSmartContract: true,
			isEIP7702: true,
			delegatedTo,
		};
	}

	// Regular smart contract
	return {
		isEOA: false,
		isSmartContract: true,
		isEIP7702: false,
	};
}

// For backward compatibility with existing code
export function useIsSmartAccount(address: string, chainId: number): boolean {
	const accountType = useSmartAccountType(address, chainId);
	return accountType.isSmartContract;
}

// Specific EIP-7702 detection
export function useIsEIP7702Account(address: string, chainId: number): boolean {
	const accountType = useSmartAccountType(address, chainId);
	return accountType.isEIP7702;
}
