const { useState } = React;

window.AdminAvisos = function({ globalUsers, reminders, showToast, refreshData }) {
    const [title, setTitle] = useState('');
    const [message, setMessage] = useState('');
    const [targetUsers, setTargetUsers] = useState([]);
    const [selectAll, setSelectAll] = useState(true);

    const handleSendNotice = async (e) => {
        e.preventDefault();
        if (!title.trim() || !message.trim()) return showToast("Título y mensaje son requeridos.");

        const usersToSend = selectAll ? globalUsers.map(u => u.id) : targetUsers;
        if (usersToSend.length === 0) return showToast("Debes seleccionar al menos un usuario.");

        try {
            const res = await window.apiCall('save_reminder', {
                title: title.trim(),
                message: message.trim(),
                targetUsers: usersToSend,
                createdAt: Date.now()
            });

            if (res && res.success) {
                setTitle('');
                setMessage('');
                setSelectAll(true);
                setTargetUsers([]);
                showToast("Aviso difundido con éxito.");
                if (refreshData) await refreshData();
            } else {
                showToast("Error al difundir: " + (res.error || "Desconocido"));
            }
        } catch (err) {
            showToast("Error de conexión al enviar aviso.");
        }
    };

    const handleDeleteReminder = async (id) => {
        await window.apiCall('delete_reminder', { id });
        showToast("Aviso eliminado.");
        if (refreshData) await refreshData();
    };

    return (
        <div className="grid lg:grid-cols-3 gap-6 fade-in">
            <form onSubmit={handleSendNotice} className="bg-white p-8 rounded-[3rem] shadow-sm space-y-4 h-fit border-t-[12px] border-indigo-600">
                <div>
                    <h3 className="font-black text-xl text-slate-900">Nuevo Aviso General</h3>
                    <p className="text-slate-400 font-bold text-[10px] uppercase tracking-widest mt-1">Llegará a la campanita de los colaboradores</p>
                </div>

                <div>
                    <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Título del Aviso</label>
                    <input 
                        value={title} 
                        onChange={e => setTitle(e.target.value)} 
                        placeholder="Título impactante..." 
                        className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none text-xs focus:ring-2 focus:ring-indigo-100" 
                        required 
                    />
                </div>

                <div>
                    <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Contenido del Mensaje</label>
                    <textarea 
                        value={message} 
                        onChange={e => setMessage(e.target.value)} 
                        placeholder="Escribe el mensaje que leerán tus colaboradores..." 
                        className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none text-xs h-32 resize-none focus:ring-2 focus:ring-indigo-100" 
                        required 
                    />
                </div>

                <div>
                    <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-2 block">Destinatarios</label>
                    <div className="flex items-center gap-2 mb-3 bg-slate-50 p-3 rounded-xl cursor-pointer" onClick={() => setSelectAll(!selectAll)}>
                        <input type="checkbox" checked={selectAll} onChange={e => setSelectAll(e.target.checked)} className="w-4 h-4 accent-indigo-600 cursor-pointer" />
                        <span className="text-[11px] font-black text-slate-700 uppercase">Enviar a todo el personal ({globalUsers.length})</span>
                    </div>

                    {!selectAll && (
                        <div className="max-h-40 overflow-y-auto space-y-1 p-2 bg-slate-50 rounded-xl border border-slate-100 no-scrollbar">
                            {globalUsers.map(u => (
                                <label key={u.id} className="flex items-center gap-2 p-2 hover:bg-white rounded-lg cursor-pointer text-[10px] font-bold text-slate-600">
                                    <input 
                                        type="checkbox" 
                                        checked={targetUsers.includes(u.id)} 
                                        onChange={() => setTargetUsers(prev => prev.includes(u.id) ? prev.filter(id => id !== u.id) : [...prev, u.id])} 
                                        className="w-4 h-4 accent-indigo-600" 
                                    />
                                    <span>{u.name} (@{u.alias})</span>
                                </label>
                            ))}
                        </div>
                    )}
                </div>

                <button type="submit" className="w-full py-5 bg-indigo-600 text-white font-black rounded-2xl uppercase tracking-widest text-[10px] shadow-xl active:scale-95 transition-all hover:bg-indigo-700">
                    Difundir Aviso
                </button>
            </form>

            <div className="lg:col-span-2 space-y-4">
                <h3 className="font-black text-sm uppercase tracking-widest text-slate-800 border-b border-slate-200 pb-3 mb-4">Avisos Emitidos Activos</h3>
                {(!reminders || reminders.length === 0) ? (
                    <div className="bg-white rounded-[2.5rem] p-8 text-center border border-slate-100 shadow-sm">
                        <p className="text-xs font-bold text-slate-400">No hay avisos registrados actualmente.</p>
                    </div>
                ) : (
                    reminders.map(r => {
                        const readCount = r.completedBy ? Object.keys(r.completedBy).length : 0;
                        const totalTargets = r.targetUsers ? r.targetUsers.length : 0;

                        return (
                            <div key={r.id} className="bg-white p-6 rounded-[2.5rem] shadow-sm border border-slate-100 flex flex-col md:flex-row justify-between items-start md:items-center gap-4 hover:border-indigo-100 transition-all">
                                <div className="space-y-1 flex-1">
                                    <div className="flex items-center gap-2">
                                        <span className="w-2 h-2 rounded-full bg-indigo-600"></span>
                                        <h4 className="font-black text-slate-900 text-sm uppercase">{r.title}</h4>
                                    </div>
                                    <p className="text-[11px] text-slate-600 font-medium leading-relaxed bg-slate-50 p-3 rounded-xl mt-2">{r.message}</p>
                                    <div className="flex items-center gap-4 text-[9px] font-black uppercase text-slate-400 tracking-wider pt-2">
                                        <span>Confirmados: <strong className="text-indigo-600">{readCount} de {totalTargets || globalUsers.length}</strong></span>
                                    </div>
                                </div>
                                <button onClick={() => handleDeleteReminder(r.id)} className="px-4 py-2 bg-red-50 text-red-600 hover:bg-red-100 rounded-xl font-black text-[9px] uppercase tracking-widest transition-colors active:scale-95">
                                    Eliminar
                                </button>
                            </div>
                        );
                    })
                )}
            </div>
        </div>
    );
};