import { useState, useEffect } from 'react';

const CHAIN_ID = '0x8a';

interface UseChain138Return {
  isConnected: boolean;
  isLoading: boolean;
  connect: () => Promise<void>;
  chainId: string | null;
}

export function useChain138(): UseChain138Return {
  const [isConnected, setIsConnected] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [chainId, setChainId] = useState<string | null>(null);

  const checkConnection = async () => {
    if (typeof window === 'undefined' || !window.ethereum) {
      setIsConnected(false);
      setIsLoading(false);
      return;
    }

    try {
      const currentChainId = await window.ethereum.request({
        method: 'eth_chainId',
      }) as string;
      
      setChainId(currentChainId);
      setIsConnected(currentChainId === CHAIN_ID);
    } catch (error) {
      setIsConnected(false);
    } finally {
      setIsLoading(false);
    }
  };

  const connect = async () => {
    if (typeof window === 'undefined' || !window.ethereum) {
      throw new Error('MetaMask is not installed');
    }

    const networkMetadata = {
      chainId: CHAIN_ID,
      chainName: 'DeFi Oracle Meta Mainnet',
      nativeCurrency: {
        name: 'Ether',
        symbol: 'ETH',
        decimals: 18,
      },
      rpcUrls: ['https://rpc.d-bis.org'],
      blockExplorerUrls: ['https://explorer.d-bis.org'],
    };

    try {
      // Try to switch first
      await window.ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: CHAIN_ID }],
      });
    } catch (error: any) {
      // If switch fails, network might not be added
      if (error.code === 4902) {
        // Add the network
        await window.ethereum.request({
          method: 'wallet_addEthereumChain',
          params: [networkMetadata],
        });
      } else {
        throw error;
      }
    }

    await checkConnection();
  };

  useEffect(() => {
    checkConnection();

    if (window.ethereum) {
      const handleChainChanged = () => {
        checkConnection();
      };

      window.ethereum.on('chainChanged', handleChainChanged);

      return () => {
        window.ethereum?.removeListener('chainChanged', handleChainChanged);
      };
    }
  }, []);

  return { isConnected, isLoading, connect, chainId };
}

