import React, { useState } from 'react';

interface AddTokenButtonProps {
  address: string;
  symbol: string;
  decimals: number;
  image?: string;
}

export function AddTokenButton({
  address,
  symbol,
  decimals,
  image,
}: AddTokenButtonProps) {
  const [isAdding, setIsAdding] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const addToken = async () => {
    if (typeof window === 'undefined' || !window.ethereum) {
      setError('MetaMask is not installed');
      return;
    }

    setIsAdding(true);
    setError(null);

    try {
      await window.ethereum.request({
        method: 'wallet_watchAsset',
        params: {
          type: 'ERC20',
          options: {
            address,
            symbol,
            decimals,
            ...(image && { image }),
          },
        },
      });
    } catch (err: any) {
      setError(err.message || 'Failed to add token');
    } finally {
      setIsAdding(false);
    }
  };

  return (
    <div>
      <button onClick={addToken} disabled={isAdding}>
        {isAdding ? 'Adding...' : `Add ${symbol}`}
      </button>
      {error && <div style={{ color: 'red' }}>{error}</div>}
    </div>
  );
}

