import { useState, useEffect } from 'react';
import { TrendingUp, TrendingDown, RefreshCw, ArrowRightLeft, DollarSign, ChevronDown } from 'lucide-react';
import { fetchCurrencyRates } from '../../api/mockApi';
import { fetchUserData } from '../../api/mockApi';
import toast from 'react-hot-toast';

const CURRENCIES = [
    { code: 'USD', name: 'Доллар США',     flag: '🇺🇸', symbol: '$' },
    { code: 'EUR', name: 'Евро',           flag: '🇪🇺', symbol: '€' },
    { code: 'RUB', name: 'Российский рубль', flag: '🇷🇺', symbol: '₽' },
    { code: 'GBP', name: 'Фунт стерлингов', flag: '🇬🇧', symbol: '£' },
    { code: 'JPY', name: 'Японская иена',  flag: '🇯🇵', symbol: '¥' },
    { code: 'CNY', name: 'Китайский юань', flag: '🇨🇳', symbol: '¥' },
    { code: 'CHF', name: 'Швейцарский франк', flag: '🇨🇭', symbol: 'Fr' },
    { code: 'AED', name: 'Дирхам ОАЭ',    flag: '🇦🇪', symbol: 'د.إ' },
    { code: 'TRY', name: 'Турецкая лира', flag: '🇹🇷', symbol: '₺' },
    { code: 'KZT', name: 'Казахстанский тенге', flag: '🇰🇿', symbol: '₸' },
    { code: 'UAH', name: 'Украинская гривна', flag: '🇺🇦', symbol: '₴' },
];

const MOCK_CHANGES = { EUR: +0.34, RUB: -1.2, GBP: +0.12, JPY: -0.5, CNY: +0.08, CHF: +0.21, AED: 0, TRY: -2.1, KZT: -0.9, UAH: -0.4 };

