mitai-jinkendo/frontend/src/components/FoodRecipeEditor.jsx

92 lines
3.2 KiB
React
Raw Normal View History

import { useState } from 'react'
import { api } from '../utils/api'
import FoodRecipeDialog from './FoodRecipeDialog'
export default function FoodRecipeEditor({ recipes, learned, onChanged }) {
const [open, setOpen] = useState(false)
const [editing, setEditing] = useState(null)
const [error, setError] = useState(null)
const startNew = () => {
setEditing('new')
setError(null)
setOpen(true)
}
const startEdit = (r) => {
setEditing(r)
setError(null)
setOpen(true)
}
const save = async (body) => {
if (editing === 'new') await api.createNutritionRecipe(body)
else await api.updateNutritionRecipe(editing.id, body)
setEditing(null)
onChanged?.()
}
const remove = async (id) => {
if (!confirm('Liste wirklich löschen?')) return
try {
await api.deleteNutritionRecipe(id)
if (editing && editing !== 'new' && editing.id === id) setEditing(null)
onChanged?.()
} catch (e) {
setError(e.message)
}
}
return (
<div style={{ marginTop: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
<h3 style={{ fontSize: 14, margin: 0 }}>Eigene Listen / Kombinationen ({recipes.length})</h3>
<button type="button" className="btn btn-secondary" style={{ fontSize: 12 }} onClick={() => { setOpen((v) => !v); if (open) setEditing(null) }}>
{open ? 'Einklappen' : 'Anzeigen'}
</button>
</div>
{open && (
<div style={{ marginTop: 8 }}>
{error && <div style={{ color: 'var(--danger)', fontSize: 13, marginBottom: 8 }}>{error}</div>}
<button type="button" className="btn btn-secondary btn-full" onClick={startNew}>Liste anlegen</button>
{recipes.map((r) => (
<div key={r.id} style={{ borderTop: '1px solid var(--border)', padding: '8px 0', marginTop: 8 }}>
<div style={{ fontWeight: 600 }}>{r.name_raw}</div>
<div style={{ fontSize: 12, color: 'var(--text3)' }}>
{(r.ingredients || []).length} Zutaten · {r.portions || 1} Portionen
{r.source === 'manual' ? ' · selbst angelegt' : ''}
</div>
<div style={{ display: 'flex', gap: 8, marginTop: 6 }}>
<button type="button" className="btn btn-secondary" style={{ fontSize: 12 }} onClick={() => startEdit(r)}>Bearbeiten</button>
<button type="button" className="btn btn-secondary" style={{ fontSize: 12 }} onClick={() => remove(r.id)}>Löschen</button>
</div>
</div>
))}
</div>
)}
{editing === 'new' && (
<FoodRecipeDialog
title="Liste anlegen"
learned={learned}
submitLabel="Liste anlegen"
onSave={save}
onClose={() => setEditing(null)}
/>
)}
{editing && editing !== 'new' && (
<FoodRecipeDialog
key={editing.id}
title="Liste bearbeiten"
defaultName={editing.name_raw}
defaultPortions={editing.portions}
defaultIngredients={editing.ingredients}
learned={learned}
submitLabel="Liste speichern"
onSave={save}
onClose={() => setEditing(null)}
/>
)}
</div>
)
}