import { useState, useEffect, useCallback, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useWallet } from '../context/WalletContext';
import TokenSelectModal from '../components/TokenSelectModal';
import walletAPI from '../api/wallet';

// Маппинг символа токена на иконку (для основных блоков)
const getMainTokenIcon = (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',
  'OKB': '/coins/okb.png',
  'BCH': '/coins/bch.png',
  'TAO': '/coins/tao.png',
  'SKR': '/coins/skr.png',
  'TORN': '/coins/torn.png',
  'NFLXON': '/coins/nflxon.png',
  'NVDAON': '/coins/nvdaon.png',
  'AAPL': '/coins/aapl.jpg',
  'TSLA': '/coins/tsla.png',
  'MSFT': '/coins/msft.png',
  'AMZN': '/coins/amzn.png',
  'ENSO': '/coins/enso.jpg'
  };
  return tokenIcons[symbol] || '/coins/eth.png';
};

// Маппинг названия сети на иконку (для заголовков блоков)
const getNetworkIcon = (networkName) => {
  const networkIcons = {
    'Tron': '/coins/trx.png',
    'Bitcoin': '/coins/btc.png',
    'Ethereum': '/coins/eth.png',
    'BNB Smart Chain': '/coins/bnb.png',
    'Binance Smart Chain': '/coins/cake.png',
    'Solana': '/coins/sol.png',
    'The Open Network': '/coins/ton.png',
    'TON': '/coins/not.png',
    'Ripple': '/coins/xrp.png',
    'Dogecoin': '/coins/doge.png',
    'Cardano': '/coins/ada.png',
    'Polkadot': '/coins/dot.png',
    'Zcash': '/coins/zec.png',
    'Stellar': '/coins/xlm.png',
    'Hyperliquid': '/coins/hype.png',
    'NEAR Protocol': '/coins/near.png',
    'Cosmos': '/coins/atom.png',
    'Dash': '/coins/dash.png',
    'Hedera': '/coins/hbar.jpg',
    'Litecoin': '/coins/ltc.png',
    'Aptos': '/coins/apt.png',
    'Sui': '/coins/sui.png',
    'Avalanche': '/coins/avax.png',
    'Aster': '/coins/aster.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',
  'Ethereum Classic': '/coins/etc.png',
  'Vameon': '/coins/von.jpg',
  'zkSync': '/coins/zk.png',
  'Bitcoin Cash': '/coins/bch.png',
  'Bittensor': '/coins/tao.png'
  };
  return networkIcons[networkName] || '/coins/eth.png';
};

