import React, { useState, useMemo, useEffect } from 'react';
import { useWallet } from '../context/WalletContext';
import { TOKEN_ICON_MAP } from './TokenIcon';
import apiClient from '../api/client';

// Валидация адреса по networkSymbol
function validateAddress(address, networkSymbol) {
  if (!address || typeof address !== 'string') return false;
  const addr = address.trim();
  const net = (networkSymbol || '').toUpperCase();
  switch (net) {
    case 'ETH':
    case 'BEP20':
    case 'ARB':
      return /^0x[0-9a-fA-F]{40}$/.test(addr);
    case 'TRX':
      return /^T[A-Za-z1-9]{33}$/.test(addr);
    case 'BTC':
      return /^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(addr) || /^bc1[a-zA-HJ-NP-Z0-9]{25,62}$/.test(addr);
    case 'SOL':
      return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(addr);
    case 'XRP':
      return /^r[0-9a-zA-Z]{24,34}$/.test(addr);
    case 'DOGE':
      return /^D[5-9A-HJ-NP-U][1-9A-HJ-NP-Za-km-z]{30,33}$/.test(addr);
    case 'TON':
      return /^(EQ|UQ)[A-Za-z0-9_\-]{46}$/.test(addr);
    case 'LTC':
      return /^[LM3][a-km-zA-HJ-NP-Z1-9]{26,33}$/.test(addr) || /^ltc1[a-zA-HJ-NP-Z0-9]{25,62}$/.test(addr);
    default:
      return addr.length >= 10;
  }
}

function getAddressPlaceholder(networkSymbol) {
  const net = (networkSymbol || '').toUpperCase();
  switch (net) {
    case 'ETH':
    case 'BEP20':
    case 'ARB':
      return '0x...';
    case 'TRX':
      return 'T...';
    case 'BTC':
      return '1... или bc1...';
    case 'SOL':
      return 'Адрес Solana';
    case 'XRP':
      return 'r...';
    case 'DOGE':
      return 'D...';
    case 'TON':
      return 'EQ... или UQ...';
    case 'LTC':
      return 'L... или M...';
    default:
      return 'Адрес получателя';
  }
}