const CurrencyView = () => {
    const [rates, setRates]       = useState({});
    const [loading, setLoading]   = useState(true);
    const [fromCur, setFromCur]   = useState('USD');
    const [toCur, setToCur]       = useState('EUR');
    const [fromAmt, setFromAmt]   = useState('100');
    const [balance, setBalance]   = useState(0);
    const [lastUpdated, setLastUpdated] = useState(null);

    const load = async () => {
        setLoading(true);
        try {
            const r = await fetchCurrencyRates();
            setRates(r);
            setLastUpdated(new Date());
        } catch { toast.error('Не удалось загрузить курсы'); }
        finally { setLoading(false); }
    };

    useEffect(() => {
        load();
        fetchUserData().then(d => setBalance(parseFloat(d.balance || 0)));
    }, []);

    const convert = (amount, from, to) => {
        if (!rates[to] || !rates[from]) return 0;
        const inUSD = from === 'USD' ? parseFloat(amount) : parseFloat(amount) / rates[from];
        return to === 'USD' ? inUSD : inUSD * rates[to];
    };

    const result = convert(fromAmt, fromCur, toCur);
    const fromSymbol = CURRENCIES.find(c => c.code === fromCur)?.symbol || fromCur;
    const toSymbol   = CURRENCIES.find(c => c.code === toCur)?.symbol   || toCur;

    const swap = () => { setFromCur(toCur); setToCur(fromCur); };

    const CurrencySelect = ({ value, onChange }) => (
        <div className="relative">
            <select value={value} onChange={e => onChange(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 appearance-none pr-8">
                {CURRENCIES.map(c => (
                    <option key={c.code} value={c.code} className="bg-gray-800">{c.flag} {c.code} — {c.name}</option>
                ))}
            </select>
            <ChevronDown size={14} className="absolute right-3 top-1/2 -translate-y-1/2 text-dimWhite pointer-events-none" />
        </div>
    );

    return (
        <div className="animate-fade-in pb-24">
            <div className="flex justify-between items-start mb-8">
                <div>
                    <h2 className="text-3xl font-poppins font-semibold text-white mb-2">Валюта и курсы</h2>
                    <p className="text-dimWhite font-poppins text-sm">
                        {lastUpdated ? `Обновлено: ${lastUpdated.toLocaleTimeString('ru-RU')}` : 'Загрузка...'}
                    </p>
                </div>
                <button onClick={load} disabled={loading}
                    className={`flex items-center gap-2 px-4 py-2 rounded-xl font-poppins text-sm bg-black-gradient-2 border border-gray-700 text-dimWhite hover:text-white hover:border-secondary/50 transition-all ${loading ? 'opacity-50' : ''}`}>
                    <RefreshCw size={14} className={loading ? 'animate-spin' : ''} /> Обновить
                </button>
            </div>

            {/* Конвертер */}
            <div className="bg-gradient-to-br from-blue-600/20 to-indigo-900/20 border border-blue-500/30 rounded-3xl p-6 mb-8 relative overflow-hidden">
                <div className="absolute top-0 right-0 w-40 h-40 bg-blue-500/10 rounded-full -mr-10 -mt-10 blur-2xl pointer-events-none" />
                <h3 className="text-white font-poppins font-semibold mb-5 flex items-center gap-2 relative z-10">
                    <ArrowRightLeft size={18} className="text-secondary" /> Конвертер валют
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-[1fr_auto_1fr] gap-4 items-end relative z-10">
                    <div className="space-y-2">
                        <label className="text-dimWhite text-xs font-poppins uppercase tracking-wider">Из</label>
                        <CurrencySelect value={fromCur} onChange={setFromCur} />
                        <div className="relative">
                            <span className="absolute left-3 top-1/2 -translate-y-1/2 text-dimWhite text-sm">{fromSymbol}</span>
                            <input type="number" value={fromAmt} onChange={e => setFromAmt(e.target.value)}
                                className="w-full bg-black/40 border border-gray-700 rounded-xl pl-8 pr-4 py-3 text-white font-poppins text-xl font-bold focus:outline-none focus:border-secondary" />
                        </div>
                    </div>

                    <button onClick={swap} className="w-12 h-12 rounded-full bg-secondary/20 border border-secondary/30 flex items-center justify-center text-secondary hover:bg-secondary/30 transition-all hover:scale-110 self-end mb-0.5 mx-auto">
                        <ArrowRightLeft size={18} />
                    </button>

                    <div className="space-y-2">
                        <label className="text-dimWhite text-xs font-poppins uppercase tracking-wider">В</label>
                        <CurrencySelect value={toCur} onChange={setToCur} />
                        <div className="bg-black/40 border border-secondary/30 rounded-xl px-4 py-3">
                            <div className="text-secondary font-poppins text-xl font-bold">
                                {toSymbol} {result.toLocaleString('ru-RU', { minimumFractionDigits: 2, maximumFractionDigits: 4 })}
                            </div>
                        </div>
                    </div>
                </div>
                <div className="mt-4 pt-4 border-t border-white/10 flex items-center justify-between relative z-10">
                    <span className="text-dimWhite text-xs font-poppins">
                        1 {fromCur} = {toSymbol} {convert(1, fromCur, toCur).toFixed(4)}
                    </span>
                    <span className="text-dimWhite text-xs font-poppins">
                        Ваш баланс: <span className="text-white font-semibold">${balance.toFixed(2)}</span>
                    </span>
                </div>
            </div>

            {/* Таблица курсов */}
            {loading ? (
                <div className="flex justify-center py-12"><div className="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-secondary"></div></div>
            ) : (
                <div className="bg-black-gradient-2 rounded-2xl border border-gray-800 overflow-hidden">
                    <div className="px-5 py-4 border-b border-gray-800">
                        <h3 className="text-white font-poppins font-semibold">Курсы к доллару (USD)</h3>
                    </div>
                    <div className="divide-y divide-gray-800/50">
                        {CURRENCIES.filter(c => c.code !== 'USD').map(currency => {
                            const rate = rates[currency.code];
                            const change = MOCK_CHANGES[currency.code] || 0;
                            const isUp = change >= 0;
                            return (
                                <div key={currency.code} className="flex items-center justify-between px-5 py-4 hover:bg-white/5 transition-colors">
                                    <div className="flex items-center gap-3">
                                        <span className="text-2xl">{currency.flag}</span>
                                        <div>
                                            <div className="text-white font-poppins font-semibold text-sm">{currency.code}</div>
                                            <div className="text-dimWhite font-poppins text-xs">{currency.name}</div>
                                        </div>
                                    </div>
                                    <div className="text-right">
                                        <div className="text-white font-poppins font-semibold">
                                            {currency.symbol}{rate ? rate.toLocaleString('ru-RU', { minimumFractionDigits: 2, maximumFractionDigits: 4 }) : '—'}
                                        </div>
                                        <div className={`flex items-center justify-end gap-1 text-xs font-poppins ${isUp ? 'text-green-400' : 'text-red-400'}`}>
                                            {isUp ? <TrendingUp size={11} /> : <TrendingDown size={11} />}
                                            {isUp ? '+' : ''}{change.toFixed(2)}%
                                        </div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
            )}
        </div>
    );
};

export default CurrencyView;
