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 } from 'lucide-react';

export default function XDockScriptsAdmin() {
    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';

    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) {
        return (
            <Layout>
                <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>
            </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

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

    return (
        <Layout>
            <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">
                                    <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>
                                            <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>

        </Layout>
    );
}
