import { useState, useEffect } from 'react';
import { Zap, Wifi, QrCode, Droplets, Flame, Phone, Building2, DollarSign, X, CheckCircle, ChevronRight, History } from 'lucide-react';
import { makePayment, fetchPayments } from '../../api/mockApi';
import { useNotifications } from '../../context/NotificationsContext';
import toast from 'react-hot-toast';
import QRCode from 'qrcode';

const CATEGORIES = [
    {
        id: 'utilities',
        label: 'Коммунальные услуги',
        icon: Building2,
        color: 'from-blue-500/20 to-blue-600/10',
        border: 'border-blue-500/30',
        accent: 'bg-blue-500',
        providers: [
            { id: 'electric', name: 'Электроэнергия', icon: Zap, color: 'text-yellow-400' },
            { id: 'water',    name: 'Водоснабжение',  icon: Droplets, color: 'text-blue-400' },
            { id: 'gas',      name: 'Газоснабжение',  icon: Flame, color: 'text-orange-400' },
        ]
    },
    {
        id: 'internet',
        label: 'Интернет и связь',
        icon: Wifi,
        color: 'from-purple-500/20 to-purple-600/10',
        border: 'border-purple-500/30',
        accent: 'bg-purple-500',
        providers: [
            { id: 'mts',      name: 'МТС',           icon: Phone, color: 'text-red-400' },
            { id: 'megafon',  name: 'МегаФон',       icon: Phone, color: 'text-green-400' },
            { id: 'beeline',  name: 'Билайн',        icon: Phone, color: 'text-yellow-400' },
            { id: 'rostelecom', name: 'Ростелеком',  icon: Wifi,  color: 'text-blue-400' },
        ]
    },
];

