import React, { useState, useMemo, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useWallet } from '../context/WalletContext';
import TokenIcon from '../components/TokenIcon';
import ReceiveModal from '../components/ReceiveModal';
import { walletAPI } from '../api/wallet';

export default function ReceivePage() {
  const navigate = useNavigate();
  const { activeWallet, sessionLogin } = useWallet();
  const [search, setSearch] = useState('');
  const [qrToken, setQrToken] = useState(null);
  const [addressMap, setAddressMap] = useState({});
  const [copyingSymbol, setCopyingSymbol] = useState(null);
  const [copiedSymbol, setCopiedSymbol] = useState(null);

  // Собираем адреса из activeWallet сразу при загрузке
  useEffect(() => {
    if (!activeWallet?.tokens) return;
    const map = {};
    activeWallet.tokens.forEach(t => {
      const sym = t.tokenInfo?.symbol;
      if (sym && t.address) map[sym] = t.address;
    });
    setAddressMap(map);
  }, [activeWallet]);

  const tokens = useMemo(() => {
    if (!activeWallet?.tokens) return [];
    return activeWallet.tokens
      .filter(t => {
        if (!search.trim()) return true;
        const q = search.toLowerCase();
        return (
          (t.tokenInfo?.symbol || '').toLowerCase().includes(q) ||
          (t.tokenInfo?.name || '').toLowerCase().includes(q)
        );
      })
      .sort((a, b) => {
        const aUsd = (parseFloat(a.balance) || 0) * (parseFloat(a.tokenInfo?.price) || 0);
        const bUsd = (parseFloat(b.balance) || 0) * (parseFloat(b.tokenInfo?.price) || 0);
        return bUsd - aUsd;
      });
  }, [activeWallet, search]);

  const getAddress = async (symbol) => {
    if (addressMap[symbol]) return addressMap[symbol];
    try {
      const res = await walletAPI.getTokenAddress({
        sessionLogin,
        tokenSymbol: symbol,
        walletId: activeWallet?.id,
      });
      if (res.success && res.data?.address) {
        setAddressMap(prev => ({ ...prev, [symbol]: res.data.address }));
        return res.data.address;
      }
    } catch (e) {
      console.error('[ReceivePage] getAddress error', e);
    }
    return null;
  };

  const handleCopy = async (symbol) => {
    if (copyingSymbol) return;
    setCopyingSymbol(symbol);
    try {
      const addr = await getAddress(symbol);
      if (addr) {
        await navigator.clipboard.writeText(addr);
        setCopiedSymbol(symbol);
        setTimeout(() => setCopiedSymbol(null), 2000);
      }
    } finally {
      setCopyingSymbol(null);
    }
  };

  const truncate = (addr) => {
    if (!addr) return null;
    return addr.slice(0, 6) + '...' + addr.slice(-4);
  };

  return (
    <div className="min-h-screen bg-[#1b1b1c] flex flex-col">
      {/* Header */}
      <div className="sticky top-0 z-10 bg-[#1b1b1c] border-b border-gray-800">
        <div className="max-w-md mx-auto px-4 pt-4 pb-3 flex items-center gap-3">
          <button
            onClick={() => navigate(-1)}
            className="w-9 h-9 flex items-center justify-center rounded-full bg-gray-800/60 hover:bg-gray-700 transition-colors shrink-0"
          >
            <svg className="w-5 h-5 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 flex-1 text-center pr-9">Получить</h1>
        </div>

        {/* Search */}
        <div className="max-w-md mx-auto px-4 pb-3">
          <div className="relative">
            <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" 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"
              placeholder="Поиск"
              value={search}
              onChange={e => setSearch(e.target.value)}
              className="w-full bg-gray-800/60 border border-gray-700/50 rounded-xl pl-9 pr-4 py-2.5 text-white text-sm placeholder-gray-500 focus:outline-none focus:border-gray-600 transition-colors"
            />
          </div>
        </div>
      </div>

      {/* Token list */}
      <div className="max-w-md mx-auto w-full flex-1 pb-6">
        {tokens.length === 0 ? (
          <p className="text-center text-gray-500 py-12 text-sm">Токены не найдены</p>
        ) : (
          tokens.map(token => {
            const sym = token.tokenInfo?.symbol || '';
            const displaySym = sym === 'USDTERC' ? 'USDT' : sym;
            const networkName = token.tokenInfo?.networkName || token.tokenInfo?.networkSymbol || '';
            const addr = addressMap[sym];
            const isCopied = copiedSymbol === sym;
            const isCopying = copyingSymbol === sym;

            return (
              <div
                key={sym}
                className="flex items-center gap-3 px-4 py-3.5 border-b border-gray-800/50"
              >
                {/* Icon */}
                <div className="shrink-0">
                  <TokenIcon symbol={sym} size="w-11 h-11" />
                </div>

                {/* Name + address */}
                <div className="flex-1 min-w-0 overflow-hidden">
                  <div className="flex items-center gap-1.5 flex-wrap">
                    <span className="text-white font-semibold text-sm">{displaySym}</span>
                    {networkName && (
                      <span className="text-[11px] text-gray-400 bg-gray-700/60 rounded-full px-2 py-0.5 leading-none">
                        {networkName}
                      </span>
                    )}
                  </div>
                  {addr ? (
                    <span className="text-gray-500 text-xs font-mono">{truncate(addr)}</span>
                  ) : (
                    <span className="text-gray-700 text-xs">—</span>
                  )}
                </div>

                {/* Buttons */}
                <div className="flex items-center gap-2 shrink-0">
                  {/* QR code */}
                  <button
                    onClick={() => setQrToken(sym)}
                    className="w-9 h-9 flex items-center justify-center rounded-lg bg-gray-800 hover:bg-gray-700 active:scale-95 transition-all"
                    title="QR-код"
                  >
                    <QRIcon />
                  </button>

                  {/* Copy */}
                  <button
                    onClick={() => handleCopy(sym)}
                    disabled={!!copyingSymbol}
                    className="w-9 h-9 flex items-center justify-center rounded-lg bg-gray-800 hover:bg-gray-700 active:scale-95 transition-all"
                    title="Скопировать адрес"
                  >
                    {isCopied ? (
                      <svg className="w-5 h-5 text-[#48ff91]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                      </svg>
                    ) : isCopying ? (
                      <div className="w-4 h-4 border-2 border-gray-600 border-t-gray-300 rounded-full animate-spin" />
                    ) : (
                      <CopyIcon />
                    )}
                  </button>
                </div>
              </div>
            );
          })
        )}
      </div>

      {/* QR Modal – reuses existing ReceiveModal */}
      <ReceiveModal
        isOpen={!!qrToken}
        onClose={() => setQrToken(null)}
        tokenSymbol={qrToken}
      />
    </div>
  );
}

function QRIcon() {
  return (
    <svg className="w-5 h-5 text-gray-300" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="3" width="7" height="7" rx="1" />
      <rect x="14" y="3" width="7" height="7" rx="1" />
      <rect x="3" y="14" width="7" height="7" rx="1" />
      <path d="M14 14h.01M14 18h3M18 14v7M21 14h.01" />
    </svg>
  );
}

function CopyIcon() {
  return (
    <svg className="w-5 h-5 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
      <rect x="9" y="9" width="13" height="13" rx="2" />
      <path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1" />
    </svg>
  );
}
