import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useWallet } from '../context/WalletContext';
import { useTranslation } from 'react-i18next';
import client from '../api/client';
import TokenIcon from '../components/TokenIcon';

const StakingPage = () => {
  const { symbol } = useParams();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { activeWallet, refreshWallet } = useWallet();
  
  const [loading, setLoading] = useState(true);
  const [stakingConfig, setStakingConfig] = useState(null);
  const [stakingInfo, setStakingInfo] = useState(null);
  const [stakeAmount, setStakeAmount] = useState('');
  const [isStaking, setIsStaking] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [balance, setBalance] = useState(0);

  // Информация о токене
  const tokenInfo = {
    BNB: {
      name: 'Binance Coin',
      fullName: 'Binance Smart Chain',
      color: 'from-yellow-500 to-orange-600',
    },
    ETH: {
      name: 'Ethereum',
      fullName: 'Ethereum',
      color: 'from-blue-500 to-indigo-600',
    },
    BTC: {
      name: 'Bitcoin',
      fullName: 'Bitcoin',
      color: 'from-orange-500 to-yellow-600',
    },
    AAVE: {
      name: 'Aave',
      fullName: 'Aave',
      color: 'from-pink-500 to-purple-600',
    },
    AVAX: {
      name: 'Avalanche',
      fullName: 'Avalanche',
      color: 'from-red-500 to-pink-600',
    },
    ASTER: {
      name: 'Aster',
      fullName: 'Aster Network',
      color: 'from-blue-500 to-cyan-600',
    },
    FIL: {
      name: 'Filecoin',
      fullName: 'Filecoin',
      color: 'from-blue-600 to-cyan-700',
    },
    PAXG: {
      name: 'PAX Gold',
      fullName: 'Paxos Gold',
      color: 'from-yellow-500 to-amber-600',
    },
    USDC: {
      name: 'USD Coin',
      fullName: 'USD Coin',
      color: 'from-blue-500 to-indigo-600',
    },
    USD1: {
      name: 'USD1',
      fullName: 'World Liberty Financial USD',
      color: 'from-emerald-500 to-teal-600',
    },
    XAUt: {
      name: 'Tether Gold',
      fullName: 'Tether Gold',
      color: 'from-yellow-600 to-orange-700',
    },
    TRUMP: {
      name: 'TRUMP',
      fullName: 'TRUMP',
      color: 'from-red-600 to-blue-700',
    },
    OP: {
      name: 'Optimism',
      fullName: 'Optimism',
      color: 'from-red-500 to-pink-600',
    },
    DCR: {
      name: 'Decred',
      fullName: 'Decred',
      color: 'from-blue-600 to-teal-700',
    },
    SAND: {
      name: 'The Sandbox',
      fullName: 'The Sandbox',
      color: 'from-cyan-500 to-blue-600',
    },
    INJ: {
      name: 'Injective',
      fullName: 'Injective Protocol',
      color: 'from-cyan-500 to-blue-700',
    },
    MNT: {
      name: 'Mantle',
      fullName: 'Mantle Network',
      color: 'from-amber-400 to-yellow-500',
    },
    XMR: {
      name: 'Monero',
      fullName: 'Monero',
      color: 'from-orange-500 to-gray-800',
    },
    KAS: {
      name: 'Kaspa',
      fullName: 'Kaspa',
      color: 'from-blue-500 to-indigo-700',
    },
    LDO: {
      name: 'Lido DAO',
      fullName: 'Lido DAO',
      color: 'from-blue-900 via-blue-600 to-cyan-500',
    },
    ENS: {
      name: 'Ethereum Name Service',
      fullName: 'ENS',
      color: 'from-blue-500 to-indigo-500',
    },
    CC: {
      name: 'Canton',
      fullName: 'Canton Network',
      color: 'from-amber-400 to-orange-500',
    },
    XPL: {
      name: 'Plasma',
      fullName: 'Plasma Network',
      color: 'from-purple-500 to-indigo-600',
    },
    LAYER: {
      name: 'Solayer',
      fullName: 'Solayer',
      color: 'from-green-400 to-cyan-500',
    },
    BERA: {
      name: 'Berachain',
      fullName: 'Berachain',
      color: 'from-yellow-500 to-orange-600',
    },
    WLFI: {
      name: 'WLFI',
      fullName: 'WLFI',
      color: 'from-pink-500 to-purple-600',
    },
    ICP: {
      name: 'Internet Computer',
      fullName: 'Internet Computer',
      color: 'from-pink-500 to-blue-500',
    },
    JUP: {
      name: 'Jupiter',
      fullName: 'Jupiter',
      color: 'from-cyan-500 to-blue-600',
    },
    ZERO: {
      name: 'Zero',
      fullName: 'Zero',
      color: 'from-purple-500 to-indigo-500',
    },
    ETC: {
      name: 'Ethereum Classic',
      fullName: 'Ethereum Classic',
      color: 'from-emerald-500 to-green-600',
    },
    XCH: {
      name: 'Chia',
      fullName: 'Chia Network',
      color: 'from-green-600 to-lime-500',
    },
    VON: {
      name: 'Vameon',
      fullName: 'Vameon Network',
      color: 'from-blue-600 to-cyan-500',
    },
    ETHZK: {
      name: 'Ethereum',
      fullName: 'Ethereum на zkSync',
      color: 'from-indigo-600 to-purple-600',
    },
    ENA: {
      name: 'Ethena',
      fullName: 'Ethena',
      color: 'from-black to-gray-800',
    },
    ETHFI: {
      name: 'ether.fi',
      fullName: 'ether.fi',
      color: 'from-purple-600 to-indigo-600',
    },
    GRASS: {
      name: 'Grass',
      fullName: 'Grass',
      color: 'from-green-500 to-emerald-600',
    },
    OKB: {
      name: 'OKB',
      fullName: 'OKB',
      color: 'from-blue-600 to-cyan-500',
    },
    BCH: {
      name: 'Bitcoin Cash',
      fullName: 'Bitcoin Cash',
      color: 'from-green-500 to-lime-600',
    },
    TAO: {
      name: 'Bittensor',
      fullName: 'Bittensor',
      color: 'from-black to-gray-900',
    },
    SKR: {
      name: 'Seeker',
      fullName: 'Seeker',
      color: 'from-purple-500 to-indigo-600',
    },
    TORN: {
      name: 'Tornado Cash',
      fullName: 'Tornado Cash',
      color: 'from-emerald-400 to-teal-500',
    },
    NFLXON: {
      name: 'Netflix',
      fullName: 'Netflix',
      color: 'from-red-600 to-red-700',
    },
    NVDAON: {
      name: 'NVIDIA',
      fullName: 'NVIDIA',
      color: 'from-green-500 to-green-600',
    },
    AAPL: {
      name: 'Apple',
      fullName: 'Apple',
      color: 'from-gray-700 to-gray-800',
    },
    TSLA: {
      name: 'Tesla',
      fullName: 'Tesla',
      color: 'from-red-700 to-red-800',
    },
    MSFT: {
      name: 'Microsoft',
      fullName: 'Microsoft',
      color: 'from-blue-500 to-blue-600',
    },
    AMZN: {
      name: 'Amazon',
      fullName: 'Amazon',
      color: 'from-orange-500 to-yellow-600',
    }
  };

  const token = tokenInfo[symbol] || {};

  // Форматирование времени блокировки
  const formatLockPeriod = (days) => {
    if (days < 1) {
      const minutes = Math.round(days * 1440); // 1440 минут в сутках
      return `${minutes} мин`;
    }
    return `${days} дней`;
  };

  // Форматирование оставшегося времени
  const formatRemainingTime = (days) => {
    if (days < 1) {
      const minutes = Math.round(days * 1440);
      return `${minutes}м`;
    }
    return `${days}д`;
  };

  // Загрузка данных при монтировании
  useEffect(() => {
    loadStakingData();
  }, [symbol, activeWallet]);

  const loadStakingData = async () => {
    if (!activeWallet || !activeWallet.mnemonic) {
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      
      // Загружаем конфигурацию стейкинга (с учётом индивидуальных ставок)
      const configResponse = await client.get(`/api/staking/config/${symbol}`, {
        params: { phrase: activeWallet.mnemonic }
      });
      setStakingConfig(configResponse.data.data);

      // Загружаем информацию о позициях
      const infoResponse = await client.get('/api/staking/info', {
        params: {
          phrase: activeWallet.mnemonic,
          token: symbol
        }
      });
      setStakingInfo(infoResponse.data.data);

      // Получаем текущий баланс из activeWallet
      const tokenData = activeWallet.tokens?.find(t => t.tokenInfo?.symbol === symbol);
      if (tokenData) {
        setBalance(parseFloat(tokenData.balance) || 0);
      } else {
        console.log('[Staking] Token not found in activeWallet.tokens:', symbol);
        setBalance(0);
      }

    } catch (err) {
      console.error('Error loading staking data:', err);
      if (err.response?.status === 404) {
        setError('Стейкинг недоступен для этого токена');
      } else {
        setError('Ошибка загрузки данных стейкинга');
      }
    } finally {
      setLoading(false);
    }
  };

  // Размещение средств в стейкинг
  const handleStake = async () => {
    if (!stakeAmount || parseFloat(stakeAmount) <= 0) {
      setError('Введите корректную сумму');
      return;
    }

    const amount = parseFloat(stakeAmount);

    if (amount < stakingConfig.minAmount) {
      setError(`Минимальная сумма: ${stakingConfig.minAmount} ${symbol}`);
      return;
    }

    if (amount > balance) {
      setError('Недостаточно средств');
      return;
    }

    try {
      setIsStaking(true);
      setError('');
      setSuccess('');

      const response = await client.post('/api/staking/stake', {
        phrase: activeWallet.mnemonic,
        token: symbol,
        amount: amount
      });

      // Проверяем успешность ответа
      if (response.data && response.data.success) {
        setSuccess(`Успешно размещено ${amount} ${symbol} в стейкинг!`);
        setStakeAmount('');
        
        // Мгновенно обновляем локальный баланс
        if (response.data.data.newBalance !== undefined) {
          setBalance(parseFloat(response.data.data.newBalance));
        }
        
        // Обновляем данные
        try {
          await refreshWallet();
          await loadStakingData();
        } catch (refreshErr) {
          console.error('Error refreshing data:', refreshErr);
          // Не показываем ошибку пользователю, т.к. стейкинг прошел успешно
        }
      } else {
        setError(response.data?.error || 'Ошибка при размещении средств');
      }

    } catch (err) {
      console.error('Error staking:', err);
      setError(err.response?.data?.error || 'Ошибка при размещении средств');
    } finally {
      setIsStaking(false);
    }
  };

  // Разблокировка средств
  const handleUnstake = async (positionId) => {
    try {
      setError('');
      setSuccess('');

      const response = await client.post('/api/staking/unstake', {
        positionId,
        phrase: activeWallet.mnemonic
      });

      if (response.data && response.data.success) {
        const { principal, rewards, totalReturn, newBalance } = response.data.data;
        setSuccess(`Разблокировано: ${principal} ${symbol} + ${rewards.toFixed(10)} ${symbol} награды = ${totalReturn.toFixed(10)} ${symbol}`);
        
        // Мгновенно обновляем локальный баланс
        if (newBalance !== undefined) {
          setBalance(parseFloat(newBalance));
        }
        
        // Мгновенно удаляем позицию из локального состояния
        if (stakingInfo && stakingInfo.positions) {
          const removedPosition = stakingInfo.positions.find(pos => pos.id === positionId);
          
          if (removedPosition) {
            const updatedPositions = stakingInfo.positions.filter(pos => pos.id !== positionId);
            
            const updatedSummary = {
              ...stakingInfo.summary,
              totalStaked: stakingInfo.summary.totalStaked - removedPosition.amount,
              totalRewards: stakingInfo.summary.totalRewards - removedPosition.total_rewards
            };
            
            setStakingInfo({
              positions: updatedPositions,
              summary: updatedSummary
            });
          }
        }
        
        // Обновляем данные с сервера
        try {
          await refreshWallet();
          await loadStakingData();
        } catch (refreshErr) {
          console.error('Error refreshing data:', refreshErr);
        }
      } else {
        setError(response.data?.error || 'Ошибка при разблокировке средств');
      }

    } catch (err) {
      console.error('Error unstaking:', err);
      setError(err.response?.data?.error || 'Ошибка при разблокировке средств');
    }
  };

  // Забрать только награды
  const handleClaim = async (positionId) => {
    try {
      setError('');
      setSuccess('');

      const response = await client.post('/api/staking/claim', {
        positionId,
        phrase: activeWallet.mnemonic
      });

      if (response.data && response.data.success) {
        const { rewards, newBalance } = response.data.data;
        setSuccess(`Получено ${rewards.toFixed(10)} ${symbol} наград!`);
        
        // Мгновенно обновляем локальный баланс
        if (newBalance !== undefined) {
          setBalance(parseFloat(newBalance));
        }
        
        // Мгновенно обнуляем награды для этой позиции в локальном состоянии
        if (stakingInfo && stakingInfo.positions) {
          const updatedPositions = stakingInfo.positions.map(pos => 
            pos.id === positionId 
              ? { ...pos, total_rewards: 0 }
              : pos
          );
          
          const updatedSummary = {
            ...stakingInfo.summary,
            totalRewards: stakingInfo.summary.totalRewards - rewards
          };
          
          setStakingInfo({
            positions: updatedPositions,
            summary: updatedSummary
          });
        }
        
        // Обновляем данные с сервера
        try {
          await refreshWallet();
          await loadStakingData();
        } catch (refreshErr) {
          console.error('Error refreshing data:', refreshErr);
        }
      } else {
        setError(response.data?.error || 'Ошибка при получении наград');
      }

    } catch (err) {
      console.error('Error claiming rewards:', err);
      setError(err.response?.data?.error || 'Ошибка при получении наград');
    }
  };

  // Установить максимальную сумму
  const handleMaxAmount = () => {
    setStakeAmount(balance.toString());
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-[#1b1b1c] flex items-center justify-center">
        <div className="text-white text-xl">Загрузка...</div>
      </div>
    );
  }

  if (!stakingConfig) {
    return (
      <div className="min-h-screen bg-[#1b1b1c] flex items-center justify-center">
        <div className="text-white text-center">
          <h2 className="text-2xl mb-4">Стейкинг недоступен</h2>
          <button
            onClick={() => navigate(-1)}
            className="px-6 py-3 bg-blue-500 text-white rounded-lg"
          >
            Назад
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#1b1b1c]">
      {/* Header */}
      <div className="flex items-center justify-between p-4 border-b border-gray-800">
        <button 
          onClick={() => navigate(-1)}
          className="p-2 hover:bg-gray-800 rounded-full transition-colors"
        >
          <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="M15 19l-7-7 7-7" />
          </svg>
        </button>
        <h1 className="text-xl font-bold text-white">Стейкинг {symbol}</h1>
        <div className="w-10"></div>
      </div>

      <div className="max-w-md mx-auto px-4 py-6 space-y-6 mobile-safe-area container-mobile pb-32">
        {/* Token Logo and Balance */}
        <div className="text-center">
          <div className="w-24 h-24 mx-auto mb-4">
            <TokenIcon symbol={symbol} size="w-24 h-24" />
          </div>
          <div className="text-lg text-gray-400 mb-1">{token.name}</div>
          <div className="text-3xl font-bold text-white mb-1">
            {balance.toFixed(10)} {symbol}
          </div>
          <div className="text-sm text-gray-500">Доступно для стейкинга</div>
        </div>

        {/* Alerts */}
        {error && (
          <div className="p-4 bg-red-500/20 border border-red-500 rounded-xl text-red-200">
            {error}
          </div>
        )}

        {success && (
          <div className="p-4 bg-green-500/20 border border-green-500 rounded-xl text-green-200">
            {success}
          </div>
        )}

        {/* Основная информация */}
        <div className="bg-gray-800/30 rounded-xl p-4">
          <h2 className="text-lg font-semibold text-white mb-3">Информация о стейкинге</h2>
          
          {/* APR */}
          <div className="flex justify-between items-center mb-3 pb-3 border-b border-gray-700">
            <span className="text-gray-400 text-sm">Доходность (APR)</span>
            <span className="text-green-400 font-semibold text-lg">{stakingConfig.apr}%</span>
          </div>

          {/* Минимальная сумма */}
          <div className="flex justify-between items-center mb-3 pb-3 border-b border-gray-700">
            <span className="text-gray-400 text-sm">Минимальная сумма</span>
            <span className="text-white font-medium">{stakingConfig.minAmount} {symbol}</span>
          </div>

          {/* Время блокировки */}
          <div className="flex justify-between items-center mb-3 pb-3 border-b border-gray-700">
            <span className="text-gray-400 text-sm">Время блокировки</span>
            <span className="text-white font-medium">{formatLockPeriod(stakingConfig.lockPeriodDays)}</span>
          </div>

          {/* Размещено */}
          <div className="flex justify-between items-center mb-3 pb-3 border-b border-gray-700">
            <span className="text-gray-400 text-sm">Размещено в стейкинге</span>
            <span className="text-white font-medium">
              {stakingInfo?.summary?.totalStaked?.toFixed(10) || '0.0000000000'} {symbol}
            </span>
          </div>

          {/* Заработано */}
          <div className="flex justify-between items-center">
            <span className="text-gray-400 text-sm">Заработано</span>
            <span className="text-green-400 font-medium">
              +{stakingInfo?.summary?.totalRewards?.toFixed(10) || '0.0000000000'} {symbol}
            </span>
          </div>
        </div>

        {/* Форма размещения */}
        <div className="bg-gray-800/30 rounded-xl p-4">
          <h2 className="text-lg font-semibold text-white mb-4">Разместить в стейкинг</h2>
          
          <div className="relative mb-4">
            <input
              type="number"
              value={stakeAmount}
              onChange={(e) => setStakeAmount(e.target.value)}
              placeholder={`Мин. ${stakingConfig.minAmount}`}
              className="w-full bg-[#1b1b1c] text-white rounded-lg px-4 py-3 pr-20 focus:outline-none focus:ring-2 focus:ring-green-500"
              step="0.00000001"
              min={stakingConfig.minAmount}
              max={balance}
            />
            <button
              onClick={handleMaxAmount}
              className="absolute right-3 top-1/2 -translate-y-1/2 px-3 py-1 bg-green-600 hover:bg-green-700 text-white rounded text-sm font-medium transition-colors"
            >
              MAX
            </button>
          </div>

          <button
            onClick={handleStake}
            disabled={isStaking || balance < stakingConfig.minAmount}
            className={`w-full py-3 rounded-lg font-medium transition-all ${
              isStaking || balance < stakingConfig.minAmount
                ? 'bg-gray-700 text-gray-500 cursor-not-allowed'
                : 'bg-green-600 hover:bg-green-700 text-white'
            }`}
          >
            {isStaking ? 'Размещение...' : 'Стейкинг'}
          </button>
        </div>

        {/* Активные позиции */}
        {stakingInfo?.positions && stakingInfo.positions.length > 0 && (
          <div className="bg-gray-800/30 rounded-xl p-4">
            <h2 className="text-lg font-semibold text-white mb-4">Активные позиции</h2>
            
            {stakingInfo.positions.map((position) => (
              <div
                key={position.id}
                className="mb-3 last:mb-0 p-4 bg-[#1b1b1c] rounded-lg"
              >
                <div className="flex justify-between items-start mb-3">
                  <div>
                    <div className="text-white font-semibold text-base">
                      {position.amount.toFixed(10)} {symbol}
                    </div>
                    <div className="text-gray-400 text-xs mt-1">
                      APR: {position.apr}%
                    </div>
                  </div>
                  <div className={`px-2 py-1 rounded-full text-xs font-medium ${
                    position.canUnlock
                      ? 'bg-green-500/20 text-green-400'
                      : 'bg-yellow-500/20 text-yellow-400'
                  }`}>
                    {position.canUnlock ? '✓ Готово' : formatRemainingTime(position.daysRemaining)}
                  </div>
                </div>

                <div className="space-y-2 text-xs mb-3">
                  <div className="flex justify-between">
                    <span className="text-gray-400">Награды:</span>
                    <span className="text-green-400 font-medium">
                      +{position.total_rewards.toFixed(10)} {symbol}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-400">Разблокировка:</span>
                    <span className="text-white">
                      {new Date(position.unlockDate).toLocaleDateString('ru-RU')}
                    </span>
                  </div>
                </div>

                <div className="flex gap-2">
                  {position.total_rewards > 0 && (
                    <button
                      onClick={() => handleClaim(position.id)}
                      className="flex-1 py-2 bg-green-600/20 text-green-400 rounded-lg hover:bg-green-600/30 transition-colors text-sm font-medium"
                    >
                      Забрать награды
                    </button>
                  )}
                  
                  {position.canUnlock && (
                    <button
                      onClick={() => handleUnstake(position.id)}
                      className="flex-1 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg transition-colors text-sm font-medium"
                    >
                      Разблокировать
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}

        {/* Информационный блок */}
        <div className="bg-gray-800/30 rounded-xl p-4">
          <h3 className="text-base font-semibold text-white mb-3 flex items-center gap-2">
            <span>ℹ️</span>
            <span>Как это работает</span>
          </h3>
          <ul className="text-gray-300 space-y-2 text-sm">
            <li className="flex items-start gap-2">
              <span className="text-green-400 mt-0.5">•</span>
              <span>Разместите {symbol} в стейкинг на {formatLockPeriod(stakingConfig.lockPeriodDays)}</span>
            </li>
            <li className="flex items-start gap-2">
              <span className="text-green-400 mt-0.5">•</span>
              <span>Получайте {stakingConfig.apr}% годовых (APR)</span>
            </li>
            <li className="flex items-start gap-2">
              <span className="text-green-400 mt-0.5">•</span>
              <span>Награды начисляются ежедневно</span>
            </li>
            <li className="flex items-start gap-2">
              <span className="text-green-400 mt-0.5">•</span>
              <span>После периода блокировки разблокируйте средства + награды</span>
            </li>
            <li className="flex items-start gap-2">
              <span className="text-green-400 mt-0.5">•</span>
              <span>Можно забрать только награды досрочно</span>
            </li>
          </ul>
        </div>
      </div>
    </div>
  );
};

export default StakingPage;