const SwapPage = () => {
  const navigate = useNavigate();
  const { activeWallet, sessionLogin, refreshSession } = useWallet();

  const [fromToken, setFromToken] = useState({
    symbol: 'USDT',
    name: 'Tron',
    balance: '0'
  });

  const [toToken, setToToken] = useState({
    symbol: 'DOGE',
    name: 'Dogecoin',
    balance: '0'
  });

  const [fromAmount, setFromAmount] = useState('');
  const [toAmount, setToAmount] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const [infoMessage, setInfoMessage] = useState('');
  const [pendingSwap, setPendingSwap] = useState(null);
  const pendingSwapRef = useRef(null);

  // Состояния для модальных окон выбора токенов
  const [showFromTokenModal, setShowFromTokenModal] = useState(false);
  const [showToTokenModal, setShowToTokenModal] = useState(false);

  // Получаем данные токена из кошелька
  const getTokenData = (symbol) => {
    if (!activeWallet?.tokens) return null;
    return activeWallet.tokens.find(t => t.tokenInfo?.symbol === symbol);
  };

  // Получаем баланс токена
  const getTokenBalance = (symbol) => {
    const tokenData = getTokenData(symbol);
    return tokenData ? (parseFloat(tokenData.balance) || 0).toFixed(6) : '0.000000';
  };

  // Получаем цену токена
  const getTokenPrice = (symbol) => {
    const tokenData = getTokenData(symbol);
    return tokenData ? (parseFloat(tokenData.tokenInfo?.price) || 0) : 0;
  };

  // Рассчитываем стоимость в долларах
  const calculateUsdValue = (amount, symbol) => {
    if (!amount || isNaN(amount)) return '0,00';
    const price = getTokenPrice(symbol);
    const value = parseFloat(amount) * price;
    return value.toFixed(2).replace('.', ',');
  };

  // Функция для переключения монет местами
  const handleSwapTokens = () => {
    const temp = fromToken;
    setFromToken(toToken);
    setToToken(temp);
    
    const tempAmount = fromAmount;
    setFromAmount(toAmount);
    setToAmount(tempAmount);
  };

  // Обработчик выбора токена "из"
  const handleFromTokenSelect = (token) => {
    setFromToken({
      symbol: token.symbol,
      name: token.network,
      balance: getTokenBalance(token.symbol)
    });
  };

  // Обработчик выбора токена "в"
  const handleToTokenSelect = (token) => {
    setToToken({
      symbol: token.symbol,
      name: token.network,
      balance: getTokenBalance(token.symbol)
    });
  };

  // Автоматический расчет суммы обмена при изменении fromAmount
  useEffect(() => {
    if (!fromAmount || isNaN(fromAmount) || parseFloat(fromAmount) <= 0) {
      setToAmount('');
      return;
    }

    const fromPrice = getTokenPrice(fromToken.symbol);
    const toPrice = getTokenPrice(toToken.symbol);

    if (fromPrice > 0 && toPrice > 0) {
      // Рассчитываем сумму в USD
      const usdValue = parseFloat(fromAmount) * fromPrice;
      // Конвертируем в токен назначения
      const calculatedAmount = usdValue / toPrice;
      // Вычитаем комиссию 3%
      const amountAfterFee = calculatedAmount * 0.97;
      // Округляем до 6 знаков после запятой
      setToAmount(amountAfterFee.toFixed(6));
    } else {
      setToAmount('0');
    }
  }, [fromAmount, fromToken.symbol, toToken.symbol]);

  const fetchPendingSwap = useCallback(async () => {
    if (!sessionLogin) return;
    try {
      const response = await walletAPI.getPendingSwaps(sessionLogin);
      const newPending = response.success && Array.isArray(response.data) && response.data.length > 0
        ? response.data[0]
        : null;
      const hadPending = !!pendingSwapRef.current;
      pendingSwapRef.current = newPending;
      setPendingSwap(newPending);

      if (newPending) {
        setInfoMessage('Зачисление произойдёт в течение нескольких минут.');
      } else if (hadPending) {
        setInfoMessage('Обмен завершён. Баланс обновлён.');
        await refreshSession();
      }
    } catch (error) {
      console.error('Failed to load pending swaps:', error);
    }
  }, [sessionLogin, refreshSession]);

  useEffect(() => {
    fetchPendingSwap();
  }, [fetchPendingSwap]);

  useEffect(() => {
    if (!pendingSwap) return undefined;
    const intervalId = setInterval(() => {
      fetchPendingSwap();
    }, 5000);
    return () => clearInterval(intervalId);
  }, [pendingSwap, fetchPendingSwap]);

  useEffect(() => {
    if (!activeWallet?.tokens) return;
    setFromToken((prev) => ({
      ...prev,
      balance: getTokenBalance(prev.symbol),
    }));
    setToToken((prev) => ({
      ...prev,
      balance: getTokenBalance(prev.symbol),
    }));
  }, [activeWallet]);

  const handleAmountChange = (event) => {
    const raw = event.target.value.replace(',', '.');
    if (raw === '' || /^[0-9]*\.?[0-9]*$/.test(raw)) {
      setFromAmount(raw);
    }
  };

  const handleExecuteSwap = async () => {
    if (!sessionLogin) {
      setErrorMessage('Сессия недействительна. Перезайдите и попробуйте снова.');
      return;
    }
    if (!fromAmount || parseFloat(fromAmount) <= 0) {
      setErrorMessage('Введите сумму обмена');
      return;
    }
    if (pendingSwap) {
      setErrorMessage('Дождитесь завершения текущего обмена');
      return;
    }

    try {
      setIsSubmitting(true);
      setErrorMessage('');
      setInfoMessage('');

      const response = await walletAPI.executeSwap({
        sessionLogin,
        fromSymbol: fromToken.symbol,
        toSymbol: toToken.symbol,
        amount: parseFloat(fromAmount),
      });

      if (!response.success) {
        throw new Error(response.error || 'Не удалось выполнить обмен');
      }

      pendingSwapRef.current = response.data;
      setPendingSwap(response.data);
      setInfoMessage('Зачисление произойдёт в течение нескольких минут.');
      setFromAmount('');
      setToAmount('');
      fetchPendingSwap();
      refreshSession();
    } catch (error) {
      const message = error?.response?.data?.error || error.message || 'Не удалось выполнить обмен';
      setErrorMessage(message);
    } finally {
      setIsSubmitting(false);
    }
  };

  const isButtonDisabled = !fromAmount || !toAmount || isSubmitting || Boolean(pendingSwap);

  return (
    <div className="min-h-screen bg-[#1b1b1c] pb-20">
      {/* Header */}
      <div className="sticky top-0 z-10 bg-[#1b1b1c] border-b border-gray-800">
        <div className="max-w-2xl mx-auto flex items-center p-4">
          <button
            onClick={() => navigate(-1)}
            className="p-2 -ml-2 text-white"
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
          </button>
          <h1 className="flex-1 text-lg font-semibold text-white text-center mr-8">
            Обмен
          </h1>
        </div>
      </div>

      {/* Swap Content */}
      <div className="max-w-[400px] mx-auto px-4 py-4">
        {pendingSwap && (
          <div className="bg-yellow-500/10 border border-yellow-500/30 rounded-xl p-3 mb-4 text-yellow-200 text-sm">
            <p className="font-semibold">Обмен выполняется...</p>
            <p className="mt-1">
              Зачисление {pendingSwap.toAmount} {pendingSwap.toSymbol} произойдёт в течение нескольких минут.
            </p>
          </div>
        )}

        {!pendingSwap && infoMessage && (
          <div className="bg-emerald-500/10 border border-emerald-500/30 rounded-xl p-3 mb-4 text-emerald-200 text-sm">
            {infoMessage}
          </div>
        )}

        {errorMessage && (
          <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-3 mb-4 text-red-200 text-sm">
            {errorMessage}
          </div>
        )}

        {/* From Token Block */}
        <div className="bg-gray-800/30 rounded-xl">
          <div className="flex flex-col space-y-3 p-4">
            {/* Header */}
            <div className="flex items-center justify-between">
              {/* Network selector */}
              <div className="flex items-center space-x-1">
                <span className="text-gray-400 text-xs font-normal">С</span>
                <div className="flex items-center">
                  <div className="w-4 h-4 rounded-full overflow-hidden flex-shrink-0">
                    <img 
                      src={getNetworkIcon(fromToken.name)} 
                      alt={fromToken.name}
                      className="w-full h-full object-contain"
                    />
                  </div>
                  <span className="ml-1 text-gray-400 text-xs font-medium">{fromToken.name}</span>
                </div>
              </div>
              {/* Balance */}
              <div className="flex items-center">
                <svg className="text-gray-400" fill="none" width="16" height="16" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" style={{ paddingLeft: '1px' }}>
                  <path d="M16.495 4.75012H4.995C4.375 4.75012 3.875 5.25012 3.875 5.87012C3.875 6.49012 4.375 6.99012 4.995 6.99012H16.495C16.985 6.99012 17.375 7.38012 17.375 7.87012V16.1101C17.375 16.6001 16.975 16.9901 16.495 16.9901H3.505C3.015 16.9901 2.625 16.5901 2.625 16.1101V3.87012C2.625 3.39012 3.015 2.99012 3.495 2.99012H16.495C17.115 2.99012 17.615 2.49012 17.615 1.87012C17.615 1.25012 17.115 0.750122 16.495 0.750122H3.495C1.775 0.750122 0.375 2.15012 0.375 3.87012V16.1101C0.375 17.8401 1.785 19.2401 3.505 19.2401H16.495C18.225 19.2401 19.625 17.8401 19.625 16.1101V7.87012C19.625 6.15012 18.215 4.75012 16.495 4.75012Z" fill="currentColor" />
                  <path d="M14.6249 12.5001C15.2449 12.5001 15.7449 12.0001 15.7449 11.3801C15.7449 10.7601 15.2449 10.2601 14.6249 10.2601H12.3749C11.7549 10.2601 11.2549 10.7601 11.2549 11.3801C11.2549 12.0001 11.7549 12.5001 12.3749 12.5001H14.6249Z" fill="currentColor" />
                </svg>
                <span className="ml-1 text-gray-400 text-xs font-normal">{getTokenBalance(fromToken.symbol)}</span>
              </div>
            </div>

            {/* Token and Amount */}
            <div className="flex items-center justify-between space-x-2">
              {/* Token info */}
              <div className="flex items-center space-x-2.5">
                <div className="w-10 h-10 rounded-full overflow-hidden flex-shrink-0">
                  <img 
                    src={getMainTokenIcon(fromToken.symbol)} 
                    alt={fromToken.symbol}
                    className="w-full h-full object-contain"
                  />
                </div>
                <button
                  className="outline-none cursor-pointer"
                  onClick={() => setShowFromTokenModal(true)}
                >
                  <div className="flex items-center space-x-1">
                    <span className="text-white text-lg font-semibold">{fromToken.symbol}</span>
                    <svg className="text-gray-400" fill="none" width="20" height="20" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                      <path fillRule="evenodd" clipRule="evenodd" d="M7.89784 4.3613C8.53455 3.84231 9.47374 3.87891 10.0672 4.47213L16.0703 10.4752L16.2183 10.6387C16.862 11.4278 16.8618 12.5676 16.2183 13.3568L16.0703 13.5203L10.0672 19.5234C9.47365 20.1167 8.53456 20.1534 7.89784 19.6342L7.77429 19.5234C7.14124 18.8903 7.1414 17.8636 7.77429 17.2304L13.007 11.9977L7.77429 6.76507C7.14142 6.13189 7.14125 5.10521 7.77429 4.47213L7.89784 4.3613Z" fill="currentColor" />
                    </svg>
                  </div>
                </button>
              </div>

              {/* Amount input */}
              <div className="flex flex-col w-full items-end space-y-1 overflow-hidden">
                <input
                  type="text"
                  value={fromAmount}
                  onChange={handleAmountChange}
                  placeholder="0"
                  className="w-full h-8 text-right p-0 border-0 outline-none bg-transparent text-3xl font-semibold text-white"
                  spellCheck="false"
                />
                <span className="text-gray-400 text-xs font-normal">{calculateUsdValue(fromAmount, fromToken.symbol)} $</span>
              </div>
            </div>
          </div>
        </div>

        {/* Swap Button */}
        <div className="relative z-0 flex w-10 h-10 -my-3 mx-auto rounded-full bg-[#1b1b1c]">
          <button
            onClick={handleSwapTokens}
            className="outline-none bg-transparent text-white w-full p-0 rounded-full hover:bg-[#2a2a2c] transition-colors"
          >
            <svg className="text-gray-400 hover:text-[#2ea169] transition mx-auto" fill="none" width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <path fillRule="evenodd" clipRule="evenodd" d="M8.89207 2.36553C9.32215 1.99561 9.92743 1.8958 10.4575 2.1151L10.561 2.16248C11.0676 2.41828 11.3924 2.93931 11.3925 3.51326V20.4865C11.3925 21.3223 10.7142 21.9997 9.87832 21.9997C9.04279 21.9993 8.3651 21.3221 8.3651 20.4865V7.16722L5.29128 10.241C4.73724 10.7949 3.86 10.8301 3.2656 10.3455L3.15053 10.241C2.55994 9.65 2.55976 8.69122 3.15053 8.1003L8.80794 2.44289L8.89207 2.36553Z" fill="currentColor" />
              <path fillRule="evenodd" clipRule="evenodd" d="M14.1221 2.00004C14.9578 2.00014 15.6352 2.67755 15.6353 3.51326V16.8325L18.7091 13.7587L18.8242 13.6542C19.4185 13.1695 20.2958 13.2049 20.8499 13.7587L20.9533 13.8737C21.406 14.4287 21.4062 15.2295 20.9533 15.7844L20.8499 15.8994L15.1925 21.5568C14.7866 21.9626 14.1884 22.1017 13.6493 21.9243L13.5429 21.8846C12.9776 21.6502 12.6089 21.0985 12.6089 20.4865V3.51326C12.609 2.67764 13.2865 2.00029 14.1221 2.00004Z" fill="currentColor" />
            </svg>
          </button>
        </div>

        {/* To Token Block */}
        <div className="bg-gray-800/30 rounded-xl">
          <div className="flex flex-col space-y-3 p-4">
            {/* Header */}
            <div className="flex items-center justify-between">
              {/* Network selector */}
              <div className="flex items-center space-x-1">
                <span className="text-gray-400 text-xs font-normal">На</span>
                <div className="flex items-center">
                  <div className="w-4 h-4 rounded-full overflow-hidden flex-shrink-0">
                    <img 
                      src={getNetworkIcon(toToken.name)} 
                      alt={toToken.name}
                      className="w-full h-full object-contain"
                    />
                  </div>
                  <span className="ml-1 text-gray-400 text-xs font-medium">{toToken.name}</span>
                </div>
              </div>
            </div>

            {/* Token and Amount */}
            <div className="flex items-center justify-between space-x-2">
              {/* Token info */}
              <div className="flex items-center space-x-2.5">
                <div className="w-10 h-10 rounded-full overflow-hidden flex-shrink-0">
                  <img 
                    src={getMainTokenIcon(toToken.symbol)} 
                    alt={toToken.symbol}
                    className="w-full h-full object-contain"
                  />
                </div>
                <button
                  className="outline-none cursor-pointer"
                  onClick={() => setShowToTokenModal(true)}
                >
                  <div className="flex items-center space-x-1">
                    <span className="text-white text-lg font-semibold">{toToken.symbol}</span>
                    <svg className="text-gray-400" fill="none" width="20" height="20" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                      <path fillRule="evenodd" clipRule="evenodd" d="M7.89784 4.3613C8.53455 3.84231 9.47374 3.87891 10.0672 4.47213L16.0703 10.4752L16.2183 10.6387C16.862 11.4278 16.8618 12.5676 16.2183 13.3568L16.0703 13.5203L10.0672 19.5234C9.47365 20.1167 8.53456 20.1534 7.89784 19.6342L7.77429 19.5234C7.14124 18.8903 7.1414 17.8636 7.77429 17.2304L13.007 11.9977L7.77429 6.76507C7.14142 6.13189 7.14125 5.10521 7.77429 4.47213L7.89784 4.3613Z" fill="currentColor" />
                    </svg>
                  </div>
                </button>
              </div>

              {/* Amount display */}
              <div className="flex text-end">
                <span className="text-white text-3xl font-semibold">{toAmount || '0'}</span>
              </div>
            </div>
          </div>
        </div>

      </div>

      {/* Continue Button */}
      <div className="fixed bottom-0 left-0 right-0 p-4 bg-[#1b1b1c] border-t border-gray-800">
        <div className="max-w-[400px] mx-auto">
          <button
            className="w-full bg-[#2ea169] text-white text-base font-semibold py-3.5 rounded-xl hover:bg-[#26895a] transition-colors disabled:bg-gray-700 disabled:text-gray-500 disabled:cursor-not-allowed"
            disabled={isButtonDisabled}
            onClick={handleExecuteSwap}
          >
            {pendingSwap ? 'Ожидание зачисления' : isSubmitting ? 'Обмен...' : 'Обменять'}
          </button>
        </div>
      </div>

      {/* Token Select Modals */}
      <TokenSelectModal
        isOpen={showFromTokenModal}
        onClose={() => setShowFromTokenModal(false)}
        onSelect={handleFromTokenSelect}
        excludeToken={toToken.symbol}
      />

      <TokenSelectModal
        isOpen={showToTokenModal}
        onClose={() => setShowToTokenModal(false)}
        onSelect={handleToTokenSelect}
        excludeToken={fromToken.symbol}
      />
    </div>
  );
};

export default SwapPage;