const PaymentsView = () => {
    const [activeTab, setActiveTab] = useState('pay');
    const [selectedCategory, setSelectedCategory] = useState(null);
    const [selectedProvider, setSelectedProvider] = useState(null);
    const [amount, setAmount] = useState('');
    const [accountNum, setAccountNum] = useState('');
    const [paying, setPaying] = useState(false);
    const [qrValue, setQrValue] = useState('');
    const [qrImg, setQrImg]     = useState('');
    const [history, setHistory] = useState([]);
    const { pushLocal, reload: reloadNotifs } = useNotifications();

    useEffect(() => { fetchPayments().then(setHistory); }, []);

    const handlePay = async (e) => {
        e.preventDefault();
        if (!selectedProvider || !amount || parseFloat(amount) <= 0) { toast.error('Заполните все поля'); return; }
        setPaying(true);
        try {
            await makePayment({ category: selectedCategory.id, provider: selectedProvider.name, account_number: accountNum, amount: parseFloat(amount) });
            toast.success(`Оплачено ${selectedProvider.name} — $${amount}`);
            pushLocal('Списание', `Оплата ${selectedProvider.name}: $${amount}`, 'warning');
            reloadNotifs();
            setAmount(''); setAccountNum(''); setSelectedProvider(null);
            fetchPayments().then(setHistory);
        } catch (err) { toast.error(err.message); }
        finally { setPaying(false); }
    };

    const generateQR = async () => {
        if (!qrValue) { toast.error('Введите данные для QR'); return; }
        try {
            const url = await QRCode.toDataURL(qrValue, { width: 256, color: { dark: '#ffffff', light: '#00000000' } });
            setQrImg(url);
        } catch { toast.error('Ошибка генерации QR'); }
    };

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

    const categoryLabel = (c) => {
        const map = { utilities: 'Коммунальные', internet: 'Интернет', other: 'Прочее' };
        return map[c] || c;
    };

    return (
        <div className="animate-fade-in pb-24">
            <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">Оплата услуг, QR-платежи</p>
            </div>

            {/* Tabs */}
            <div className="flex gap-2 mb-7 bg-black/30 p-1 rounded-2xl border border-gray-800 w-fit">
                {[{ id: 'pay', label: 'Оплата', icon: DollarSign }, { id: 'qr', label: 'QR-код', icon: QrCode }, { id: 'history', label: 'История', icon: History }].map(t => (
                    <button key={t.id} onClick={() => setActiveTab(t.id)}
                        className={`flex items-center gap-2 px-5 py-2.5 rounded-xl font-poppins text-sm font-medium transition-all ${activeTab === t.id ? 'bg-blue-gradient text-primary shadow-md' : 'text-dimWhite hover:text-white'}`}>
                        <t.icon size={15} />{t.label}
                    </button>
                ))}
            </div>

            {/* === PAYMENT TAB === */}
            {activeTab === 'pay' && (
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <div>
                        {!selectedCategory ? (
                            <div className="flex flex-col gap-4">
                                <p className="text-dimWhite font-poppins text-sm mb-1">Выберите категорию</p>
                                {CATEGORIES.map(cat => {
                                    const Icon = cat.icon;
                                    return (
                                        <button key={cat.id} onClick={() => setSelectedCategory(cat)}
                                            className={`flex items-center justify-between p-5 rounded-2xl bg-gradient-to-br ${cat.color} border ${cat.border} hover:scale-[1.02] transition-all group`}>
                                            <div className="flex items-center gap-4">
                                                <div className={`w-12 h-12 rounded-xl ${cat.accent}/20 flex items-center justify-center`}><Icon size={22} className="text-white" /></div>
                                                <div className="text-left">
                                                    <div className="text-white font-poppins font-semibold">{cat.label}</div>
                                                    <div className="text-dimWhite text-xs font-poppins">{cat.providers.length} поставщика</div>
                                                </div>
                                            </div>
                                            <ChevronRight size={18} className="text-dimWhite group-hover:text-white transition-colors" />
                                        </button>
                                    );
                                })}
                            </div>
                        ) : !selectedProvider ? (
                            <div>
                                <button onClick={() => setSelectedCategory(null)} className="text-secondary font-poppins text-sm mb-4 flex items-center gap-1 hover:underline">← Назад</button>
                                <p className="text-dimWhite font-poppins text-sm mb-3">{selectedCategory.label} — выберите поставщика</p>
                                <div className="flex flex-col gap-3">
                                    {selectedCategory.providers.map(p => {
                                        const Icon = p.icon;
                                        return (
                                            <button key={p.id} onClick={() => setSelectedProvider(p)}
                                                className="flex items-center justify-between p-4 rounded-2xl bg-black-gradient-2 border border-gray-700 hover:border-secondary/50 hover:bg-white/5 transition-all group">
                                                <div className="flex items-center gap-3">
                                                    <Icon size={20} className={p.color} />
                                                    <span className="text-white font-poppins font-medium">{p.name}</span>
                                                </div>
                                                <ChevronRight size={16} className="text-dimWhite group-hover:text-white" />
                                            </button>
                                        );
                                    })}
                                </div>
                            </div>
                        ) : (
                            <div>
                                <button onClick={() => setSelectedProvider(null)} className="text-secondary font-poppins text-sm mb-4 flex items-center gap-1 hover:underline">← Назад</button>
                                <div className="bg-black-gradient-2 rounded-2xl p-6 border border-gray-800">
                                    <div className="flex items-center gap-3 mb-6 pb-4 border-b border-gray-800">
                                        <selectedProvider.icon size={22} className={selectedProvider.color} />
                                        <div>
                                            <div className="text-white font-poppins font-semibold">{selectedProvider.name}</div>
                                            <div className="text-dimWhite text-xs font-poppins">{selectedCategory.label}</div>
                                        </div>
                                    </div>
                                    <form onSubmit={handlePay} className="space-y-4">
                                        <div>
                                            <label className="block text-dimWhite text-sm font-poppins mb-1.5">Номер лицевого счёта</label>
                                            <input type="text" value={accountNum} onChange={e => setAccountNum(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="например: 123456789" />
                                        </div>
                                        <div>
                                            <label className="block text-dimWhite text-sm font-poppins mb-1.5">Сумма ($)</label>
                                            <div className="relative">
                                                <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 text-dimWhite" size={16} />
                                                <input type="number" min="1" value={amount} onChange={e => setAmount(e.target.value)} required
                                                    className="w-full bg-black/40 border border-gray-700 rounded-xl pl-9 pr-4 py-3 text-white font-poppins focus:outline-none focus:border-secondary"
                                                    placeholder="0.00" />
                                            </div>
                                            <div className="flex 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>
                                        <button type="submit" disabled={paying}
                                            className={`w-full py-3 rounded-xl font-poppins font-semibold transition-all ${paying ? 'bg-gray-600 text-gray-300' : 'bg-blue-gradient text-primary hover:opacity-90 shadow-lg shadow-cyan-500/20'}`}>
                                            {paying ? 'Оплата...' : `Оплатить${amount ? ' $' + parseFloat(amount).toFixed(2) : ''}`}
                                        </button>
                                    </form>
                                </div>
                            </div>
                        )}
                    </div>

                    {/* Recent payments side */}
                    <div className="bg-black-gradient-2 rounded-2xl p-6 border border-gray-800 h-fit">
                        <h3 className="text-white font-poppins font-semibold mb-4">Последние платежи</h3>
                        {history.length === 0 ? (
                            <div className="text-dimWhite text-sm font-poppins text-center py-8">Платежей пока нет</div>
                        ) : (
                            <div className="space-y-3">
                                {history.slice(0, 6).map((p, i) => (
                                    <div key={i} className="flex justify-between items-center p-3 bg-black/30 rounded-xl">
                                        <div>
                                            <div className="text-white text-sm font-poppins font-medium">{p.provider}</div>
                                            <div className="text-dimWhite text-xs font-poppins">{categoryLabel(p.category)} · {new Date(p.created_at).toLocaleDateString('ru-RU')}</div>
                                        </div>
                                        <div className="text-right">
                                            <div className="text-red-400 font-poppins font-semibold text-sm">-${parseFloat(p.amount).toFixed(2)}</div>
                                            <div className={`text-xs font-poppins ${p.status === 'completed' ? 'text-green-400' : 'text-yellow-400'}`}>
                                                {p.status === 'completed' ? 'Выполнен' : 'В обработке'}
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                </div>
            )}

            {/* === QR TAB === */}
            {activeTab === 'qr' && (
                <div className="max-w-lg mx-auto">
                    <div className="bg-black-gradient-2 rounded-2xl p-6 border border-gray-800 mb-4">
                        <h3 className="text-white font-poppins font-semibold mb-4 flex items-center gap-2"><QrCode size={18} className="text-secondary" /> Генератор QR-кода</h3>
                        <div className="space-y-4">
                            <div>
                                <label className="block text-dimWhite text-sm font-poppins mb-1.5">Данные для QR (ссылка, номер счёта, текст)</label>
                                <textarea value={qrValue} onChange={e => setQrValue(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 h-24 resize-none"
                                    placeholder="Введите данные для QR-кода..." />
                            </div>
                            <button onClick={generateQR} className="w-full py-3 rounded-xl font-poppins font-semibold bg-blue-gradient text-primary hover:opacity-90">
                                Создать QR-код
                            </button>
                        </div>
                    </div>
                    {qrImg && (
                        <div className="bg-black-gradient-2 rounded-2xl p-6 border border-secondary/30 flex flex-col items-center gap-4">
                            <div className="bg-white/5 p-4 rounded-2xl border border-gray-700">
                                <img src={qrImg} alt="QR Code" className="w-48 h-48" />
                            </div>
                            <p className="text-dimWhite text-sm font-poppins text-center break-all">{qrValue}</p>
                            <a href={qrImg} download="qrcode.png"
                                className="px-6 py-2.5 rounded-xl font-poppins text-sm font-medium bg-secondary/20 text-secondary hover:bg-secondary/30 transition-colors">
                                Скачать QR
                            </a>
                        </div>
                    )}
                </div>
            )}

            {/* === HISTORY TAB === */}
            {activeTab === 'history' && (
                <div className="bg-black-gradient-2 rounded-2xl border border-gray-800 overflow-hidden">
                    <div className="p-5 border-b border-gray-800">
                        <h3 className="text-white font-poppins font-semibold">История платежей</h3>
                    </div>
                    {history.length === 0 ? (
                        <div className="text-center py-12 text-dimWhite font-poppins">Платежей нет</div>
                    ) : (
                        <div className="divide-y divide-gray-800/50">
                            {history.map((p, i) => (
                                <div key={i} className="flex justify-between items-center px-5 py-4 hover:bg-white/5 transition-colors">
                                    <div className="flex items-center gap-3">
                                        <div className="w-9 h-9 rounded-full bg-red-500/15 flex items-center justify-center"><DollarSign size={16} className="text-red-400" /></div>
                                        <div>
                                            <div className="text-white font-poppins text-sm font-medium">{p.provider}</div>
                                            <div className="text-dimWhite text-xs font-poppins">{categoryLabel(p.category)} {p.account_number ? `· ${p.account_number}` : ''}</div>
                                        </div>
                                    </div>
                                    <div className="text-right">
                                        <div className="text-red-400 font-poppins font-semibold text-sm">-${parseFloat(p.amount).toFixed(2)}</div>
                                        <div className="text-dimWhite text-xs font-poppins">{new Date(p.created_at).toLocaleDateString('ru-RU')}</div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            )}
        </div>
    );
};

export default PaymentsView;
