import { useState } from 'react';
import { CreditCard, Bitcoin, DollarSign, Copy, Check, ArrowDownCircle } from 'lucide-react';
import { depositMoney } from '../../api/mockApi';
import toast from 'react-hot-toast';

const CRYPTO_OPTIONS = [
    { id: 'BTC', name: 'Bitcoin', symbol: 'BTC', address: '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa', color: 'from-orange-500 to-yellow-500', icon: '₿' },
    { id: 'ETH', name: 'Ethereum', symbol: 'ETH', address: '0x742d35Cc6634C0532925a3b8D4C9B3e0c8427a5', color: 'from-blue-500 to-purple-600', icon: 'Ξ' },
    { id: 'USDT', name: 'Tether', symbol: 'USDT', address: 'TQn9Y2khEsLJW1ChVWFMSMeRDow5KcbLSE', color: 'from-green-500 to-teal-500', icon: '₮' },
    { id: 'BNB', name: 'BNB', symbol: 'BNB', address: 'bnb1grpf0955h0ykzq3ar5nmum7y6gdfl6lxfn46h2', color: 'from-yellow-400 to-yellow-600', icon: 'B' },
];

const QUICK_AMOUNTS = [50, 100, 250, 500, 1000, 2000];

const TopupView = () => {
    const [method, setMethod] = useState('card');
    const [amount, setAmount] = useState('');
    const [cardNumber, setCardNumber] = useState('');
    const [cardExpiry, setCardExpiry] = useState('');
    const [cardCvv, setCardCvv] = useState('');
    const [selectedCrypto, setSelectedCrypto] = useState(CRYPTO_OPTIONS[0]);
    const [isProcessing, setIsProcessing] = useState(false);
    const [copiedAddress, setCopiedAddress] = useState(false);
    const [success, setSuccess] = useState(null);

    const handleCopyAddress = () => {
        navigator.clipboard.writeText(selectedCrypto.address);
        setCopiedAddress(true);
        toast.success('Адрес скопирован!');
        setTimeout(() => setCopiedAddress(false), 2000);
    };

    const formatCard = (v) => v.replace(/\D/g, '').slice(0, 16).replace(/(.{4})/g, '$1 ').trim();
    const formatExpiry = (v) => { v = v.replace(/\D/g, '').slice(0, 4); return v.length >= 2 ? v.slice(0, 2) + '/' + v.slice(2) : v; };

    const handleDeposit = async (e) => {
        e.preventDefault();
        if (!amount || parseFloat(amount) < 1) { toast.error('Минимальное пополнение — $1'); return; }
        setIsProcessing(true);
        try {
            const res = await depositMoney({
                amount: parseFloat(amount), method,
                ...(method === 'card' ? { card_last4: cardNumber.replace(/\s/g, '').slice(-4) } : { crypto_currency: selectedCrypto.id, crypto_address: selectedCrypto.address })
            });
            setSuccess({ amount, method });
            toast.success(res.message || 'Пополнение выполнено!');
            setAmount(''); setCardNumber(''); setCardExpiry(''); setCardCvv('');
        } catch (error) { toast.error(error.message || 'Ошибка пополнения'); }
        finally { setIsProcessing(false); }
    };

    return (
        <div className="animate-fade-in pb-20">
            <div className="mb-8">
                <h2 className="text-3xl font-poppins font-semibold text-white mb-2">Пополнение счёта</h2>
                <p className="text-dimWhite font-poppins text-sm">Пополните баланс банковской картой или криптовалютой</p>
            </div>

            {success && (
                <div className="mb-6 bg-green-500/10 border border-green-500/30 rounded-2xl p-5 flex items-center gap-4">
                    <div className="w-12 h-12 rounded-full bg-green-500/20 flex items-center justify-center flex-shrink-0">
                        <ArrowDownCircle className="text-green-400" size={24} />
                    </div>
                    <div>
                        <div className="text-green-400 font-poppins font-semibold">Пополнение выполнено!</div>
                        <div className="text-dimWhite text-sm font-poppins">${parseFloat(success.amount).toFixed(2)} через {success.method === 'card' ? 'карту' : 'крипту'}</div>
                    </div>
                </div>
            )}

            <div className="flex gap-3 mb-6">
                {[{ val: 'card', icon: CreditCard, label: 'Банковская карта' }, { val: 'crypto', icon: Bitcoin, label: 'Криптовалюта' }].map(m => (
                    <button key={m.val} onClick={() => setMethod(m.val)}
                        className={`flex items-center gap-2 px-5 py-3 rounded-xl font-poppins font-medium transition-all ${method === m.val ? 'bg-blue-gradient text-primary' : 'bg-black-gradient-2 border border-gray-700 text-dimWhite hover:border-gray-500'}`}>
                        <m.icon size={18} /> {m.label}
                    </button>
                ))}
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div className="bg-black-gradient-2 rounded-2xl p-6 border border-gray-800">
                    <form onSubmit={handleDeposit} className="space-y-4">
                        <div>
                            <label className="block text-dimWhite text-sm font-poppins mb-1.5">Сумма (USD)</label>
                            <div className="relative">
                                <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 text-dimWhite" size={18} />
                                <input type="number" min="1" value={amount} onChange={(e) => setAmount(e.target.value)}
                                    className="w-full bg-black/40 border border-gray-700 rounded-xl pl-10 pr-4 py-3 text-white font-poppins focus:outline-none focus:border-secondary" placeholder="Введите сумму..." required />
                            </div>
                            <div className="flex flex-wrap gap-2 mt-2">
                                {QUICK_AMOUNTS.map(q => (
                                    <button key={q} type="button" onClick={() => setAmount(String(q))}
                                        className={`px-3 py-1 rounded-lg text-xs font-poppins border transition-all ${amount === String(q) ? 'bg-secondary/20 text-secondary border-secondary/30' : 'bg-black/30 text-dimWhite border-gray-800 hover:border-gray-600'}`}>
                                        ${q}
                                    </button>
                                ))}
                            </div>
                        </div>

                        {method === 'card' ? (
                            <>
                                <div>
                                    <label className="block text-dimWhite text-sm font-poppins mb-1.5">Номер карты</label>
                                    <div className="relative">
                                        <CreditCard className="absolute left-3 top-1/2 -translate-y-1/2 text-dimWhite" size={18} />
                                        <input type="text" value={cardNumber} onChange={(e) => setCardNumber(formatCard(e.target.value))}
                                            className="w-full bg-black/40 border border-gray-700 rounded-xl pl-10 pr-4 py-3 text-white font-poppins focus:outline-none focus:border-secondary"
                                            placeholder="1234 5678 9012 3456" required />
                                    </div>
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <label className="block text-dimWhite text-sm font-poppins mb-1.5">Срок действия</label>
                                        <input type="text" value={cardExpiry} onChange={(e) => setCardExpiry(formatExpiry(e.target.value))}
                                            className="w-full bg-black/40 border border-gray-700 rounded-xl px-4 py-3 text-white font-poppins focus:outline-none focus:border-secondary" placeholder="ММ/ГГ" required />
                                    </div>
                                    <div>
                                        <label className="block text-dimWhite text-sm font-poppins mb-1.5">CVV</label>
                                        <input type="text" value={cardCvv} onChange={(e) => setCardCvv(e.target.value.replace(/\D/g, '').slice(0, 3))}
                                            className="w-full bg-black/40 border border-gray-700 rounded-xl px-4 py-3 text-white font-poppins focus:outline-none focus:border-secondary" placeholder="•••" required />
                                    </div>
                                </div>
                            </>
                        ) : (
                            <div>
                                <label className="block text-dimWhite text-sm font-poppins mb-1.5">Выберите криптовалюту</label>
                                <div className="grid grid-cols-2 gap-3">
                                    {CRYPTO_OPTIONS.map(crypto => (
                                        <div key={crypto.id} onClick={() => setSelectedCrypto(crypto)}
                                            className={`cursor-pointer border rounded-xl p-3 flex items-center gap-3 transition-all ${selectedCrypto.id === crypto.id ? 'border-secondary bg-secondary/10' : 'border-gray-700 bg-black/30 hover:border-gray-500'}`}>
                                            <div className={`w-8 h-8 rounded-full bg-gradient-to-br ${crypto.color} flex items-center justify-center text-white font-bold text-sm`}>{crypto.icon}</div>
                                            <div>
                                                <div className="text-white text-sm font-poppins font-semibold">{crypto.symbol}</div>
                                                <div className="text-dimWhite text-xs font-poppins">{crypto.name}</div>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}

                        <button type="submit" disabled={isProcessing}
                            className={`w-full py-3 rounded-xl font-poppins font-semibold transition-all ${isProcessing ? 'bg-gray-600 text-gray-300 cursor-not-allowed' : 'bg-blue-gradient text-primary hover:opacity-90'}`}>
                            {isProcessing ? 'Обработка...' : `Пополнить${amount ? ' $' + parseFloat(amount).toFixed(2) : ''}`}
                        </button>
                    </form>
                </div>

                <div className="flex flex-col gap-4">
                    {method === 'crypto' && (
                        <div className="bg-black-gradient-2 rounded-2xl p-5 border border-gray-800">
                            <h3 className="text-white font-poppins font-semibold mb-3">Адрес для {selectedCrypto.name}</h3>
                            <div className="bg-black/40 border border-gray-700 rounded-xl p-4 break-all mb-3">
                                <div className="text-white font-poppins text-sm mb-3">{selectedCrypto.address}</div>
                                <button onClick={handleCopyAddress} className="flex items-center gap-2 text-secondary text-sm font-poppins hover:text-white transition-colors">
                                    {copiedAddress ? <Check size={14} /> : <Copy size={14} />}
                                    {copiedAddress ? 'Скопировано!' : 'Копировать адрес'}
                                </button>
                            </div>
                            <div className="text-yellow-400/80 text-xs font-poppins bg-yellow-400/10 rounded-lg p-3">
                                После отправки введите эквивалент в USD выше и нажмите «Пополнить».
                            </div>
                        </div>
                    )}
                    <div className="bg-black-gradient-2 rounded-2xl p-5 border border-gray-800">
                        <h3 className="text-white font-poppins font-semibold mb-3">Комиссии</h3>
                        <div className="space-y-2 text-sm font-poppins">
                            {[['Пополнение картой', 'Бесплатно'], ['Пополнение криптой', 'Бесплатно'], ['Переводы', 'Бесплатно']].map(([l, v]) => (
                                <div key={l} className="flex justify-between">
                                    <span className="text-dimWhite">{l}</span>
                                    <span className="text-green-400">{v}</span>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default TopupView;
