import React from 'react';
import { AlertCircle, CheckCircle2, LayoutDashboard, Info, Zap, Key, ShieldAlert } from 'lucide-react';
import { clearBacktestRuntimeFlagCache } from '../backtest/flags';
import { fetchDynamicConfigItems, upsertDynamicConfigItems } from '../lib/dynamicConfigApi';

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

interface BacktestFlagState {
    enableBacktest: boolean;
    customerEnabled: boolean;
}

const BACKTEST_FLAG_KEYS = {
    ENABLE_BACKTEST: 'ENABLE_BACKTEST',
    BACKTEST_CUSTOMER_ENABLED: 'BACKTEST_CUSTOMER_ENABLED'
} as const;

const readBooleanConfig = (configs: ConfigItem[], key: string, fallback: boolean = false): boolean => {
    const row = configs.find((item) => item.key === key);
    if (!row) return fallback;
    const normalized = String(row.value || '').trim().toLowerCase();
    if (['true', '1', 'yes', 'on'].includes(normalized)) return true;
    if (['false', '0', 'no', 'off'].includes(normalized)) return false;
    return fallback;
};

export const cloneConfigItems = (configs: ConfigItem[]) =>
    JSON.parse(JSON.stringify(configs)) as ConfigItem[];

export const hasConfigChanges = (configs: ConfigItem[], originalConfigs: ConfigItem[]) =>
    JSON.stringify(configs) !== JSON.stringify(originalConfigs);

export function buildConfigUpsertPayload(configs: ConfigItem[]): ConfigItem[];
export function buildConfigUpsertPayload(configs: ConfigItem[], timestampIso: string): Array<{ key: string; value: string; updated_at: string }>;
export function buildConfigUpsertPayload(configs: ConfigItem[], timestampIso?: string) {
    return configs.map((config) => (
        timestampIso
            ? {
                key: config.key,
                value: config.value,
                updated_at: timestampIso
            }
            : {
                key: config.key,
                value: config.value,
                description: config.description
            }
    ));
}

