'use client';

import { useMemo } from 'react';
import assert from 'assert';

import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react';
import { WalletModalProvider } from '@solana/wallet-adapter-react-ui';
import { BackpackWalletAdapter } from '@solana/wallet-adapter-backpack';
import { PhantomWalletAdapter } from '@solana/wallet-adapter-phantom';
import { SolflareWalletAdapter } from '@solana/wallet-adapter-solflare';

import { usePaymentMethod } from '@/contexts/PaymentMethodContext';
import { PaymentMethod } from '@/types';

// Default styles that can be overridden by your app
import '@solana/wallet-adapter-react-ui/styles.css';

assert(process.env.NEXT_PUBLIC_SOLANA_RPC_URL, 'SOLANA_RPC_URL is required');
const SOLANA_RPC_URL = process.env.NEXT_PUBLIC_SOLANA_RPC_URL;

interface WalletProvidersProps {
  children: React.ReactNode;
}

export default function WalletProviders({ children }: WalletProvidersProps) {
  const { selectedPaymentMethod } = usePaymentMethod();

  // Configure the Solana network endpoint
  const endpoint = useMemo(() => {
    return SOLANA_RPC_URL;
  }, []);

  // All available wallet adapters
  const allWallets = useMemo(
    () => [
      new PhantomWalletAdapter(),
      new SolflareWalletAdapter(),
      new BackpackWalletAdapter()
    ],
    []
  );

  // Filter wallets based on selected payment method
  const wallets = useMemo(() => {
    if (!selectedPaymentMethod) {
      // If no payment method selected, do not show any wallets
      return [];
    }

    return allWallets.filter(wallet => {
      const isBackpack = wallet.name.toLowerCase().includes('backpack');

      if (selectedPaymentMethod === PaymentMethod.NAT_GOR) {
        return isBackpack; // Only Backpack for native GOR
      } else {
        return !isBackpack; // Only non-Backpack wallets for SPL tokens
      }
    });
  }, [allWallets, selectedPaymentMethod]);

  return (
    <ConnectionProvider endpoint={endpoint}>
      <WalletProvider wallets={wallets} autoConnect>
        <WalletModalProvider>
          {children}
        </WalletModalProvider>
      </WalletProvider>
    </ConnectionProvider>
  );
}
