import React from 'react';
import { Save, AlertCircle, CheckCircle } from 'lucide-react';
import { fetchDynamicConfigItems, upsertDynamicConfigItems } from '../lib/dynamicConfigApi';

interface ConfigItem {
    key: string;
    value: string;
    description: string;
}

export const GlobalConfigManager = () => {
    const [configs, setConfigs] = React.useState<ConfigItem[]>([]);
    const [loading, setLoading] = React.useState(true);
    const [saving, setSaving] = React.useState(false);
    const [message, setMessage] = React.useState<{ type: 'success' | 'error', text: string } | null>(null);

    const fetchConfigs = async () => {
        setLoading(true);
        try {
            const data = await fetchDynamicConfigItems();
            setConfigs(data || []);
        } catch (error: any) {
            console.error('Error fetching global config:', error);
            setMessage({ type: 'error', text: error?.message || 'Dynamic config service unavailable.' });
        }
        setLoading(false);
    };

    React.useEffect(() => {
        fetchConfigs();
    }, []);

    const handleChange = (key: string, value: string) => {
        setConfigs(prev => prev.map(item => item.key === key ? { ...item, value } : item));
    };

    const handleSave = async (item: ConfigItem) => {
        setSaving(true);
        try {
            await upsertDynamicConfigItems([item]);
            setMessage({ type: 'success', text: `${item.key} updated successfully.` });
            setTimeout(() => setMessage(null), 3000);
        } catch (error: any) {
            setMessage({ type: 'error', text: `Failed to save ${item.key}: ${error.message}` });
        }
        setSaving(false);
    };

    if (loading) return <div className="p-4 text-gray-500">Loading system configuration...</div>;

    return (
        <div className="bg-black/20 border border-white/5 rounded-xl p-6">
            <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
                🌍 Global Bot Configuration
            </h3>

            {message && (
                <div className={`mb-4 p-3 rounded-lg flex items-center gap-2 text-sm ${message.type === 'success' ? 'bg-green-500/10 text-green-400 border border-green-500/20' : 'bg-red-500/10 text-red-400 border border-red-500/20'
                    }`}>
                    {message.type === 'success' ? <CheckCircle size={16} /> : <AlertCircle size={16} />}
                    {message.text}
                </div>
            )}

            <div className="space-y-4">
                {configs.map((config) => (
                    <div key={config.key} className="flex flex-col gap-1 pb-4 border-b border-white/5 last:border-0 last:pb-0">
                        <div className="flex items-center justify-between">
                            <label className="text-xs font-bold text-orange-400 uppercase tracking-wider">{config.key}</label>
                            <button
                                onClick={() => handleSave(config)}
                                disabled={saving}
                                className="text-xs bg-orange-500/20 hover:bg-orange-500/40 text-orange-300 px-2 py-1 rounded border border-orange-500/30 transition-colors flex items-center gap-1"
                            >
                                <Save size={12} /> Save
                            </button>
                        </div>
                        <input
                            type="text"
                            value={config.value}
                            onChange={(e) => handleChange(config.key, e.target.value)}
                            className="bg-black/40 border border-white/10 rounded px-3 py-2 text-sm text-gray-200 focus:outline-none focus:border-orange-500/50"
                        />
                        <p className="text-[10px] text-gray-500 italic">{config.description || 'System setting used by the trading core.'}</p>
                    </div>
                ))}

                {configs.length === 0 && (
                    <div className="text-center py-8 border border-dashed border-white/10 rounded-lg">
                        <p className="text-sm text-gray-500 mb-2">No dynamic configuration entries found.</p>
                        <p className="text-xs text-gray-600">The bot is currently using .env defaults.</p>
                    </div>
                )}
            </div>

            <div className="mt-6 pt-4 border-t border-white/10">
                <p className="text-[10px] text-gray-400 leading-relaxed">
                    <strong>Note:</strong> Changes to global variables usually require a bot restart to take full effect (e.g. changing intervals or providers). Symbols may update dynamically depending on strategy implementation.
                </p>
            </div>
        </div>
    );
};
