import { useState, useEffect } from 'react';
import { Settings, Save, ToggleLeft, ToggleRight, DollarSign, Percent, Globe } from 'lucide-react';
import { fetchSettings, updateSettings } from '../../api/mockApi';
import toast from 'react-hot-toast';

const AdminSettings = () => {
    const [settings, setSettings] = useState({});
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);

    useEffect(() => { fetchSettings().then(d => { setSettings(d); setLoading(false); }).catch(() => setLoading(false)); }, []);

    const handleSave = async () => {
        setSaving(true);
        try { await updateSettings(settings); toast.success('Настройки сохранены!'); }
        catch (e) { toast.error(e.message || 'Ошибка сохранения'); }
        finally { setSaving(false); }
    };

    const toggle = (key) => setSettings(s => ({ ...s, [key]: s[key] === '1' ? '0' : '1' }));
    const setValue = (key, value) => setSettings(s => ({ ...s, [key]: value }));

    if (loading) return <div className="flex justify-center py-20"><div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-secondary"></div></div>;

    return (
        <div className="animate-fade-in pb-20">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 gap-4">
                <div>
                    <h2 className="text-3xl font-poppins font-semibold text-white mb-2">Настройки системы</h2>
                    <p className="text-dimWhite font-poppins text-sm">Глобальные настройки банка</p>
                </div>
                <button onClick={handleSave} disabled={saving}
                    className={`flex items-center gap-2 px-6 py-3 rounded-xl font-poppins font-medium transition-all ${saving ? 'bg-gray-600 text-gray-300' : 'bg-blue-gradient text-primary hover:opacity-90'}`}>
                    <Save size={18} /> {saving ? 'Сохранение...' : 'Сохранить'}
                </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">
                    <h3 className="text-white font-poppins font-semibold mb-5 flex items-center gap-2"><Globe size={18} className="text-secondary" /> Общие</h3>
                    <div className="space-y-4">
                        <div>
                            <label className="block text-dimWhite text-sm font-poppins mb-1.5">Название банка</label>
                            <input type="text" value={settings.bank_name || ''} onChange={(e) => setValue('bank_name', 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" />
                        </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" value={settings.max_transfer_limit || ''} onChange={(e) => setValue('max_transfer_limit', e.target.value)}
                                    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" />
                            </div>
                        </div>
                        <div>
                            <label className="block text-dimWhite text-sm font-poppins mb-1.5">Процентная ставка по кредитам (% / год)</label>
                            <div className="relative">
                                <Percent className="absolute left-3 top-1/2 -translate-y-1/2 text-dimWhite" size={16} />
                                <input type="number" step="0.1" value={settings.loan_interest_rate || ''} onChange={(e) => setValue('loan_interest_rate', e.target.value)}
                                    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" />
                            </div>
                        </div>
                    </div>
                </div>

                <div className="bg-black-gradient-2 rounded-2xl p-6 border border-gray-800">
                    <h3 className="text-white font-poppins font-semibold mb-5 flex items-center gap-2"><Settings size={18} className="text-secondary" /> Функции</h3>
                    <div className="space-y-4">
                        {[
                            { key: 'crypto_enabled', label: 'Пополнение криптой', desc: 'Разрешить пополнение через криптовалюту' },
                            { key: 'registration_enabled', label: 'Регистрация', desc: 'Разрешить новым пользователям регистрацию' },
                            { key: 'maintenance_mode', label: 'Режим обслуживания', desc: 'Ограничить доступ к приложению' },
                        ].map(item => (
                            <div key={item.key} className="flex items-center justify-between p-4 bg-black/30 rounded-xl border border-gray-800/50">
                                <div>
                                    <div className="text-white font-poppins font-medium text-sm">{item.label}</div>
                                    <div className="text-dimWhite text-xs font-poppins">{item.desc}</div>
                                </div>
                                <button onClick={() => toggle(item.key)}>
                                    {settings[item.key] === '1' ? <ToggleRight size={32} className="text-secondary" /> : <ToggleLeft size={32} className="text-gray-600" />}
                                </button>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default AdminSettings;