export const ConfigTab = () => {
    const [configs, setConfigs] = React.useState<ConfigItem[]>([]);
    const [originalConfigs, setOriginalConfigs] = React.useState<ConfigItem[]>([]);
    const [loading, setLoading] = React.useState(true);
    const [saving, setSaving] = React.useState(false);
    const [savingBacktestFlags, setSavingBacktestFlags] = React.useState(false);
    const [backtestFlags, setBacktestFlags] = React.useState<BacktestFlagState>({
        enableBacktest: false,
        customerEnabled: false
    });
    const [message, setMessage] = React.useState<{ type: 'success' | 'error', text: string } | null>(null);

    const fetchConfigs = async () => {
        setLoading(true);
        try {
            const configData = await fetchDynamicConfigItems();
            setConfigs(configData);
            setOriginalConfigs(cloneConfigItems(configData));
            setBacktestFlags({
                enableBacktest: readBooleanConfig(configData, BACKTEST_FLAG_KEYS.ENABLE_BACKTEST, false),
                customerEnabled: readBooleanConfig(configData, BACKTEST_FLAG_KEYS.BACKTEST_CUSTOMER_ENABLED, false)
            });
        } catch (error) {
            console.error('Error fetching global config:', error);
        } finally {
            setLoading(false);
        }
    };

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

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

    const handleReset = () => {
        setConfigs(cloneConfigItems(originalConfigs));
    };

    const handleSaveAll = async () => {
        setSaving(true);
        try {
            await upsertDynamicConfigItems(buildConfigUpsertPayload(configs));

            clearBacktestRuntimeFlagCache();
            setMessage({ type: 'success', text: 'Neural parameters synchronized successfully.' });
            setOriginalConfigs(cloneConfigItems(configs));
            setTimeout(() => setMessage(null), 4000);
        } catch (err: any) {
            setMessage({ type: 'error', text: `Sync failed: ${err.message}` });
        } finally {
            setSaving(false);
        }
    };

    const handleSaveBacktestFlags = async () => {
        setSavingBacktestFlags(true);
        try {
            await upsertDynamicConfigItems([
                {
                    key: BACKTEST_FLAG_KEYS.ENABLE_BACKTEST,
                    value: String(backtestFlags.enableBacktest),
                    description: 'Master switch for /api/backtest/run.'
                },
                {
                    key: BACKTEST_FLAG_KEYS.BACKTEST_CUSTOMER_ENABLED,
                    value: String(backtestFlags.customerEnabled),
                    description: 'Allows non-admin customers to use backtest.'
                }
            ]);
            clearBacktestRuntimeFlagCache();
            await fetchConfigs();
            setMessage({ type: 'success', text: 'Backtest access flags updated.' });
            setTimeout(() => setMessage(null), 4000);
        } catch (err: any) {
            setMessage({ type: 'error', text: `Backtest flag update failed: ${err.message}` });
        } finally {
            setSavingBacktestFlags(false);
        }
    };

    const hasChanges = hasConfigChanges(configs, originalConfigs);

    if (loading) {
        return (
            <div className="flex flex-col items-center justify-center h-64 text-gray-500 animate-pulse">
                <div className="w-10 h-10 border-4 border-[#00ff88]/10 border-t-[#00ff88] rounded-full animate-spin mb-4 shadow-xl" />
                <p className="text-xs font-black uppercase tracking-[0.3em]">Calibrating Infrastructure...</p>
            </div>
        );
    }

    return (
        <div className="space-y-10 animate-in fade-in duration-700">
            {/* 1. NOTIFICATION PANEL */}
            {message && (
                <div className={`p-6 rounded-2xl flex items-center gap-4 border-2 animate-in slide-in-from-top-4 duration-500 ${message.type === 'success' ? 'bg-green-500/10 border-green-500/20 text-green-400' : 'bg-red-500/10 border-red-500/20 text-red-400'
                    }`}>
                    <div className={`p-2 rounded-full ${message.type === 'success' ? 'bg-green-400/20' : 'bg-red-400/20'}`}>
                        {message.type === 'success' ? <CheckCircle2 size={24} /> : <AlertCircle size={24} />}
                    </div>
                    <div>
                        <span className="text-sm font-black uppercase tracking-widest">{message.type === 'success' ? 'SYNC COMPLETE' : 'CRITICAL ERROR'}</span>
                        <p className="text-xs font-bold opacity-80 uppercase tracking-tight leading-none mt-1">{message.text}</p>
                    </div>
                </div>
            )}

            {/* 2. ACTION CONTROL CENTER */}
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-6 bg-[#14151a] border border-white/5 p-8 rounded-3xl relative overflow-hidden group shadow-2xl">
                <div className="relative z-10 flex items-center gap-6">
                    <div className="w-14 h-14 bg-white/5 border border-white/10 rounded-2xl flex items-center justify-center text-blue-400 shadow-xl">
                        <Zap size={30} fill="currentColor" fillOpacity={0.1} />
                    </div>
                    <div>
                        <h2 className="text-xl font-black text-white flex items-center gap-3 uppercase tracking-tight">
                            Global Operational Parameters
                        </h2>
                        <p className="text-gray-500 text-[10px] font-bold uppercase tracking-[0.2em] opacity-60 mt-2">Core Infrastructure Configuration & Credentials</p>
                    </div>
                </div>

                <div className="flex items-center gap-4 relative z-10">
                    {hasChanges && (
                        <button
                            onClick={handleReset}
                            className="px-4 py-2 text-[10px] font-black uppercase tracking-widest text-gray-500 hover:text-white transition-all underline underline-offset-8 decoration-white/10"
                        >
                            Abort Changes
                        </button>
                    )}
                    <button
                        onClick={handleSaveAll}
                        disabled={!hasChanges || saving}
                        className={`flex items-center gap-3 px-10 py-4 rounded-2xl text-[10px] font-black uppercase tracking-widest transition-all shadow-2xl ${hasChanges && !saving
                            ? 'bg-white text-black hover:bg-blue-400 transition-colors'
                            : 'bg-white/5 text-gray-600 cursor-not-allowed'
                            }`}
                    >
                        {saving ? 'Syncing...' : 'Commit Changes'}
                    </button>
                </div>
            </div>

            <div className="bg-[#14151a] border border-white/5 p-6 rounded-3xl space-y-4">
                <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                    <div>
                        <h3 className="text-sm font-black text-white uppercase tracking-widest">Backtest Access Control</h3>
                        <p className="text-[10px] text-zinc-500 uppercase tracking-wider mt-1">
                            Runtime flags in <code>bot_config</code>. Applies automatically on dynamic config refresh.
                        </p>
                    </div>
                    <button
                        onClick={handleSaveBacktestFlags}
                        disabled={savingBacktestFlags}
                        className={`px-5 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest ${savingBacktestFlags ? 'bg-white/5 text-zinc-600 cursor-not-allowed' : 'bg-emerald-400 text-black hover:bg-emerald-300'}`}
                    >
                        {savingBacktestFlags ? 'Saving...' : 'Save Backtest Flags'}
                    </button>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <label className="flex items-start gap-3 rounded-2xl border border-white/10 bg-black/20 p-4">
                        <input
                            type="checkbox"
                            checked={backtestFlags.enableBacktest}
                            onChange={(event) => setBacktestFlags((prev) => ({
                                ...prev,
                                enableBacktest: event.target.checked,
                                customerEnabled: event.target.checked ? prev.customerEnabled : false
                            }))}
                        />
                        <span>
                            <span className="block text-[11px] font-black text-white uppercase tracking-wide">Enable Backtest Globally</span>
                            <span className="block text-[10px] text-zinc-500 mt-1">Master switch for `/api/backtest/run`.</span>
                        </span>
                    </label>
                    <label className="flex items-start gap-3 rounded-2xl border border-white/10 bg-black/20 p-4">
                        <input
                            type="checkbox"
                            checked={backtestFlags.customerEnabled}
                            disabled={!backtestFlags.enableBacktest}
                            onChange={(event) => setBacktestFlags((prev) => ({ ...prev, customerEnabled: event.target.checked }))}
                        />
                        <span>
                            <span className="block text-[11px] font-black text-white uppercase tracking-wide">Enable Backtest For Customers</span>
                            <span className="block text-[10px] text-zinc-500 mt-1">When off, only admin users can run backtests.</span>
                        </span>
                    </label>
                </div>
            </div>

            {/* 3. RESPONSIVE TABLE OF CONFIGS */}
            <div className="table-container overflow-x-auto">
                <table className="pro-table w-full">
                    <thead>
                        <tr>
                            <th className="min-w-[200px]">Parameter Key</th>
                            <th className="min-w-[300px]">Functional Description</th>
                            <th className="min-w-[400px]">Operational Value</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-white/5">
                        {configs.length > 0 ? (
                            configs.map((config) => {
                                const isSecret = config.key.includes('KEY') || config.key.includes('SECRET') || config.key.includes('TOKEN');
                                return (
                                    <tr key={config.key} className="group">
                                        <td className="px-6 py-8 align-top">
                                            <div className="flex items-center gap-4">
                                                <div className={`w-10 h-10 rounded-xl flex items-center justify-center shadow-inner group-hover:scale-110 transition-transform ${isSecret ? 'bg-orange-500/10 text-orange-400 border border-orange-500/20' : 'bg-blue-500/10 text-blue-400 border border-blue-500/20'}`}>
                                                    {isSecret ? <Key size={16} /> : <Zap size={16} />}
                                                </div>
                                                <span className="text-[11px] font-black text-white uppercase tracking-tight break-all">
                                                    {config.key}
                                                </span>
                                            </div>
                                        </td>
                                        <td className="px-6 py-8 align-top">
                                            <p className="text-[11px] text-gray-500 font-bold uppercase tracking-wider leading-relaxed group-hover:text-gray-400 transition-colors">
                                                {config.description || 'Core system constant utilized by the execution engine logic.'}
                                            </p>
                                        </td>
                                        <td className="px-6 py-6">
                                            <div className="relative group/field">
                                                <textarea
                                                    value={config.value}
                                                    onChange={(e) => handleChange(config.key, e.target.value)}
                                                    className={`w-full bg-black/40 border border-white/5 rounded-2xl px-5 py-4 text-[12px] font-mono font-bold focus:outline-none transition-all min-h-[80px] hover:border-white/10 ${isSecret ? 'text-orange-400 focus:border-orange-500' : 'text-blue-400 focus:border-blue-500'}`}
                                                    rows={2}
                                                />
                                                <div className={`absolute bottom-4 right-4 text-[8px] font-black uppercase tracking-widest opacity-20 group-hover/field:opacity-40 transition-opacity ${isSecret ? 'text-orange-400' : 'text-blue-400'}`}>
                                                    {isSecret ? 'ENCRYPTED' : 'UNSECURED'}
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                );
                            })
                        ) : (
                            <tr>
                                <td colSpan={3} className="px-6 py-32 text-center">
                                    <LayoutDashboard size={64} className="mx-auto mb-6 text-gray-800 opacity-40" />
                                    <p className="text-lg font-black text-gray-700 uppercase tracking-[0.3em] opacity-40">Configuration Map Null</p>
                                </td>
                            </tr>
                        )}
                    </tbody>
                </table>
            </div>

            {/* 4. IMMUTABLE FOOTER INFO */}
            <footer className="relative p-12 bg-gradient-to-br from-[#0c0d10] to-[#000] border border-white/5 rounded-[3rem] overflow-hidden group shadow-2xl">
                <div className="absolute top-0 right-0 p-12 opacity-[0.03] group-hover:opacity-10 transition-all duration-1000">
                    <ShieldAlert size={160} className="text-blue-400" />
                </div>
                <div className="relative z-10 flex flex-col lg:flex-row gap-10 items-center">
                    <div className="p-8 bg-blue-500/5 rounded-3xl text-blue-400 border border-blue-500/10 shadow-inner">
                        <Info size={40} />
                    </div>
                    <div className="space-y-4 max-w-4xl text-center lg:text-left">
                        <h5 className="text-xs font-black text-white uppercase tracking-[0.5em] opacity-80">Synchronization Protocol Alpha</h5>
                        <p className="text-[11px] text-gray-600 font-bold leading-relaxed uppercase tracking-[0.15em]">
                            Updates to <span className="text-white/80 border-b border-blue-500/30 pb-0.5">SYMBOLS</span> and <span className="text-white/80 border-b border-blue-500/30 pb-0.5">CAPITAL</span> are hot-loaded within the active cycle.
                            Changes to <span className="text-white/80 border-b border-blue-500/30 pb-0.5">ENCRYPTED PROVIDERS</span> or <span className="text-white/80 border-b border-blue-500/30 pb-0.5">API CREDENTIALS</span> require a hard handshake reset of the neural execution daemon to re establishment secure connections.
                        </p>
                    </div>
                </div>
            </footer>
        </div>
    );
};
