import { useEffect } from "react";
import { formatEther, type Address } from "viem";
import { useBalance, useBlockNumber, useConnect, useConnection, useConnectors, useDisconnect } from "wagmi";

function WalletDetails({ address }: { address: Address }) {
    const { data: blockNumber } = useBlockNumber({ watch: true });
    const { data: balance, isPending, error, refetch: refetchBalance } = useBalance({ address });
    const { mutate: disconnect } = useDisconnect();

    useEffect(() => {
        refetchBalance();
    }, [blockNumber]);

    return (
        <div className="flex flex-col gap-6">
            <h1 className="text-lg font-bold">You are connected</h1>

            <p className="break-all">Your address is: {address}</p>

            {isPending && <p>Loading balance...</p>}
            {error && <p>An error occurred.</p>}

            {blockNumber && <p>Block number: {blockNumber.toLocaleString()}</p>}
            {balance && <p>Balance: {formatEther(balance.value)} ETH</p>}

            <div className="flex flex-row">
                <button
                    className="bg-black text-white py-2 px-6 rounded-xl cursor-pointer"
                    onClick={() => disconnect()}
                >
                    Disconnect
                </button>
            </div>
        </div>
    )
}



function ConnectWallet() {
    const connectors = useConnectors();
    const { mutate: connect } = useConnect();

    return (
        <div className="flex flex-col gap-6">
            <h1 className="text-lg font-bold">Connect your wallet</h1>

            <p>Choose an option from the list below:</p>
            <div className="flex flex-row gap-6">
                {connectors.map(connector => (
                    <button
                        key={connector.id}
                        onClick={() => connect({ connector })}
                        className="bg-black text-white px-6 py-2 rounded-lg cursor-pointer"
                    >
                        Connect {connector.name}
                    </button>
                ))}
            </div>

        </div>
    )
}


export function StatusPage() {
    const { address, isConnected } = useConnection();

    return (
        <div className="bg-white p-5 border border-slate-200 shadow-sm rounded-xl flex flex-col gap-6">
            {isConnected && address ? (
                <WalletDetails address={address} />
            ) : (
                <ConnectWallet />
            )}

        </div>
    );
}
