Spaces:
Running
Running
File size: 13,386 Bytes
188bf54 28b0bde 188bf54 28b0bde 188bf54 28b0bde 188bf54 28b0bde 188bf54 28b0bde | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | import React, { useState, useEffect } from 'react';
import { db, storage } from '../../firebase/config';
import { ref, onValue, push, set, remove, update } from 'firebase/database';
import { ref as sRef, uploadBytes, getDownloadURL } from 'firebase/storage';
import { Plus, Trash2, Edit3, X, Image as ImageIcon, Save, Palette, Upload, Loader2, ListTree, ChefHat } from 'lucide-react';
export default function MenuEditor() {
const [products, setProducts] = useState([]);
const [inventory, setInventory] = useState([]);
const [formData, setFormData] = useState({
name: '', price: '', category: 'Principales', image: '',
variants: [], ingredients: []
});
const [editingItem, setEditingItem] = useState(null);
const [isModalOpen, setIsModalOpen] = useState(false);
const [menuTheme, setMenuTheme] = useState('dark');
const [uploading, setUploading] = useState(false);
useEffect(() => {
onValue(ref(db, 'menu'), (snapshot) => {
const data = snapshot.val();
setProducts(data ? Object.keys(data).map(id => ({ id, ...data[id] })) : []);
});
onValue(ref(db, 'inventory'), (snapshot) => {
const data = snapshot.val();
setInventory(data ? Object.keys(data).map(id => ({ id, ...data[id] })) : []);
});
onValue(ref(db, 'config/menuTheme'), (snapshot) => {
if (snapshot.exists()) setMenuTheme(snapshot.val());
});
}, []);
const handleToggleTheme = async () => {
await set(ref(db, 'config/menuTheme'), menuTheme === 'dark' ? 'light' : 'dark');
};
const handleImageUpload = async (e, isEditing = false) => {
const file = e.target.files[0];
if (!file || !file.type.startsWith('image/')) return;
setUploading(true);
try {
const storagePath = `menu/${Date.now()}_${file.name}`;
const fileRef = sRef(storage, storagePath);
await uploadBytes(fileRef, file);
const url = await getDownloadURL(fileRef);
if (isEditing) setEditingItem(prev => ({ ...prev, image: url }));
else setFormData(prev => ({ ...prev, image: url }));
} catch (error) { console.error(error); } finally { setUploading(false); }
};
const handleAddProduct = async (e) => {
e.preventDefault();
if (!formData.name || !formData.price) return;
const newRef = push(ref(db, 'menu'));
await set(newRef, { ...formData, price: parseFloat(formData.price), active: true });
setFormData({ name: '', price: '', category: 'Principales', image: '', variants: [], ingredients: [] });
};
const handleDelete = async (id) => {
if(window.confirm('¿Eliminar producto?')) await remove(ref(db, `menu/${id}`));
};
const addIngredientToProduct = (isEditing) => {
const newIng = { id: '', qty: 1 };
if (isEditing) setEditingItem({ ...editingItem, ingredients: [...(editingItem.ingredients || []), newIng] });
else setFormData({ ...formData, ingredients: [...formData.ingredients, newIng] });
};
const handleSaveEdit = async () => {
const { id, ...updates } = editingItem;
await update(ref(db, `menu/${id}`), { ...updates, price: parseFloat(updates.price) });
setIsModalOpen(false);
};
return (
<div className="animate-fade-in" style={{ padding: '0 1rem' }}>
<header style={{ marginBottom: '2.5rem', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
<h2 className="text-gradient" style={{ fontSize: '2rem', fontWeight: '800', display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
<ChefHat size={28} /> Carta & Recetas
</h2>
<p style={{ color: 'var(--text-muted)' }}>Gestión de productos y consumo de insumos</p>
</div>
<button onClick={handleToggleTheme} className="btn-glass" style={{ padding: '0.8rem 1.25rem' }}>
Tema QR: {menuTheme.toUpperCase()}
</button>
</header>
<section className="glass-card" style={{ marginBottom: '3rem', padding: '1.5rem' }}>
<h3 style={{ marginBottom: '1.5rem', fontSize: '1.1rem' }}>Agregar Platillo</h3>
<form onSubmit={handleAddProduct} style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '1.25rem', alignItems: 'end' }}>
<div>
<label style={labelStyle}>Nombre</label>
<input type="text" value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})} style={inputStyle} />
</div>
<div>
<label style={labelStyle}>Precio Base ($)</label>
<input type="number" value={formData.price} onChange={e => setFormData({...formData, price: e.target.value})} style={inputStyle} />
</div>
<div>
<label style={labelStyle}>Categoría</label>
<select value={formData.category} onChange={e => setFormData({...formData, category: e.target.value})} style={inputStyle}>
{['Entradas', 'Bebidas', 'Fuertes', 'Postres', 'Pizzas', 'Combos'].map(c => <option key={c} value={c}>{c}</option>)}
</select>
</div>
<div style={{ display: 'flex', gap: '0.5rem' }}>
<button type="button" onClick={() => addIngredientToProduct(false)} className="btn-glass" style={{ flex: 1, padding: '0.8rem' }}>
<ListTree size={18} /> Insumos
</button>
<button type="submit" className="btn-primary" style={{ padding: '0.8rem 1.5rem', opacity: uploading ? 0.5 : 1 }}>
<Plus size={20} />
</button>
</div>
</form>
{formData.ingredients.length > 0 && (
<div style={{ marginTop: '1.5rem', display: 'flex', flexWrap: 'wrap', gap: '1rem' }}>
{formData.ingredients.map((ing, idx) => (
<div key={idx} className="glass-panel" style={{ padding: '0.5rem 1rem', display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
<select
value={ing.id}
onChange={e => {
const newIngs = [...formData.ingredients];
newIngs[idx].id = e.target.value;
setFormData({...formData, ingredients: newIngs});
}}
style={{...inputStyle, padding: '0.4rem', width: 'auto'}}
>
<option value="">Seleccionar Insumo</option>
{inventory.map(i => <option key={i.id} value={i.id}>{i.name}</option>)}
</select>
<input
type="number"
value={ing.qty}
onChange={e => {
const newIngs = [...formData.ingredients];
newIngs[idx].qty = parseFloat(e.target.value);
setFormData({...formData, ingredients: newIngs});
}}
style={{...inputStyle, padding: '0.4rem', width: '60px'}}
/>
<button type="button" onClick={() => setFormData({...formData, ingredients: formData.ingredients.filter((_, i) => i !== idx)})} style={{color: 'var(--primary)', background: 'none', border: 'none'}}><X size={16}/></button>
</div>
))}
</div>
)}
</section>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: '1.5rem' }}>
{products.map(item => (
<div key={item.id} className="glass-card" style={{ padding: '0', overflow: 'hidden' }}>
<div style={{ position: 'relative', height: '160px', background: 'rgba(255,255,255,0.05)' }}>
{item.image && <img src={item.image} alt={item.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />}
<div style={{ position: 'absolute', top: '10px', right: '10px', display: 'flex', gap: '5px' }}>
<button onClick={() => { setEditingItem({...item}); setIsModalOpen(true); }} style={actionBtnStyle}><Edit3 size={16} /></button>
<button onClick={() => handleDelete(item.id)} style={{...actionBtnStyle, color: 'var(--primary)'}}><Trash2 size={16} /></button>
</div>
</div>
<div style={{ padding: '1.25rem' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '0.5rem' }}>
<h4 style={{ fontWeight: '700' }}>{item.name}</h4>
<span style={{ color: 'var(--success)', fontWeight: '800' }}>${item.price}</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span style={{ fontSize: '0.7rem', color: 'var(--text-muted)', background: 'rgba(255,255,255,0.05)', padding: '2px 8px', borderRadius: '4px' }}>{item.category}</span>
{item.ingredients?.length > 0 && <span title="Tiene receta vinculada" style={{ color: 'var(--primary)' }}><ChefHat size={14} /></span>}
</div>
</div>
</div>
))}
</div>
{isModalOpen && editingItem && (
<div style={{ position: 'fixed', top: 0, left: 0, width: '100%', height: '100%', background: 'rgba(0,0,0,0.85)', display: 'flex', justifyContent: 'center', alignItems: 'center', zIndex: 1000, padding: '20px' }}>
<div className="glass-panel animate-scale-in" style={{ maxWidth: '600px', width: '100%', padding: '2rem', maxHeight: '90vh', overflowY: 'auto' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2rem' }}>
<h2 className="text-gradient">Editar: {editingItem.name}</h2>
<button onClick={() => setIsModalOpen(false)} style={{ background: 'none', border: 'none', color: '#fff' }}><X size={24} /></button>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
<div><label style={labelStyle}>Nombre</label><input type="text" value={editingItem.name} onChange={e => setEditingItem({...editingItem, name: e.target.value})} style={inputStyle} /></div>
<div><label style={labelStyle}>Precio</label><input type="number" value={editingItem.price} onChange={e => setEditingItem({...editingItem, price: e.target.value})} style={inputStyle} /></div>
</div>
<div>
<label style={labelStyle}>Receta (Consumo de insumos por venta)</label>
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
{(editingItem.ingredients || []).map((ing, i) => (
<div key={i} style={{ display: 'flex', gap: '0.5rem' }}>
<select value={ing.id} onChange={e => {
const ings = [...editingItem.ingredients];
ings[i].id = e.target.value;
setEditingItem({...editingItem, ingredients: ings});
}} style={{...inputStyle, flex: 2}}>
<option value="">Seleccionar Insumo</option>
{inventory.map(inv => <option key={inv.id} value={inv.id}>{inv.name}</option>)}
</select>
<input type="number" value={ing.qty} onChange={e => {
const ings = [...editingItem.ingredients];
ings[i].qty = parseFloat(e.target.value);
setEditingItem({...editingItem, ingredients: ings});
}} style={{...inputStyle, flex: 1}} />
<button onClick={() => setEditingItem({...editingItem, ingredients: editingItem.ingredients.filter((_, idx) => idx !== i)})} style={{color: 'var(--primary)'}}><Trash2 size={18} /></button>
</div>
))}
<button onClick={() => addIngredientToProduct(true)} className="btn-glass" style={{ padding: '0.5rem', fontSize: '0.8rem' }}><Plus size={14} /> Añadir Insumo</button>
</div>
</div>
<div style={{ display: 'flex', gap: '1rem', marginTop: '1rem' }}>
<label style={{ flex: 1, display: 'flex', alignItems: 'center', gap: '0.5rem', background: 'var(--primary)', padding: '0.8rem', borderRadius: '8px', cursor: 'pointer', justifyContent: 'center' }}>
<Upload size={18} /> {uploading ? 'Subiendo...' : 'Cambiar Imagen'}
<input type="file" hidden onChange={e => handleImageUpload(e, true)} accept="image/*" />
</label>
<button onClick={handleSaveEdit} className="btn-primary" style={{ flex: 1, padding: '0.8rem' }}><Save size={18} /> Guardar</button>
</div>
</div>
</div>
</div>
)}
</div>
);
}
const inputStyle = { width: '100%', padding: '0.8rem', borderRadius: '8px', background: 'rgba(255,255,255,0.05)', border: '1px solid var(--border-subtle)', color: '#fff', outline: 'none' };
const labelStyle = { display: 'block', fontSize: '0.8rem', color: 'var(--text-muted)', marginBottom: '0.4rem' };
const actionBtnStyle = { width: '32px', height: '32px', borderRadius: '8px', border: 'none', background: 'rgba(0,0,0,0.6)', color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' };
|