import { useEffect, useState } from 'react';
import axios from '../../../bootstrap';
import { Save, CheckCircle } from 'lucide-react';
import { HeartbeatIntervalSelect } from './HeartbeatIntervalSelect';

export function PolicyView() {
    const [scope, setScope] = useState('global');
    const [groupId, setGroupId] = useState('');
    const [agentId, setAgentId] = useState('');

    const [groups, setGroups] = useState<any[]>([]);
    const [agents, setAgents] = useState<any[]>([]);
    const [settings, setSettings] = useState<any>(null);
    const [isLoading, setIsLoading] = useState(true);
    const [isSaving, setIsSaving] = useState(false);
    const [message, setMessage] = useState<string | null>(null);

    const loadMeta = async () => {
        try {
            const [groupsRes, agentsRes] = await Promise.all([
                axios.get('/agent-groups'),
                axios.get('/agents')
            ]);
            setGroups(groupsRes.data.groups || []);
            setAgents(agentsRes.data.agents || []);
        } catch (err) {
            console.error(err);
        }
    };

    const fetchPolicy = async () => {
        setIsLoading(true);
        setMessage(null);
        try {
            const params: any = { scope };
            if (scope === 'group' && groupId) params.group_id = groupId;
            if (scope === 'agent' && agentId) params.agent_id = agentId;

            if ((scope === 'group' && !groupId) || (scope === 'agent' && !agentId)) {
                setSettings(null);
                setIsLoading(false);
                return;
            }

            const res = await axios.get('/policies', { params });
            setSettings(res.data.settings);
        } catch (err) {
            console.error(err);
        } finally {
            setIsLoading(false);
        }
    };

    useEffect(() => {
        loadMeta();
    }, []);

    useEffect(() => {
        fetchPolicy();
    }, [scope, groupId, agentId]);

    const handleSave = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!settings) return;
        setIsSaving(true);
        setMessage(null);

        try {
            const payload: any = { scope, settings };
            if (scope === 'group') payload.group_id = parseInt(groupId);
            if (scope === 'agent') payload.agent_id = agentId;

            await axios.post('/policies', payload);
            setMessage('Policy settings saved successfully.');
            setTimeout(() => setMessage(null), 3000);
        } catch (err) {
            console.error(err);
        } finally {
            setIsSaving(false);
        }
    };

    const handleToggleModule = (moduleKey: string) => {
        if (!settings) return;
        const nextSettings = { ...settings };
        nextSettings.modules[moduleKey].enabled = !nextSettings.modules[moduleKey].enabled;
        setSettings(nextSettings);
    };

    const handleModuleSettingChange = (moduleKey: string, settingKey: string, value: any) => {
        if (!settings) return;
        const nextSettings = { ...settings };
        nextSettings.modules[moduleKey].settings[settingKey] = value;
        setSettings(nextSettings);
    };

    const handleIntervalChange = (value: number) => {
        if (!settings) return;
        setSettings({
            ...settings,
            heartbeat_interval: value,
        });
    };

    // 13 modular definitions for presentation mapping
    const moduleDefs = [
        { key: 'deactivation_protection', label: 'Password / Deactivation Lock' },
        { key: 'brute_force_protection', label: 'Brute Force Protection' },
        { key: 'ip_blocking', label: 'IP Blocking Firewall' },
        { key: 'performance_guard', label: 'Performance Guard (DB telemetry)' },
        { key: 'malware_scanner', label: 'Local Malware Scanner' },
        { key: 'file_integrity_monitor', label: 'File Integrity Monitor' },
        { key: 'login_monitoring', label: 'Login & Account Monitoring' },
        { key: 'plugin_whitelist', label: 'Plugin Whitelist Constraints' },
        { key: 'emergency_lock', label: 'Emergency Security Lock' },
        { key: 'uploads_protection', label: 'Uploads Assets Protection' },
        { key: 'security_score', label: 'Security Score Grading' },
        { key: 'telegram_notifications', label: 'Telegram Alert Push Notifications' },
        { key: 'audit_logging', label: 'Audit Logging Logs Ingestion' },
    ];

    return (
        <div className="space-y-6">
            {/* Control Panel Header */}
            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 bg-slate-900/40 border border-slate-800/80 p-5 rounded-2xl">
                <div className="flex flex-wrap items-center gap-3">
                    <span className="text-xs font-semibold text-slate-400 uppercase tracking-wider">Scope:</span>
                    <select
                        value={scope}
                        onChange={(e) => { setScope(e.target.value); setGroupId(''); setAgentId(''); }}
                        className="px-3 py-1.5 bg-slate-950 border border-slate-800 rounded-lg text-sm text-slate-200 focus:outline-none"
                    >
                        <option value="global">Global Policy</option>
                        <option value="group">Group Policy</option>
                        <option value="agent">Website Override</option>
                    </select>

                    {scope === 'group' && (
                        <select
                            value={groupId}
                            onChange={(e) => setGroupId(e.target.value)}
                            className="px-3 py-1.5 bg-slate-950 border border-slate-800 rounded-lg text-sm text-slate-200 focus:outline-none"
                        >
                            <option value="">-- Select Group --</option>
                            {groups.map((group) => (
                                <option key={group.id} value={group.id}>{group.name}</option>
                            ))}
                        </select>
                    )}

                    {scope === 'agent' && (
                        <select
                            value={agentId}
                            onChange={(e) => setAgentId(e.target.value)}
                            className="px-3 py-1.5 bg-slate-950 border border-slate-800 rounded-lg text-sm text-slate-200 focus:outline-none"
                        >
                            <option value="">-- Select Website --</option>
                            {agents.map((agent) => (
                                <option key={agent.id} value={agent.id}>{agent.site_name} ({agent.domain})</option>
                            ))}
                        </select>
                    )}
                </div>

                {settings && (
                    <button
                        onClick={handleSave}
                        disabled={isSaving}
                        className="flex items-center gap-2 px-4 py-2 bg-rose-500 hover:bg-rose-600 disabled:opacity-50 text-white rounded-xl text-sm font-semibold transition-all active:scale-95 shadow-md"
                    >
                        <Save className="w-4 h-4" />
                        {isSaving ? 'Saving...' : 'Save Settings'}
                    </button>
                )}
            </div>

            {message && (
                <div className="p-4 bg-emerald-500/10 border border-emerald-500/20 rounded-2xl text-sm text-emerald-400 font-semibold flex items-center gap-2">
                    <CheckCircle className="w-5 h-5" />
                    {message}
                </div>
            )}

            {isLoading && (
                <div className="flex justify-center items-center py-20">
                    <div className="w-8 h-8 border-4 border-rose-500/20 border-t-rose-500 rounded-full animate-spin"></div>
                </div>
            )}

            {/* Config Form Settings */}
            {!isLoading && settings && (
                <div className="space-y-6 animate-fade-in">
                    {/* Heartbeat settings */}
                    <div className="bg-slate-900/40 border border-slate-800/80 rounded-2xl p-6 space-y-4">
                        <h4 className="text-base font-bold text-white flex items-center gap-2">
                            General Pulse Configuration
                        </h4>
                        <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center">
                            <div className="space-y-1">
                                <label className="text-xs font-semibold text-slate-400 uppercase block">
                                    Agent Heartbeat Pulse Interval
                                </label>
                                <p className="text-xs text-slate-500">Defines telemetry interval (A-Monster Guard local checks)</p>
                            </div>
                            <div className="flex items-center gap-3">
                                <HeartbeatIntervalSelect
                                    value={settings.heartbeat_interval ?? 300}
                                    onChange={handleIntervalChange}
                                />
                            </div>
                        </div>
                    </div>

                    {/* 13 Feature Module List */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        {moduleDefs.map((def) => {
                            const mod = settings.modules[def.key];
                            if (!mod) return null;

                            return (
                                <div key={def.key} className="bg-slate-900/40 border border-slate-800/80 rounded-2xl p-6 flex flex-col justify-between gap-4">
                                    <div className="flex justify-between items-start gap-4">
                                        <div>
                                            <h5 className="font-bold text-white text-sm">{def.label}</h5>
                                            <p className="text-[10px] text-slate-500 mt-0.5">Subsystem Module identifier</p>
                                        </div>
                                        {/* Boolean Switch Toggle */}
                                        <button
                                            type="button"
                                            onClick={() => handleToggleModule(def.key)}
                                            className={`w-11 h-6 rounded-full transition-colors relative focus:outline-none ${
                                                mod.enabled ? 'bg-rose-500' : 'bg-slate-800'
                                            }`}
                                        >
                                            <span className={`block w-4 h-4 rounded-full bg-white transition-transform absolute top-1 ${
                                                mod.enabled ? 'translate-x-6' : 'translate-x-1'
                                            }`}></span>
                                        </button>
                                    </div>

                                    {/* Parameters config placeholder if enabled */}
                                    {mod.enabled && mod.settings && Object.keys(mod.settings).length > 0 && (
                                        <div className="p-3.5 bg-slate-950/60 border border-slate-850 rounded-xl space-y-3">
                                            {Object.entries(mod.settings).map(([sKey, sVal]) => (
                                                <div key={sKey} className="flex justify-between items-center gap-3">
                                                    <span className="text-[10px] font-mono text-slate-400 capitalize">{sKey.replace(/_/g, ' ')}</span>
                                                    <input
                                                        type="text"
                                                        value={String(sVal)}
                                                        onChange={(e) => handleModuleSettingChange(def.key, sKey, e.target.value)}
                                                        className="w-1/2 px-2 py-1 bg-slate-900 border border-slate-800 rounded-lg text-xs font-mono text-slate-200 text-right focus:outline-none"
                                                    />
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            );
                        })}
                    </div>
                </div>
            )}

            {!isLoading && !settings && (
                <div className="text-center py-20 text-slate-500 text-sm">
                    Select a Group or Website scope from the options above to manage policy overrides.
                </div>
            )}
        </div>
    );
}
