import React, { useState } from 'react';
import { useSoulStream } from '../contexts/SoulStreamContext';

interface ChainSwitcherProps {
  onSwitch?: (chainId: string, success: boolean) => void;
  className?: string;
}

/**
 * A component that allows users to switch between configured chains
 */
const ChainSwitcher: React.FC<ChainSwitcherProps> = ({ 
  onSwitch,
  className = ''
}) => {
  const { chains, switchChain, currentChainId } = useSoulStream();
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);

  const handleSwitchChain = async (chainId: string) => {
    if (chainId === currentChainId) return;
    
    try {
      setIsLoading(true);
      setError(null);
      
      const success = await switchChain(chainId);
      
      if (success) {
        if (onSwitch) {
          onSwitch(chainId, true);
        }
      } else {
        setError(`Failed to switch to chain ${chainId}`);
        if (onSwitch) {
          onSwitch(chainId, false);
        }
      }
    } catch (err) {
      console.error('Error switching chain:', err);
      setError('Error switching chain');
      if (onSwitch) {
        onSwitch(chainId, false);
      }
    } finally {
      setIsLoading(false);
    }
  };

  if (!chains.chainA && !chains.chainB) {
    return <div className={className}>No chains configured</div>;
  }

  return (
    <div className={`chain-switcher ${className}`}>
      <div className="chain-switcher-header">
        <h4>Network</h4>
      </div>
      
      <div className="chain-switcher-options">
        {chains.chainA && (
          <button
            className={`chain-option ${currentChainId === chains.chainA.chainId ? 'active' : ''}`}
            onClick={() => handleSwitchChain(chains.chainA!.chainId)}
            disabled={isLoading || currentChainId === chains.chainA.chainId}
          >
            Ethereum (Chain A)
            {currentChainId === chains.chainA.chainId && <span className="current-indicator">•</span>}
          </button>
        )}
        
        {chains.chainB && (
          <button
            className={`chain-option ${currentChainId === chains.chainB.chainId ? 'active' : ''}`}
            onClick={() => handleSwitchChain(chains.chainB!.chainId)}
            disabled={isLoading || currentChainId === chains.chainB.chainId}
          >
            Polygon (Chain B)
            {currentChainId === chains.chainB.chainId && <span className="current-indicator">•</span>}
          </button>
        )}
      </div>
      
      {isLoading && <div className="chain-switcher-loading">Switching networks...</div>}
      {error && <div className="chain-switcher-error">{error}</div>}
    </div>
  );
};

export default ChainSwitcher;