import React, { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import Layout from '../components/Layout';
import { api } from '../lib/api';
import { useAuth } from '../context/AuthContext';
import { toast } from 'sonner';
import { ArrowLeft, Search, Users, Power, Plus, Pencil, Trash2, X } from 'lucide-react';

export default function XDockScriptsAdmin() {
    return <XDockScriptsAdminInner embedded={false} />;
}

export function XDockScriptsPanel() {
    return <XDockScriptsAdminInner embedded={true} />;
}

function XDockScriptsAdminInner({ embedded = false }) {
    const navigate = useNavigate();
    const { user } = useAuth();

    const [users, setUsers] = useState([]);
    const [catalog, setCatalog] = useState([]);
    const [selectedId, setSelectedId] = useState(null);
    const [features, setFeatures] = useState(new Set());
    const [userSearch, setUserSearch] = useState('');
    const [modSearch, setModSearch] = useState('');
    const [filter, setFilter] = useState('all');
    const [loading, setLoading] = useState(true);

    const canAccess = !!user?.can_manage_xdock_scripts || (user?.username || '').toLowerCase() === 'mathieu.u';
    const isMathieu = (user?.username || '').toLowerCase() === 'mathieu.u';

    // v2.7.5 : modal d'édition / ajout de script (mathieu.u uniquement)
    const [editorOpen, setEditorOpen] = useState(false);
    const [editorMode, setEditorMode] = useState('add'); // 'add' | 'edit'
    const [editorKey, setEditorKey] = useState('');
    const [editorLabel, setEditorLabel] = useState('');
    const [editorGroup, setEditorGroup] = useState('');
    const [editorOrigKey, setEditorOrigKey] = useState('');

    useEffect(() => {
        if (!canAccess) return;
        const load = async () => {
            setLoading(true);
            try {
                const [c, u] = await Promise.all([
                    api.get('/xdock-scripts/catalog'),
                    api.get('/xdock-scripts/users'),
                ]);
                setCatalog(c.data.catalog);
                setUsers(u.data.users);
            } catch (e) {
                toast.error(e?.response?.data?.detail || 'Erreur chargement');
            } finally {
                setLoading(false);
            }
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
        load();
    }, [canAccess]);

    const loadFeatures = async (uid) => {
        if (!uid) { setFeatures(new Set()); return; }
        try {
            const r = await api.get(`/xdock-scripts/users/${uid}/features`);
            setFeatures(new Set(r.data.features));
        } catch (e) {
            toast.error(e?.response?.data?.detail || 'Erreur features');
        }
    };

    // eslint-disable-next-line react-hooks/exhaustive-deps
    useEffect(() => { loadFeatures(selectedId); }, [selectedId]);

    const filteredUsers = useMemo(() => {
        const q = userSearch.trim().toLowerCase();
        if (!q) return users;
        return users.filter((u) =>
            ((u.fullname || '') + ' ' + (u.username || '') + ' ' + (u.email || '') + ' ' + (u.role || '')).toLowerCase().includes(q),
        );
    }, [users, userSearch]);

    const filteredCatalog = useMemo(() => {
        const q = modSearch.trim().toLowerCase();
        return catalog.filter((s) => {
            if (q && !(s.label + ' ' + s.key).toLowerCase().includes(q)) return false;
            const cat = catalog.find((x) => x.key === s.key);
            const realKeys = cat?.group?.length ? cat.group : [s.key];
            const en = realKeys.every((rk) => features.has(rk));
            if (filter === 'on' && !en) return false;
            if (filter === 'off' && en) return false;
            return true;
        });
    }, [catalog, modSearch, filter, features]);

    if (!canAccess) {
        const block = (
            <div className="rounded-lg border border-red-200 bg-red-50 p-6 text-red-800">
                <h2 className="font-bold mb-2">Accès refusé</h2>
                <p className="text-sm">Tu n&apos;as pas les droits pour gérer les scripts XDock+. Demande au super-admin de t&apos;autoriser.</p>
            </div>
        );
        return embedded ? block : <Layout>{block}</Layout>;
    }

    const isEnabled = (key) => {
        const cat = catalog.find((s) => s.key === key);
        const realKeys = cat?.group?.length ? cat.group : [key];
        return realKeys.every((rk) => features.has(rk));
    };

    const toggleScript = async (key) => {
        if (!selectedId) return;
        const enabled = !isEnabled(key);
        try {
            await api.post(`/xdock-scripts/users/${selectedId}/toggle`, { script_key: key, enabled });
            // Refresh features
            const r = await api.get(`/xdock-scripts/users/${selectedId}/features`);
            setFeatures(new Set(r.data.features));
            toast.success('Sauvegardé');
        } catch (e) {
            toast.error(e?.response?.data?.detail || 'Erreur toggle');
        }
    };

    const bulkSet = async (mode) => {
        if (!selectedId) return;
        const label = mode === 'all_on' ? 'Tout activer' : mode === 'all_off' ? 'Tout désactiver' : 'Preset recommandé';
        if (mode !== 'preset_reco' && !window.confirm(`${label} pour cet utilisateur ?`)) return;
        try {
            await api.post(`/xdock-scripts/users/${selectedId}/bulk-set`, { mode });
            const r = await api.get(`/xdock-scripts/users/${selectedId}/features`);
            setFeatures(new Set(r.data.features));
            toast.success(`${label} appliqué`);
        } catch (e) {
            toast.error(e?.response?.data?.detail || 'Erreur bulk');
        }
    };

    const createUser = async () => { return; }; // eslint-disable-line no-unused-vars

    const deleteUser = async (uid) => { return; }; // eslint-disable-line no-unused-vars

    // v2.7.5 : édition / ajout / suppression d'un script (mathieu.u uniquement)
    const openAddScript = () => {
        setEditorMode('add');
        setEditorKey('');
        setEditorLabel('');
        setEditorGroup('');
        setEditorOrigKey('');
        setEditorOpen(true);
    };

    const openEditScript = (script) => {
        setEditorMode('edit');
        setEditorKey(script.key);
        setEditorLabel(script.label);
        setEditorGroup((script.group || []).join(','));
        setEditorOrigKey(script.key);
        setEditorOpen(true);
    };

    const saveScript = async () => {
        const key = editorKey.trim().toLowerCase();
        const label = editorLabel.trim();
        if (!key || !label) {
            toast.error('Clé et libellé requis');
            return;
        }
        if (!/^[a-z0-9_]+$/.test(key)) {
            toast.error('Clé invalide (a-z, 0-9, _)');
            return;
        }
        const group = editorGroup.split(',').map((s) => s.trim()).filter(Boolean);
        try {
            await api.post('/xdock-scripts/catalog/upsert', {
                key,
                label,
                group: group.length ? group : null,
            });
            const c = await api.get('/xdock-scripts/catalog');
            setCatalog(c.data.catalog);
            setEditorOpen(false);
            toast.success(editorMode === 'add' ? 'Script ajouté' : 'Script mis à jour');
        } catch (e) {
            toast.error(e?.response?.data?.detail || 'Erreur');
        }
    };

    const deleteScript = async (key) => {
        if (!window.confirm(`Supprimer le script "${key}" du catalogue ?\n\nSi c'est un script custom il disparaît. Si c'était un override d'un script intégré, le libellé d'origine revient.`)) return;
        try {
            await api.delete(`/xdock-scripts/catalog/${encodeURIComponent(key)}`);
            const c = await api.get('/xdock-scripts/catalog');
            setCatalog(c.data.catalog);
            toast.success('Script supprimé');
        } catch (e) {
            toast.error(e?.response?.data?.detail || 'Erreur');
        }
    };

    const activeCount = catalog.filter((s) => isEnabled(s.key)).length;
    const selectedUser = users.find((u) => u.id === selectedId);

    const content = (
        <>
            {!embedded && (
                <>
                    <button
                        data-testid="back-btn"
                        onClick={() => navigate('/settings')}
                        className="mb-5 inline-flex items-center gap-2 text-sm font-semibold text-slate-600 hover:text-stef transition"
                    >
                        <ArrowLeft className="h-4 w-4" /> Retour aux paramètres
                    </button>

                    <div className="mb-6 flex items-start justify-between gap-4 flex-wrap">
                        <div className="flex items-center gap-3">
                            <div className="flex h-11 w-11 items-center justify-center rounded-md bg-stef/10 text-stef">
                                <Power className="h-5 w-5" />
                            </div>
                            <div>
                                <p className="text-xs font-bold uppercase tracking-[0.2em] text-stef">XDock Plus</p>
                                <h1 className="font-heading text-2xl sm:text-3xl font-black tracking-tight text-slate-900">
                                    Gestion des scripts utilisateurs
                                </h1>
                            </div>
                        </div>
                    </div>
                </>
            )}

            <div className="grid grid-cols-1 lg:grid-cols-12 gap-4">
                {/* USERS */}
                <div className="lg:col-span-4 rounded-lg border border-slate-200 bg-white p-4 sm:p-5">
                    <div className="flex items-center gap-3 mb-3">
                        <Users className="h-5 w-5 text-stef" />
                        <div className="flex-1">
                            <div className="font-heading font-bold text-slate-900">Utilisateurs XDock+</div>
                            <div className="text-xs text-slate-500">{users.length} au total</div>
                        </div>
                    </div>
                    <div className="relative mb-3">
                        <Search className="h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                        <input
                            data-testid="user-search"
                            value={userSearch}
                            onChange={(e) => setUserSearch(e.target.value)}
                            placeholder="Rechercher (nom, email, rôle)"
                            className="w-full h-10 rounded-md border border-slate-300 bg-white pl-9 pr-3 text-sm font-medium text-slate-900 focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20"
                        />
                    </div>
                    <div className="space-y-2 max-h-[60vh] overflow-y-auto pr-1">
                        {loading ? <div className="text-sm text-slate-400 italic">Chargement…</div> :
                         filteredUsers.length === 0 ? (
                            <div className="text-sm text-slate-400 italic p-3">Aucun utilisateur ne correspond à la recherche.</div>
                         ) : filteredUsers.map((u) => {
                            const active = selectedId === u.id;
                            return (
                                <div
                                    key={u.id}
                                    data-testid={`xs-user-${u.id}`}
                                    className={`group rounded-md border p-3 cursor-pointer transition ${
                                        active
                                            ? 'border-stef bg-stef/5 ring-2 ring-stef/20'
                                            : 'border-slate-200 hover:border-stef/40 hover:bg-slate-50'
                                    }`}
                                    onClick={() => setSelectedId(u.id)}
                                >
                                    <div className="flex items-start justify-between gap-2">
                                        <div className="min-w-0 flex-1">
                                            <div className="font-semibold text-sm text-slate-900 truncate">{u.fullname || u.username}</div>
                                            <div className="text-xs text-slate-500 truncate font-mono">{u.username}{u.email ? ` · ${u.email}` : ''}</div>
                                        </div>
                                        <div className="flex flex-col items-end gap-1 shrink-0">
                                            <span className="text-[10px] font-bold uppercase tracking-wider text-slate-500 border border-slate-300 rounded px-1.5 py-0.5">
                                                {u.role}
                                            </span>
                                            <span className={`text-[10px] font-bold ${u.is_active ? 'text-emerald-600' : 'text-red-500'}`}>
                                                {u.is_active ? 'actif' : 'inactif'}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>

                {/* MODULES */}
                <div className="lg:col-span-8 rounded-lg border border-slate-200 bg-white p-4 sm:p-5">
                    {!selectedId ? (
                        <div className="py-12 text-center text-slate-500">
                            <Users className="h-12 w-12 mx-auto mb-3 text-slate-300" />
                            Sélectionne un utilisateur à gauche.
                        </div>
                    ) : (
                        <>
                            <div className="flex items-start justify-between gap-3 flex-wrap mb-4">
                                <div className="min-w-0">
                                    <div className="font-heading font-bold text-slate-900">Modules</div>
                                    <div className="text-xs text-slate-500">
                                        <span className="font-mono">{selectedUser?.email || selectedUser?.username}</span> · {activeCount}/{catalog.length} actifs
                                    </div>
                                </div>
                                <div className="flex flex-wrap gap-1.5">
                                    {isMathieu && (
                                        <button
                                            data-testid="xs-add-script-btn"
                                            onClick={openAddScript}
                                            className="rounded-md bg-emerald-600 text-white px-3 h-9 text-xs font-bold hover:bg-emerald-700 transition inline-flex items-center gap-1"
                                            title="Ajouter un script au catalogue (mathieu.u)"
                                        >
                                            <Plus className="h-3.5 w-3.5" /> Ajouter
                                        </button>
                                    )}
                                    <button
                                        data-testid="xs-bulk-preset"
                                        onClick={() => bulkSet('preset_reco')}
                                        className="rounded-md bg-stef/10 border border-stef/30 text-stef px-3 h-9 text-xs font-bold hover:bg-stef/20 transition"
                                    >
                                        Preset recommandé
                                    </button>
                                    <button
                                        data-testid="xs-bulk-on"
                                        onClick={() => bulkSet('all_on')}
                                        className="rounded-md bg-white border border-slate-300 text-slate-700 px-3 h-9 text-xs font-bold hover:bg-slate-50 transition"
                                    >
                                        Tout activer
                                    </button>
                                    <button
                                        data-testid="xs-bulk-off"
                                        onClick={() => bulkSet('all_off')}
                                        className="rounded-md bg-white border border-red-300 text-red-600 px-3 h-9 text-xs font-bold hover:bg-red-50 transition"
                                    >
                                        Tout désactiver
                                    </button>
                                </div>
                            </div>

                            <div className="flex flex-wrap gap-2 mb-4">
                                <div className="relative flex-1 min-w-[200px]">
                                    <Search className="h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                                    <input
                                        data-testid="xs-mod-search"
                                        value={modSearch}
                                        onChange={(e) => setModSearch(e.target.value)}
                                        placeholder="Rechercher un module"
                                        className="w-full h-9 rounded-md border border-slate-300 bg-white pl-9 pr-3 text-sm font-medium text-slate-900 focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20"
                                    />
                                </div>
                                {['all', 'on', 'off'].map((f) => (
                                    <button
                                        key={f}
                                        data-testid={`xs-filter-${f}`}
                                        onClick={() => setFilter(f)}
                                        className={`rounded-full px-4 h-9 text-xs font-bold transition ${
                                            filter === f
                                                ? 'bg-stef text-white'
                                                : 'bg-white border border-slate-300 text-slate-600 hover:bg-slate-50'
                                        }`}
                                    >
                                        {f === 'all' ? 'Tous' : f === 'on' ? 'Actifs' : 'Inactifs'}
                                    </button>
                                ))}
                            </div>

                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-[60vh] overflow-y-auto pr-1">
                                {filteredCatalog.length === 0 ? (
                                    <div className="col-span-2 text-sm text-slate-400 italic p-4 text-center">
                                        Aucun module ne correspond à ce filtre.
                                    </div>
                                ) : filteredCatalog.map((s) => {
                                    const en = isEnabled(s.key);
                                    return (
                                        <div
                                            key={s.key}
                                            data-testid={`xs-mod-${s.key}`}
                                            className="flex items-center justify-between gap-3 rounded-md border border-slate-200 bg-white p-3 hover:border-stef/40 transition"
                                        >
                                            <div className="min-w-0 flex-1">
                                                <div className="font-bold text-sm text-slate-900 truncate">{s.label}</div>
                                                <div className="text-[11px] text-slate-400 font-mono truncate">{s.key}</div>
                                            </div>
                                            {isMathieu && (
                                                <div className="flex items-center gap-0.5 shrink-0">
                                                    <button
                                                        type="button"
                                                        data-testid={`xs-mod-edit-${s.key}`}
                                                        onClick={(e) => { e.preventDefault(); e.stopPropagation(); openEditScript(s); }}
                                                        className="p-1.5 text-slate-400 hover:text-stef hover:bg-stef/10 rounded transition"
                                                        title="Renommer ce script"
                                                    >
                                                        <Pencil className="h-3.5 w-3.5" />
                                                    </button>
                                                    <button
                                                        type="button"
                                                        data-testid={`xs-mod-delete-${s.key}`}
                                                        onClick={(e) => { e.preventDefault(); e.stopPropagation(); deleteScript(s.key); }}
                                                        className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded transition"
                                                        title={s.is_custom ? 'Supprimer ce script custom' : "Revenir au libellé d'origine"}
                                                    >
                                                        <Trash2 className="h-3.5 w-3.5" />
                                                    </button>
                                                </div>
                                            )}
                                            <button
                                                type="button"
                                                role="switch"
                                                aria-checked={en}
                                                data-testid={`xs-mod-switch-${s.key}`}
                                                onClick={(e) => { e.preventDefault(); e.stopPropagation(); toggleScript(s.key); }}
                                                className={`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border transition ${
                                                    en ? 'bg-emerald-500 border-emerald-600' : 'bg-slate-200 border-slate-300'
                                                }`}
                                            >
                                                <span className={`inline-block h-5 w-5 rounded-full bg-white shadow transform transition ${en ? 'translate-x-5' : 'translate-x-0.5'} mt-0.5`} />
                                            </button>
                                        </div>
                                    );
                                })}
                            </div>
                        </>
                    )}
                </div>
            </div>

            {/* MODAL : Édition / Ajout d'un script (mathieu.u uniquement) */}
            {editorOpen && (
                <div
                    className="fixed inset-0 z-[1000] flex items-center justify-center bg-slate-900/50 backdrop-blur-sm p-4"
                    onClick={() => setEditorOpen(false)}
                    data-testid="xs-editor-backdrop"
                >
                    <div
                        className="w-full max-w-md rounded-xl bg-white shadow-2xl border border-slate-200 overflow-hidden"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <div className="flex items-center justify-between px-5 py-3 border-b border-slate-200 bg-slate-50">
                            <div className="font-heading font-bold text-slate-900">
                                {editorMode === 'add' ? 'Ajouter un script' : 'Modifier le script'}
                            </div>
                            <button
                                onClick={() => setEditorOpen(false)}
                                className="p-1 text-slate-500 hover:text-slate-900 rounded"
                                data-testid="xs-editor-close"
                            >
                                <X className="h-4 w-4" />
                            </button>
                        </div>

                        <div className="p-5 space-y-4">
                            <div>
                                <label className="text-xs font-bold text-slate-600 uppercase tracking-wider">
                                    Clé technique (key) *
                                </label>
                                <input
                                    data-testid="xs-editor-key"
                                    value={editorKey}
                                    onChange={(e) => setEditorKey(e.target.value)}
                                    disabled={editorMode === 'edit'}
                                    placeholder="ex: mon_script_custom"
                                    className="mt-1 w-full h-10 rounded-md border border-slate-300 px-3 text-sm font-mono text-slate-900 focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20 disabled:bg-slate-50 disabled:text-slate-500"
                                />
                                <p className="text-[10px] text-slate-400 mt-1">a-z, 0-9, underscore. Non modifiable après création.</p>
                            </div>

                            <div>
                                <label className="text-xs font-bold text-slate-600 uppercase tracking-wider">
                                    Libellé affiché *
                                </label>
                                <input
                                    data-testid="xs-editor-label"
                                    value={editorLabel}
                                    onChange={(e) => setEditorLabel(e.target.value)}
                                    placeholder="ex: Mon Script Custom"
                                    className="mt-1 w-full h-10 rounded-md border border-slate-300 px-3 text-sm text-slate-900 focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20"
                                />
                            </div>

                            <div>
                                <label className="text-xs font-bold text-slate-600 uppercase tracking-wider">
                                    Groupe (optionnel)
                                </label>
                                <input
                                    data-testid="xs-editor-group"
                                    value={editorGroup}
                                    onChange={(e) => setEditorGroup(e.target.value)}
                                    placeholder="ex: badgemap,histo_map_porte"
                                    className="mt-1 w-full h-10 rounded-md border border-slate-300 px-3 text-sm font-mono text-slate-900 focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20"
                                />
                                <p className="text-[10px] text-slate-400 mt-1">Liste séparée par des virgules. Laisse vide si le script n&apos;en active qu&apos;un seul.</p>
                            </div>

                            {editorMode === 'add' && (
                                <div className="rounded-md border border-amber-200 bg-amber-50 p-3">
                                    <div className="flex items-start gap-2">
                                        <span className="text-amber-600 text-sm leading-none mt-0.5">💡</span>
                                        <div className="text-[11px] text-amber-900 leading-relaxed">
                                            <div className="font-bold mb-1">N&apos;oublie pas <code className="font-mono bg-amber-100 px-1 rounded">xdp_loader.js</code></div>
                                            <div>Ajoute aussi cette ligne dans <code className="font-mono">MODULES</code> de l&apos;extension :</div>
                                            <pre className="mt-1.5 rounded bg-slate-900 text-emerald-300 px-2 py-1.5 text-[10px] font-mono overflow-x-auto select-all">
{`["${editorKey || 'mon_script_custom'}", "JS/${editorKey || 'mon_script'}.js"],`}
                                            </pre>
                                        </div>
                                    </div>
                                </div>
                            )}
                        </div>

                        <div className="px-5 py-3 border-t border-slate-200 bg-slate-50 flex justify-end gap-2">
                            <button
                                data-testid="xs-editor-cancel"
                                onClick={() => setEditorOpen(false)}
                                className="px-4 h-9 rounded-md border border-slate-300 bg-white text-xs font-bold text-slate-700 hover:bg-slate-100 transition"
                            >
                                Annuler
                            </button>
                            <button
                                data-testid="xs-editor-save"
                                onClick={saveScript}
                                className="px-4 h-9 rounded-md bg-stef text-white text-xs font-bold hover:bg-stef/90 transition"
                            >
                                {editorMode === 'add' ? 'Ajouter' : 'Enregistrer'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </>
    );

    return embedded ? content : <Layout>{content}</Layout>;
}
