import React, { FC, ReactNode, useMemo, useCallback, useEffect } from 'react';
import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react';
import { WalletAdapterNetwork, WalletError } from '@solana/wallet-adapter-base';
import { WalletModalProvider } from '@solana/wallet-adapter-react-ui';
import {
  PhantomWalletAdapter,
  SolflareWalletAdapter,
  TorusWalletAdapter,
} from '@solana/wallet-adapter-wallets';
import { clusterApiUrl } from '@solana/web3.js';
import { toast } from 'sonner';

// Import the CSS for wallet modal
import '@solana/wallet-adapter-react-ui/styles.css';

interface WalletContextProviderProps {
  children: ReactNode;
}

export const WalletContextProvider: FC<WalletContextProviderProps> = ({ children }) => {
  // Use devnet for development and testing
  const network = WalletAdapterNetwork.Devnet;
  const endpoint = useMemo(() => clusterApiUrl(network), [network]);

  // Debug wallet detection
  useEffect(() => {
    console.log('Checking wallet availability...');
    console.log('window.solana:', typeof window !== 'undefined' ? (window as any).solana : 'window unavailable');
    console.log('window.phantom:', typeof window !== 'undefined' ? (window as any).phantom : 'window.phantom unavailable');
    
    if (typeof window !== 'undefined') {
      // Check if Phantom is installed
      const windowAny = window as any;
      const isPhantomInstalled = windowAny.solana?.isPhantom || windowAny.phantom?.solana?.isPhantom;
      console.log('Phantom detected:', isPhantomInstalled);
      
      if (!isPhantomInstalled) {
        console.warn('Phantom wallet not detected. Please install Phantom wallet extension.');
      }
    }
  }, []);

  const wallets = useMemo(
    () => {
      console.log('Initializing wallet adapters...');
      return [
        new PhantomWalletAdapter(),
        new SolflareWalletAdapter(),
        new TorusWalletAdapter(),
      ];
    },
    []
  );

  const onError = useCallback(
    (error: WalletError) => {
      console.error('Wallet error details:', {
        name: error.name,
        message: error.message,
        stack: error.stack
      });
      
      if (error.name === 'WalletNotReadyError') {
        console.log('WalletNotReadyError - checking if Phantom is properly installed...');
        
        // Give user clear instructions
        toast.error('Wallet Not Ready', {
          description: 'Please install Phantom wallet extension and refresh the page.',
          duration: 6000,
          action: {
            label: 'Install Phantom',
            onClick: () => window.open('https://phantom.app/', '_blank'),
          },
        });
      } else if (error.name === 'WalletConnectionError') {
        toast.error('Connection Failed', {
          description: 'Please try connecting again or refresh the page.',
          duration: 4000,
        });
      } else {
        toast.error('Wallet Error', {
          description: error.message || 'An unexpected error occurred.',
          duration: 4000,
        });
      }
    },
    []
  );

  return (
    <ConnectionProvider endpoint={endpoint}>
      <WalletProvider 
        wallets={wallets} 
        onError={onError} 
        autoConnect={false}
        localStorageKey="walletAdapter"
      >
        <WalletModalProvider>
          {children}
        </WalletModalProvider>
      </WalletProvider>
    </ConnectionProvider>
  );
};