import { useState, useEffect } from 'react';

const NetworkSelectModal = ({ isOpen, onClose, onSelect, selectedNetwork }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [filteredNetworks, setFilteredNetworks] = useState([]);

  // Маппинг сетей на иконки
  const getNetworkIcon = (network) => {
    const networkIcons = {
      'Ethereum': '/coins/eth.png',
      'Bitcoin': '/coins/btc.png',
      'Tron': '/coins/trx.png',
      'BNB Smart Chain': '/coins/bnb.png',
      'Solana': '/coins/sol.png',
      'The Open Network': '/coins/ton.png',
      'Ripple': '/coins/xrp.png',
      'Dogecoin': '/coins/doge.png',
      'Cardano': '/coins/ada.png',
      'Sui': '/coins/sui.png',
      'Polkadot': '/coins/dot.png',
      'Zcash': '/coins/zec.png',
      'Stellar': '/coins/xlm.png',
      'NEAR Protocol': '/coins/near.png',
      'Cosmos': '/coins/atom.png',
      'Dash': '/coins/dash.png',
      'Litecoin': '/coins/ltc.png',
      'Aptos': '/coins/apt.png',
      'Avalanche': '/coins/avax.png',
      'Filecoin': '/coins/fil.png',
      'Optimism': '/coins/op.png',
      'Decred': '/coins/dcr.png',
      'Injective': '/coins/inj.png',
      'Mantle': '/coins/mnt.png',
      'Monero': '/coins/xmr.png',
      'Kaspa': '/coins/kas.png',
      'Canton': '/coins/cc.png',
      'Plasma': '/coins/xpl.png',
      'Solayer': '/coins/layer.png',
      'Berachain': '/coins/bera.png',
      'Internet Computer': '/coins/icp.png',
      'Chia': '/coins/chia.png',
      'Vameon': '/coins/von.jpg',
      'Bitcoin Cash': '/coins/bch.png',
      'Bittensor': '/coins/tao.png',
    };
    return networkIcons[network] || '/coins/eth.png';
  };

  // Список всех сетей
  const allNetworks = [
    { id: 'all', name: 'Все сети', symbol: 'ALL', tokensCount: 0 },
    { id: 'ethereum', name: 'Ethereum', symbol: 'ETH', tokensCount: 15 },
    { id: 'bitcoin', name: 'Bitcoin', symbol: 'BTC', tokensCount: 1 },
    { id: 'tron', name: 'Tron', symbol: 'TRX', tokensCount: 2 },
    { id: 'bnb', name: 'BNB Smart Chain', symbol: 'BNB', tokensCount: 2 },
    { id: 'solana', name: 'Solana', symbol: 'SOL', tokensCount: 4 },
    { id: 'ton', name: 'The Open Network', symbol: 'TON', tokensCount: 2 },
    { id: 'ripple', name: 'Ripple', symbol: 'XRP', tokensCount: 1 },
    { id: 'dogecoin', name: 'Dogecoin', symbol: 'DOGE', tokensCount: 1 },
    { id: 'cardano', name: 'Cardano', symbol: 'ADA', tokensCount: 1 },
    { id: 'sui', name: 'Sui', symbol: 'SUI', tokensCount: 1 },
    { id: 'polkadot', name: 'Polkadot', symbol: 'DOT', tokensCount: 1 },
    { id: 'zcash', name: 'Zcash', symbol: 'ZEC', tokensCount: 1 },
    { id: 'stellar', name: 'Stellar', symbol: 'XLM', tokensCount: 1 },
    { id: 'near', name: 'NEAR Protocol', symbol: 'NEAR', tokensCount: 1 },
    { id: 'cosmos', name: 'Cosmos', symbol: 'ATOM', tokensCount: 1 },
    { id: 'dash', name: 'Dash', symbol: 'DASH', tokensCount: 1 },
    { id: 'litecoin', name: 'Litecoin', symbol: 'LTC', tokensCount: 1 },
    { id: 'aptos', name: 'Aptos', symbol: 'APT', tokensCount: 1 },
    { id: 'avalanche', name: 'Avalanche', symbol: 'AVAX', tokensCount: 1 },
    { id: 'filecoin', name: 'Filecoin', symbol: 'FIL', tokensCount: 1 },
    { id: 'optimism', name: 'Optimism', symbol: 'OP', tokensCount: 1 },
    { id: 'decred', name: 'Decred', symbol: 'DCR', tokensCount: 1 },
    { id: 'injective', name: 'Injective', symbol: 'INJ', tokensCount: 1 },
    { id: 'mantle', name: 'Mantle', symbol: 'MNT', tokensCount: 1 },
    { id: 'monero', name: 'Monero', symbol: 'XMR', tokensCount: 1 },
    { id: 'kaspa', name: 'Kaspa', symbol: 'KAS', tokensCount: 1 },
    { id: 'canton', name: 'Canton', symbol: 'CC', tokensCount: 1 },
    { id: 'plasma', name: 'Plasma', symbol: 'XPL', tokensCount: 1 },
    { id: 'solayer', name: 'Solayer', symbol: 'LAYER', tokensCount: 1 },
    { id: 'berachain', name: 'Berachain', symbol: 'BERA', tokensCount: 1 },
    { id: 'icp', name: 'Internet Computer', symbol: 'ICP', tokensCount: 1 },
    { id: 'chia', name: 'Chia', symbol: 'XCH', tokensCount: 1 },
    { id: 'vameon', name: 'Vameon', symbol: 'VON', tokensCount: 1 },
    { id: 'bch', name: 'Bitcoin Cash', symbol: 'BCH', tokensCount: 1 },
    { id: 'bittensor', name: 'Bittensor', symbol: 'TAO', tokensCount: 1 },
  ];

  // Фильтрация сетей
  useEffect(() => {
    let filtered = allNetworks;

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

    setFilteredNetworks(filtered);
  }, [searchQuery]);

  const handleSelect = (network) => {
    onSelect(network);
    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>

        {/* Network List */}
        <div className="flex-1 overflow-y-auto">
          {filteredNetworks.length > 0 ? (
            <div className="divide-y divide-gray-800">
              {filteredNetworks.map((network) => (
                <button
                  key={network.id}
                  onClick={() => handleSelect(network)}
                  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">
                    {network.id === 'all' ? (
                      <div className="w-10 h-10 rounded-full flex items-center justify-center bg-gray-800 flex-shrink-0">
                        <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                        </svg>
                      </div>
                    ) : (
                      <div className="w-10 h-10 rounded-full overflow-hidden flex-shrink-0">
                        <img 
                          src={getNetworkIcon(network.name)} 
                          alt={network.name} 
                          className="w-full h-full object-contain"
                        />
                      </div>
                    )}
                    <div className="text-left">
                      <div className="text-white font-semibold">{network.name}</div>
                      <div className="text-gray-400 text-sm">{network.symbol}</div>
                    </div>
                  </div>
                  {/* Индикатор выбора сети */}
                  <div className="flex-shrink-0">
                    {selectedNetwork?.id === network.id ? (
                      // Активная сеть - зелёный круг с галочкой
                      <div className="w-6 h-6 rounded-full bg-[#2ea169] flex items-center justify-center">
                        <svg className="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                        </svg>
                      </div>
                    ) : (
                      // Неактивная сеть - пустой серый круг
                      <div className="w-6 h-6 rounded-full border-2 border-gray-600"></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 NetworkSelectModal;
