import { useState, useEffect } from 'react';
import { useWallet } from '../context/WalletContext';

const TokenSelectModal = ({ isOpen, onClose, onSelect, excludeToken = null }) => {
  const { activeWallet } = useWallet();
  const [searchQuery, setSearchQuery] = useState('');
  const [filteredTokens, setFilteredTokens] = useState([]);

  // Маппинг символа токена на иконку
  const getTokenIcon = (symbol) => {
    const tokenIcons = {
      'TRX': '/coins/trx.png',
      'BTC': '/coins/btc.png',
      'ETH': '/coins/eth.png',
      'BNB': '/coins/bnb.png',
      'SOL': '/coins/sol.png',
      'TON': '/coins/ton.png',
      'USDT': '/coins/tether.png',
      'XRP': '/coins/xrp.png',
      'DOGE': '/coins/doge.png',
      'ARB': '/coins/arb.png',
      'STRK': '/coins/strk.png',
      'ADA': '/coins/ada.png',
      'SUI': '/coins/sui.png',
      'DOT': '/coins/dot.png',
      'SHIB': '/coins/shiba.png',
      'USDTERC': '/coins/tether.png',
      'ZEC': '/coins/zec.png',
      'NOT': '/coins/not.png',
      'XLM': '/coins/xlm.png',
      'HYPE': '/coins/hype.png',
      'UNI': '/coins/uni.png',
      'NEAR': '/coins/near.png',
      'PEPE': '/coins/pepe.png',
      'ATOM': '/coins/atom.png',
      'DASH': '/coins/dash.png',
      'CAKE': '/coins/cake.png',
      'ZK': '/coins/zk.png',
      'HBAR': '/coins/hbar.jpg',
      'LTC': '/coins/ltc.png',
      'LINK': '/coins/link.png',
      'APT': '/coins/apt.png',
      'LDO': '/coins/ldo.png',
      'AAVE': '/coins/aave.png',
      'AVAX': '/coins/avax.png',
      'ASTER': '/coins/aster.png',
      'FIL': '/coins/fil.png',
      'PAXG': '/coins/paxg.png',
      'USDC': '/coins/usdc.png',
      'XAUt': '/coins/xaut.png',
      'TRUMP': '/coins/trump.png',
      'OP': '/coins/op.png',
      'DCR': '/coins/dcr.png',
      'SAND': '/coins/sand.png',
      'INJ': '/coins/inj.png',
      'MNT': '/coins/mnt.png',
      'XMR': '/coins/xmr.png',
      'KAS': '/coins/kas.png',
      'ENS': '/coins/ens.png',
      'CC': '/coins/cc.png',
      'XPL': '/coins/xpl.png',
      'LAYER': '/coins/layer.png',
      'BERA': '/coins/bera.png',
      'WLFI': '/coins/wlfi.png',
      'ICP': '/coins/icp.png',
      'JUP': '/coins/jup.png',
      'ZERO': '/coins/zero.png',
      'ETC': '/coins/etc.png',
      'XCH': '/coins/chia.png',
      'VON': '/coins/von.jpg',
      'ETHZK': '/coins/eth.png',
      'ENA': '/coins/ena.png',
      'ETHFI': '/coins/ethfi.png',
      'GRASS': '/coins/grass.jpg',
      'USD1': '/coins/usd1.png',
      'OKB': '/coins/okb.png',
      'BCH': '/coins/bch.png',
      'TAO': '/coins/tao.png',
      'ENSO': '/coins/enso.jpg'
    };
    return tokenIcons[symbol] || '/coins/eth.png';
  };

  // Список всех токенов сайта
  const allTokens = [
    { symbol: 'TRX', name: 'Tron', network: 'Tron' },
    { symbol: 'BTC', name: 'Bitcoin', network: 'Bitcoin' },
    { symbol: 'ETH', name: 'Ethereum', network: 'Ethereum' },
    { symbol: 'BNB', name: 'Binance Coin', network: 'BNB Smart Chain' },
    { symbol: 'SOL', name: 'Solana', network: 'Solana' },
    { symbol: 'TON', name: 'Toncoin', network: 'The Open Network' },
    { symbol: 'USDT', name: 'Tether USD', network: 'Tron' },
    { symbol: 'XRP', name: 'Ripple', network: 'Ripple' },
    { symbol: 'DOGE', name: 'Dogecoin', network: 'Dogecoin' },
    { symbol: 'ARB', name: 'Arbitrum', network: 'Ethereum' },
    { symbol: 'STRK', name: 'Starknet', network: 'Ethereum' },
    { symbol: 'ADA', name: 'Cardano', network: 'Cardano' },
    { symbol: 'SUI', name: 'Sui', network: 'Sui' },
    { symbol: 'DOT', name: 'Polkadot', network: 'Polkadot' },
    { symbol: 'SHIB', name: 'Shiba Inu', network: 'Ethereum' },
    { symbol: 'USDTERC', name: 'USDT', network: 'Ethereum' },
    { symbol: 'ZEC', name: 'Zcash', network: 'Zcash' },
    { symbol: 'NOT', name: 'Notcoin', network: 'The Open Network' },
    { symbol: 'XLM', name: 'Stellar', network: 'Stellar' },
    { symbol: 'HYPE', name: 'Hyperliquid', network: 'Solana' },
    { symbol: 'UNI', name: 'Uniswap', network: 'Ethereum' },
    { symbol: 'NEAR', name: 'NEAR Protocol', network: 'NEAR Protocol' },
    { symbol: 'PEPE', name: 'Pepe', network: 'Ethereum' },
    { symbol: 'ATOM', name: 'Cosmos', network: 'Cosmos' },
    { symbol: 'DASH', name: 'Dash', network: 'Dash' },
    { symbol: 'CAKE', name: 'PancakeSwap', network: 'Binance Smart Chain' },
    { symbol: 'ZK', name: 'zkSync', network: 'Ethereum' },
    { symbol: 'HBAR', name: 'Hedera', network: 'Solana' },
    { symbol: 'LTC', name: 'Litecoin', network: 'Litecoin' },
    { symbol: 'LINK', name: 'Chainlink', network: 'Ethereum' },
    { symbol: 'APT', name: 'Aptos', network: 'Aptos' },
    { symbol: 'LDO', name: 'Lido DAO', network: 'Ethereum' },
    { symbol: 'AAVE', name: 'Aave', network: 'Ethereum' },
    { symbol: 'AVAX', name: 'Avalanche', network: 'Avalanche' },
    { symbol: 'ASTER', name: 'Aster', network: 'Ethereum' },
    { symbol: 'FIL', name: 'Filecoin', network: 'Filecoin' },
    { symbol: 'PAXG', name: 'PAX Gold', network: 'Ethereum' },
    { symbol: 'USDC', name: 'USD Coin', network: 'Ethereum' },
    { symbol: 'XAUt', name: 'Tether Gold', network: 'Ethereum' },
    { symbol: 'TRUMP', name: 'TRUMP', network: 'Solana' },
    { symbol: 'OP', name: 'Optimism', network: 'Optimism' },
    { symbol: 'DCR', name: 'Decred', network: 'Decred' },
    { symbol: 'SAND', name: 'The Sandbox', network: 'Ethereum' },
    { symbol: 'INJ', name: 'Injective', network: 'Injective' },
    { symbol: 'MNT', name: 'Mantle', network: 'Mantle' },
    { symbol: 'XMR', name: 'Monero', network: 'Monero' },
    { symbol: 'KAS', name: 'Kaspa', network: 'Kaspa' },
    { symbol: 'ENS', name: 'Ethereum Name Service', network: 'Ethereum' },
    { symbol: 'CC', name: 'Canton', network: 'Canton' },
    { symbol: 'XPL', name: 'Plasma', network: 'Plasma' },
    { symbol: 'LAYER', name: 'Solayer', network: 'Solayer' },
    { symbol: 'BERA', name: 'Berachain', network: 'Berachain' },
    { symbol: 'WLFI', name: 'WLFI', network: 'Ethereum' },
    { symbol: 'ICP', name: 'Internet Computer', network: 'Internet Computer' },
    { symbol: 'JUP', name: 'Jupiter', network: 'Solana' },
    { symbol: 'USD1', name: 'World Liberty Financial USD', network: 'Solana' },
    { symbol: 'ZERO', name: 'Zero', network: 'Ethereum' },
    { symbol: 'ETC', name: 'Ethereum Classic', network: 'Ethereum' },
    { symbol: 'XCH', name: 'Chia', network: 'Chia' },
    { symbol: 'VON', name: 'Vameon', network: 'Vameon' },
    { symbol: 'ETHZK', name: 'Ethereum', network: 'zkSync' },
    { symbol: 'ENA', name: 'Ethena', network: 'Ethereum' },
    { symbol: 'ETHFI', name: 'ether.fi', network: 'Ethereum' },
    { symbol: 'GRASS', name: 'Grass', network: 'Solana' },
    { symbol: 'OKB', name: 'OKB', network: 'Ethereum' },
    { symbol: 'BCH', name: 'Bitcoin Cash', network: 'Bitcoin Cash' },
    { symbol: 'TAO', name: 'Bittensor', network: 'Bittensor' },
    { symbol: 'SKR', name: 'Seeker', network: 'Solana' },
    { symbol: 'TORN', name: 'Tornado Cash', network: 'Ethereum' },
    { symbol: 'NFLXON', name: 'Netflix', network: 'Ethereum' },
    { symbol: 'NVDAON', name: 'NVIDIA', network: 'Ethereum' },
    { symbol: 'AAPL', name: 'Apple', network: 'Ethereum' },
    { symbol: 'TSLA', name: 'Tesla', network: 'Ethereum' },
    { symbol: 'MSFT', name: 'Microsoft', network: 'Ethereum' },
    { symbol: 'AMZN', name: 'Amazon', network: 'Ethereum' },
    { symbol: 'ENSO', name: 'Enso Finance', network: 'Ethereum' },
  ];

  // Получаем баланс токена из кошелька
  const getTokenBalance = (symbol) => {
    if (!activeWallet?.tokens) return '0.000000';
    const tokenData = activeWallet.tokens.find(t => t.tokenInfo?.symbol === symbol);
    return tokenData ? (parseFloat(tokenData.balance) || 0).toFixed(6) : '0.000000';
  };

  // Фильтрация токенов
  useEffect(() => {
    let filtered = allTokens;

    // Исключаем уже выбранный токен
    if (excludeToken) {
      filtered = filtered.filter(token => token.symbol !== excludeToken);
    }

    // Поиск по названию и символу
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(token =>
        token.symbol.toLowerCase().includes(query) ||
        token.name.toLowerCase().includes(query) ||
        token.network.toLowerCase().includes(query)
      );
    }

    setFilteredTokens(filtered);
  }, [searchQuery, excludeToken]);

  const handleSelect = (token) => {
    onSelect(token);
    onClose();
    setSearchQuery('');
  };

  if (!isOpen) return null;

  return (
    <>
      {/* Overlay */}
      <div 
        className="fixed inset-0 bg-black/60 z-40"
        onClick={onClose}
      />

      {/* Modal */}
      <div className="fixed inset-x-0 bottom-0 z-50 bg-[#1b1b1c] rounded-t-3xl max-h-[80vh] overflow-hidden flex flex-col max-w-[600px] mx-auto left-0 right-0">
        {/* Header */}
        <div className="sticky top-0 bg-[#1b1b1c] border-b border-gray-800 p-4">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-xl font-bold text-white">Выберите токен</h2>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-white transition-colors p-2"
            >
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          {/* Search */}
          <div className="relative">
            <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Поиск токена..."
              className="w-full pl-10 pr-4 py-3 bg-gray-800/50 text-white rounded-xl outline-none focus:ring-2 focus:ring-[#2ea169] placeholder-gray-500"
            />
          </div>
        </div>

        {/* Token List */}
        <div className="flex-1 overflow-y-auto">
          {filteredTokens.length > 0 ? (
            <div className="divide-y divide-gray-800">
              {filteredTokens.map((token) => {
                const balance = getTokenBalance(token.symbol);
                return (
                  <button
                    key={token.symbol}
                    onClick={() => handleSelect(token)}
                    className="w-full flex items-center justify-between p-4 hover:bg-gray-800/50 transition-colors"
                  >
                    <div className="flex items-center space-x-3">
                      <div className="w-10 h-10 rounded-full overflow-hidden flex-shrink-0">
                        <img 
                          src={getTokenIcon(token.symbol)} 
                          alt={token.symbol} 
                          className="w-full h-full object-contain"
                        />
                      </div>
                      <div className="text-left">
                        <div className="text-white font-semibold">{token.symbol}</div>
                        <div className="text-gray-400 text-sm">{token.network}</div>
                      </div>
                    </div>
                    <div className="text-right">
                      <div className="text-white font-medium">{balance}</div>
                      <div className="text-gray-400 text-xs">{token.name}</div>
                    </div>
                  </button>
                );
              })}
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center py-12 text-gray-400">
              <svg className="w-16 h-16 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <p className="text-lg">Токены не найдены</p>
            </div>
          )}
        </div>
      </div>
    </>
  );
};

export default TokenSelectModal;