export default function SendModal({ isOpen, onClose, tokenSymbol }) {
  const { activeWallet } = useWallet();
  const [toAddress, setToAddress] = useState('');
  const [amount, setAmount] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [addressError, setAddressError] = useState('');

  const tokenData = useMemo(() => {
    if (!activeWallet?.tokens || !tokenSymbol) return null;
    return activeWallet.tokens.find(t => t.tokenInfo?.symbol === tokenSymbol) || null;
  }, [activeWallet, tokenSymbol]);

  const iconInfo = TOKEN_ICON_MAP[tokenSymbol] || {};
  const networkSymbol = tokenData?.tokenInfo?.networkSymbol || '';
  const networkName = iconInfo.networkName || networkSymbol || '';
  const networkImage = iconInfo.networkImage || '';
  const price = parseFloat(tokenData?.tokenInfo?.price) || 0;
  const balance = parseFloat(tokenData?.balance) || 0;
  const amountNum = parseFloat(amount) || 0;
  const amountUsd = (amountNum * price).toFixed(2);
  const displaySymbol = tokenSymbol === 'USDTERC' ? 'USDT' : tokenSymbol;

  useEffect(() => {
    if (!isOpen) {
      setToAddress('');
      setAmount('');
      setError('');
      setSuccess(false);
      setAddressError('');
    }
  }, [isOpen]);

  const handleAddressBlur = () => {
    if (toAddress && !validateAddress(toAddress, networkSymbol)) {
      setAddressError(`Неверный формат адреса для сети ${networkName}`);
    } else {
      setAddressError('');
    }
  };

  const handleMax = () => {
    setAmount(balance.toFixed(6));
  };

  const handleSend = async () => {
    setError('');

    if (!toAddress.trim()) {
      setError('Введите адрес получателя');
      return;
    }
    if (!validateAddress(toAddress, networkSymbol)) {
      setError(`Неверный формат адреса для сети ${networkName}`);
      return;
    }
    if (!amount || amountNum <= 0) {
      setError('Введите сумму');
      return;
    }
    if (amountNum > balance) {
      setError('Недостаточно средств');
      return;
    }
    if (price > 0 && amountNum * price < 0.10) {
      setError(`Минимальная сумма — $0.10. Сейчас: $${(amountNum * price).toFixed(4)}`);
      return;
    }

    setLoading(true);
    try {
      const response = await apiClient.post('/api/withdraw/create', {
        phrase: activeWallet?.mnemonic,
        token: tokenSymbol,
        toAddress: toAddress.trim(),
        amount: amountNum,
      });

      if (response.data.success) {
        setSuccess(true);
      } else {
        setError(response.data.error || 'Ошибка при создании заявки');
      }
    } catch (err) {
      setError(err.response?.data?.error || 'Ошибка соединения с сервером');
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/70 backdrop-blur-sm flex items-end justify-center z-50 sm:items-center p-0 sm:p-4">
      <div className="bg-[#1b1b1c] w-full sm:max-w-sm rounded-t-2xl sm:rounded-2xl shadow-2xl border border-gray-800 pb-safe">
        {/* Header */}
        <div className="flex items-center justify-between p-5 border-b border-gray-800">
          <h2 className="text-lg font-bold text-white">Отправить</h2>
          <button
            onClick={onClose}
            className="w-8 h-8 flex items-center justify-center rounded-full bg-gray-800 hover:bg-gray-700 transition-colors"
          >
            <svg className="w-4 h-4 text-gray-400" 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>

        {success ? (
          /* Success state */
          <div className="p-6 text-center">
            <div className="w-16 h-16 bg-green-500/10 rounded-full flex items-center justify-center mx-auto mb-4">
              <svg className="w-10 h-10 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            </div>
            <h3 className="text-xl font-bold text-white mb-2">Заявка создана</h3>
            <p className="text-gray-400 text-sm mb-2">
              Ваша заявка на вывод <span className="text-white font-medium">{amountNum} {displaySymbol}</span> принята и находится в обработке.
            </p>
            <p className="text-gray-500 text-xs mb-6">
              Статус можно отследить в истории операций
            </p>
            <button
              onClick={onClose}
              className="w-full bg-[#48ff91] hover:bg-[#3de080] text-black font-semibold py-3 px-4 rounded-xl transition-colors"
            >
              Закрыть
            </button>
          </div>
        ) : (
          <div className="p-5 space-y-4">
            {/* Network badge */}
            <div className="flex items-center gap-3 bg-gray-800/50 rounded-xl px-4 py-3">
              {networkImage ? (
                <img src={networkImage} alt={networkName} className="w-7 h-7 rounded-full object-cover" />
              ) : (
                <div className="w-7 h-7 rounded-full bg-blue-500/20 flex items-center justify-center text-xs font-bold text-blue-400">
                  {networkName.slice(0, 2)}
                </div>
              )}
              <div>
                <div className="text-xs text-gray-400">Сеть</div>
                <div className="text-white font-medium text-sm">{networkName || networkSymbol}</div>
              </div>
              <div className="ml-auto text-right">
                <div className="text-xs text-gray-400">Доступно</div>
                <div className="text-white text-sm font-medium">{balance.toFixed(6)} {displaySymbol}</div>
              </div>
            </div>

            {/* Address input */}
            <div>
              <label className="block text-sm text-gray-400 mb-1.5">Адрес получателя</label>
              <textarea
                value={toAddress}
                onChange={e => { setToAddress(e.target.value); setAddressError(''); }}
                onBlur={handleAddressBlur}
                placeholder={getAddressPlaceholder(networkSymbol)}
                rows={2}
                className={`w-full bg-gray-800/60 border rounded-xl px-4 py-3 text-white text-sm placeholder-gray-600 focus:outline-none resize-none transition-colors ${
                  addressError ? 'border-red-500/60 focus:border-red-500' : 'border-gray-700 focus:border-[#48ff91]/50'
                }`}
              />
              {addressError && (
                <p className="text-red-400 text-xs mt-1">{addressError}</p>
              )}
            </div>

            {/* Amount input */}
            <div>
              <label className="block text-sm text-gray-400 mb-1.5">Сумма</label>
              <div className="relative">
                <input
                  type="number"
                  value={amount}
                  onChange={e => setAmount(e.target.value)}
                  placeholder="0.00"
                  min="0"
                  step="any"
                  className="w-full bg-gray-800/60 border border-gray-700 rounded-xl px-4 py-3 pr-20 text-white text-sm placeholder-gray-600 focus:outline-none focus:border-[#48ff91]/50 transition-colors [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
                />
                <div className="absolute right-3 top-1/2 -translate-y-1/2 flex items-center gap-2">
                  <span className="text-gray-500 text-sm">{displaySymbol}</span>
                  <button
                    onClick={handleMax}
                    className="text-xs text-[#48ff91] font-semibold hover:text-[#3de080] transition-colors bg-[#48ff91]/10 px-2 py-0.5 rounded-md"
                  >
                    MAX
                  </button>
                </div>
              </div>
              {/* USD equivalent */}
              {amountNum > 0 && price > 0 && (
                <p className="text-gray-500 text-xs mt-1.5">≈ ${amountUsd} USD</p>
              )}
            </div>

            {/* Error */}
            {error && (
              <div className="bg-red-500/10 border border-red-500/30 rounded-xl px-4 py-3">
                <p className="text-red-400 text-sm">{error}</p>
              </div>
            )}

            {/* Send button */}
            <button
              onClick={handleSend}
              disabled={loading || !toAddress || !amount}
              className="w-full bg-[#48ff91] hover:bg-[#3de080] disabled:bg-gray-700 disabled:text-gray-500 text-black font-semibold py-3.5 px-4 rounded-xl transition-colors mt-2 flex items-center justify-center gap-2"
            >
              {loading ? (
                <>
                  <div className="w-4 h-4 border-2 border-black/30 border-t-black rounded-full animate-spin" />
                  Отправка...
                </>
              ) : (
                <>
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 11l5-5m0 0l5 5m-5-5v12" />
                  </svg>
                  Отправить
                </>
              )}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
