const { useState, useMemo } = React;

window.AdminRoles = function({ actions = [], roles = [], showToast, refreshData }) {
    // Estado para Botones (Marcajes)
    const [editingActionId, setEditingActionId] = useState(null);
    const [actionLabel, setActionLabel] = useState('');

    // Estado para Roles
    const [editingRoleOriginalName, setEditingRoleOriginalName] = useState(null);
    const [roleName, setRoleName] = useState('');
    const [accessLevel, setAccessLevel] = useState('full'); // 'full' (Total), 'readonly' (Sólo Lectura), 'app_only' (App)
    const [permissions, setPermissions] = useState([]);
    const [cameraActions, setCameraActions] = useState([]);

    // Botones disponibles en el sistema (por defecto + personalizados)
    const availableActions = useMemo(() => {
        return actions.length > 0 ? actions : [
            { id: 'almuerzo', label: 'Almuerzo' },
            { id: 'break', label: 'Break / Merienda' },
            { id: 'visita_in', label: 'Visita Cliente' },
            { id: 'reunion', label: 'Reunión' },
            { id: 'capacitacion', label: 'Capacitación' },
            { id: 'gestiones', label: 'Gestiones de Campo' }
        ];
    }, [actions]);

    // Combinar roles de la BD con los predeterminados
    const allCombinedRoles = useMemo(() => {
        const defaultRoles = [
            { name: 'propietario', label: 'PROPIETARIO / ADMIN', accessLevel: 'full', permissions: availableActions.map(a => a.id), cameraActions: ['entrada', 'salida'] },
            { name: 'empleado', label: 'EMPLEADO DE CAMPO / OFICINA', accessLevel: 'app_only', permissions: availableActions.map(a => a.id), cameraActions: ['entrada', 'salida'] }
        ];

        const customMapped = (roles || []).map(r => ({
            ...r,
            name: (r.name || '').toLowerCase().trim(),
            label: (r.name || '').toUpperCase().trim(),
            permissions: Array.isArray(r.permissions) ? r.permissions : (r.permissions ? JSON.parse(r.permissions) : []),
            cameraActions: Array.isArray(r.cameraActions) ? r.cameraActions : (r.cameraActions ? JSON.parse(r.cameraActions) : []),
            accessLevel: r.accessLevel || r.access_level || 'full'
        }));

        const list = [];
        const seen = new Set();

        // Primero los personalizados / editados
        customMapped.forEach(r => {
            if (!seen.has(r.name)) {
                seen.add(r.name);
                list.push(r);
            }
        });

        // Luego los defaults si no han sido personalizados
        defaultRoles.forEach(r => {
            if (!seen.has(r.name)) {
                seen.add(r.name);
                list.push(r);
            }
        });

        return list;
    }, [roles, availableActions]);

    // --- ACCIONES DE BOTONES (MARCAJES) ---
    const handleSaveAction = async () => {
        if (!actionLabel.trim()) {
            if (showToast) showToast("Escribe un nombre para el botón.");
            return;
        }

        const newId = editingActionId || actionLabel.toLowerCase().replace(/\s+/g, '_').replace(/[^a-z0-9_]/g, '') + '_' + Date.now().toString().slice(-4);
        
        const res = await window.apiCall('save_action', { action_id: newId, label: actionLabel.trim() });
        if (res && res.success) {
            setEditingActionId(null);
            setActionLabel('');
            if (showToast) showToast("Botón guardado exitosamente.");
            if (refreshData) await refreshData();
        } else {
            if (showToast) showToast("Error al guardar botón.");
        }
    };

    const handleDeleteAction = async (act) => {
        if (['entrada', 'salida'].includes(act.id)) return alert("No puedes eliminar los botones base de Entrada y Salida.");
        if (!confirm(`¿Estás seguro de eliminar el botón "${act.label}"?`)) return;
        const res = await window.apiCall('delete_action', { action_id: act.id });
        if (res && res.success) {
            if (showToast) showToast("Botón eliminado.");
            if (refreshData) await refreshData();
        }
    };

    // --- ACCIONES DE ROLES ---
    const handleEditRoleClick = (r) => {
        setEditingRoleOriginalName(r.name);
        setRoleName(r.name.toUpperCase());
        setAccessLevel(r.accessLevel || 'full');
        setPermissions(r.permissions && r.permissions.length > 0 ? r.permissions : availableActions.map(a => a.id));
        setCameraActions(r.cameraActions || ['entrada', 'salida']);
    };

    const handleCancelRoleEdit = () => {
        setEditingRoleOriginalName(null);
        setRoleName('');
        setAccessLevel('full');
        setPermissions([]);
        setCameraActions([]);
    };

    const handleSaveRole = async () => {
        if (!roleName.trim()) {
            if (showToast) showToast("El nombre del rol es obligatorio.");
            return;
        }

        const res = await window.apiCall('save_role', {
            name: roleName.toLowerCase().trim(),
            oldName: editingRoleOriginalName ? editingRoleOriginalName.toLowerCase().trim() : null,
            permissions: permissions,
            cameraActions: cameraActions,
            accessLevel: accessLevel
        });

        if (res && res.success) {
            if (showToast) showToast("Rol guardado exitosamente.");
            handleCancelRoleEdit();
            if (refreshData) await refreshData();
        } else {
            if (showToast) showToast("Error al guardar rol: " + (res?.error || ""));
        }
    };

    const togglePermission = (actionId) => {
        setPermissions(prev => prev.includes(actionId) ? prev.filter(p => p !== actionId) : [...prev, actionId]);
    };

    const toggleCamera = (actionId) => {
        setCameraActions(prev => prev.includes(actionId) ? prev.filter(p => p !== actionId) : [...prev, actionId]);
    };

    return (
        <div className="grid lg:grid-cols-2 gap-6 fade-in">
            {/* PANEL DE CONFIGURACIÓN DE BOTONES */}
            <div className="lg:col-span-2 bg-white p-8 rounded-[3rem] shadow-sm space-y-4 border-t-[12px] border-emerald-500 mb-2">
                <h3 className="font-black text-xl text-slate-900">Configuración de Botones (Marcajes)</h3>
                <p className="text-[11px] text-slate-500 font-medium leading-relaxed">
                    Crea o renombra los botones que ven los usuarios en la aplicación. Puedes modificar su nombre visible sin romper el historial de registros.
                </p>
                
                <div className="flex flex-col md:flex-row gap-4 mb-4">
                    <input 
                        value={actionLabel} 
                        onChange={e => setActionLabel(e.target.value)} 
                        placeholder="NOMBRE DEL NUEVO BOTÓN (EJ: CIRUGÍA, PERMISO)..." 
                        className="flex-1 p-4 bg-slate-50 rounded-2xl font-bold uppercase outline-none focus:ring-2 focus:ring-emerald-100 text-xs" 
                    />
                    <button onClick={handleSaveAction} className="py-4 px-8 bg-emerald-600 text-white font-black rounded-2xl uppercase tracking-widest text-[10px] shadow-lg active:scale-95 transition-all hover:bg-emerald-700">
                        {editingActionId ? 'Guardar Cambios' : 'Crear Botón'}
                    </button>
                    {editingActionId && (
                        <button onClick={() => { setEditingActionId(null); setActionLabel(''); }} className="py-4 px-6 bg-slate-100 text-slate-500 font-black rounded-2xl uppercase tracking-widest text-[10px]">
                            Cancelar
                        </button>
                    )}
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                    {availableActions.map(a => (
                        <div key={a.id} className="p-5 rounded-2xl border-2 border-slate-100 flex justify-between items-center bg-slate-50">
                            <span className="font-black text-xs text-slate-700 uppercase">{a.label}</span>
                            <div className="flex gap-2">
                                <button onClick={() => { setEditingActionId(a.id); setActionLabel(a.label); }} className="p-2 bg-white text-indigo-500 rounded-xl shadow-sm border border-slate-200 active:scale-95 hover:bg-indigo-50">
                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>
                                </button>
                                {!['entrada', 'salida'].includes(a.id) && (
                                    <button onClick={() => handleDeleteAction(a)} className="p-2 bg-white text-red-500 rounded-xl shadow-sm border border-slate-200 active:scale-95 hover:bg-red-50">
                                        <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"></path></svg>
                                    </button>
                                )}
                            </div>
                        </div>
                    ))}
                </div>
            </div>

            {/* FORMULARIO EDITAR / CREAR ROL */}
            <div className="bg-white p-8 rounded-[3rem] shadow-sm space-y-4 h-fit border-t-[12px] border-indigo-600">
                <h3 className="font-black text-xl text-slate-900">{editingRoleOriginalName ? `Editar Rol: ${editingRoleOriginalName.toUpperCase()}` : "Configurar / Nuevo Rol"}</h3>
                
                <div>
                    <label className="text-[10px] font-black uppercase text-slate-400 mb-1 block tracking-widest">Nombre del Rol</label>
                    <input 
                        value={roleName} 
                        onChange={e => setRoleName(e.target.value)} 
                        placeholder="Ej. MÉDICO, SUPERVISOR, CONTADOR..." 
                        className="w-full p-4 bg-slate-50 rounded-2xl font-bold uppercase outline-none focus:ring-2 focus:ring-indigo-100 text-xs" 
                    />
                </div>
                
                {/* 3 NIVELES DE ACCESO CLAROS */}
                <div>
                    <label className="text-[10px] font-black uppercase text-slate-400 mb-1 block tracking-widest">Nivel de Acceso al Sistema</label>
                    <select value={accessLevel} onChange={e => setAccessLevel(e.target.value)} className="w-full p-4 bg-slate-50 rounded-2xl font-bold text-xs uppercase outline-none text-indigo-700">
                        <option value="full">1. ADMINISTRACIÓN TOTAL (Crear / Editar / Borrar en Panel)</option>
                        <option value="readonly">2. SÓLO LECTURA / INSPECCIÓN (Supervisores / Vista sin edición)</option>
                        <option value="app_only">3. COLABORADOR (Solo Marcajes en App)</option>
                    </select>
                </div>

                <div>
                    <h4 className="font-black text-[10px] uppercase text-slate-400 mt-6 mb-2 tracking-widest">Permisos (Mostrar Botones al Colaborador)</h4>
                    <div className="grid grid-cols-2 gap-2">
                        {availableActions.map(a => (
                            <button 
                                key={a.id} 
                                type="button" 
                                onClick={() => togglePermission(a.id)} 
                                className={`p-4 rounded-2xl font-black text-[10px] uppercase border active:scale-95 transition-all ${permissions.includes(a.id) ? 'bg-indigo-600 text-white border-indigo-600 shadow-md' : 'bg-slate-50 text-slate-500 hover:bg-slate-100'}`}
                            >
                                {a.label}
                            </button>
                        ))}
                    </div>
                </div>

                <div>
                    <h4 className="font-black text-[10px] uppercase text-slate-400 mt-6 mb-2 tracking-widest">Exigir Foto al Marcar</h4>
                    <div className="grid grid-cols-2 gap-2">
                        {[{ id: 'entrada', label: 'Entrada' }, { id: 'salida', label: 'Salida' }, ...availableActions].map(a => (
                            <button 
                                key={'cam_' + a.id} 
                                type="button" 
                                onClick={() => toggleCamera(a.id)} 
                                className={`p-4 rounded-2xl font-black text-[10px] uppercase border active:scale-95 transition-all flex items-center justify-center gap-1 ${cameraActions.includes(a.id) ? 'bg-emerald-500 text-white border-emerald-500 shadow-md' : 'bg-slate-50 text-slate-500 hover:bg-slate-100'}`}
                            >
                                <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"></path><path strokeLinecap="round" strokeLinejoin="round" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>
                                {a.label}
                            </button>
                        ))}
                    </div>
                </div>

                <div className="flex gap-3 mt-6 pt-2">
                    {editingRoleOriginalName && (
                        <button type="button" onClick={handleCancelRoleEdit} className="w-1/3 py-4 bg-slate-100 text-slate-500 font-black rounded-2xl uppercase tracking-widest text-[10px]">
                            Cancelar
                        </button>
                    )}
                    <button onClick={handleSaveRole} className="flex-1 py-4 bg-indigo-600 text-white font-black rounded-2xl uppercase shadow-lg active:scale-95 transition-all tracking-widest text-[10px] hover:bg-indigo-700">
                        Guardar Perfil
                    </button>
                </div>
            </div>

            {/* LISTADO DE ROLES REGISTRADOS */}
            <div className="space-y-4">
                <h3 className="font-black text-sm uppercase tracking-widest text-slate-800 border-b border-slate-200 pb-3 mb-2">Roles Configurados</h3>
                {allCombinedRoles.map(r => {
                    const rName = r.name;
                    const rLabel = r.label || rName.toUpperCase();
                    const rPerms = r.permissions || [];
                    
                    const isReadOnlyRole = (r.accessLevel === 'readonly' || r.accessLevel === 'read_only');
                    const isAppOnlyRole = (r.accessLevel === 'app_only');

                    const levelBadge = isReadOnlyRole
                        ? { bg: 'bg-amber-100 text-amber-800 border-amber-200', text: 'Sólo Lectura' }
                        : isAppOnlyRole
                        ? { bg: 'bg-slate-100 text-slate-700 border-slate-200', text: 'App Colaborador' }
                        : { bg: 'bg-indigo-50 text-indigo-700 border-indigo-200', text: 'Total' };

                    // Convertir IDs a nombres legibles
                    const permLabels = rPerms.map(pid => {
                        const found = availableActions.find(a => a.id === pid);
                        return found ? found.label : pid;
                    });

                    return (
                        <div key={rName} className="bg-white p-6 rounded-[2.5rem] flex flex-col md:flex-row justify-between items-start md:items-center shadow-sm gap-4 border border-slate-100 hover:border-indigo-200 transition-all">
                            <div className="space-y-1">
                                <h4 className="font-black text-slate-800 uppercase flex items-center gap-2">
                                    {rLabel} 
                                    <span className={`text-[9px] px-2 py-0.5 rounded-full font-black uppercase tracking-wider border ${levelBadge.bg}`}>
                                        {levelBadge.text}
                                    </span>
                                </h4>
                                <p className="text-[10px] text-slate-400 font-bold uppercase tracking-wider pt-1">
                                    Permisos: <span className="text-slate-600">{permLabels.join(' • ') || 'Ninguno'}</span>
                                </p>
                            </div>
                            <button onClick={() => handleEditRoleClick(r)} className="px-6 py-3 bg-indigo-50 text-indigo-600 hover:bg-indigo-600 hover:text-white rounded-xl font-black uppercase text-[10px] active:scale-95 transition-all shadow-sm">
                                Editar
                            </button>
                        </div>
                    );
                })}
            </div>
        </div>
    );
};