import { useEffect, useMemo, useState } from 'react'; import { useSearchParams } from 'react-router-dom'; import { api } from '../../api/client.js'; import ImageUploadField from '../../components/ImageUploadField.jsx'; import TextStyleWidget from '../../components/TextStyleWidget.jsx'; import SortableList, { saveReorder } from '../../components/admin/SortableList.jsx'; import VehicleCatalogDialog from '../../components/admin/VehicleCatalogDialog.jsx'; import AiImageGenerator from '../../components/admin/AiImageGenerator.jsx'; import { useAuth } from '../../context/AuthContext.jsx'; import { useToast, useUnsavedChanges } from '../../context/AdminUiContext.jsx'; import { Button, Card, EmptyState, Field, Icon, IconButton, Input, PageHeader, Select, SlideOver } from '../../components/ui/index.jsx'; // Aufbau wie bei den Paketen: links die Marken, rechts die Modelle der gewaehlten Marke. // Sortiert wird immer innerhalb einer Marke (so erscheinen sie auch auf der Website); "Alle // Marken" ist zum Suchen da. Bearbeiten im Seitenpanel. const emptyForm = { name: '', brand_id: '', image_path: '', sort_order: 0 }; const normalize = (s) => String(s || '') .toLowerCase() .replace(/ä/g, 'ae') .replace(/ö/g, 'oe') .replace(/ü/g, 'ue') .replace(/ß/g, 'ss'); export default function Models() { const toast = useToast(); const { hasPermission } = useAuth(); const canPackages = hasPermission('packages.manage'); const [searchParams, setSearchParams] = useSearchParams(); const [models, setModels] = useState(null); const [brands, setBrands] = useState([]); const [packageCounts, setPackageCounts] = useState(null); // { [modelId]: { total, visible } } const [form, setForm] = useState(emptyForm); const [initialForm, setInitialForm] = useState(emptyForm); // null = Panel zu, 'new' = neues Modell, sonst die id des bearbeiteten Modells. const [editing, setEditing] = useState(null); const [error, setError] = useState(''); const [saving, setSaving] = useState(false); const [search, setSearch] = useState(''); const [catalogOpen, setCatalogOpen] = useState(false); const dirty = JSON.stringify(form) !== JSON.stringify(initialForm); useUnsavedChanges(editing !== null && dirty, 'models'); const load = () => { api.get('/models').then(setModels).catch(() => setModels([])); api.get('/brands').then(setBrands).catch(() => {}); // Nur fuer die Anzeige "3 Pakete" / "keine Pakete" je Modell. if (canPackages) { api .get('/packages') .then((rows) => setPackageCounts( rows.reduce((acc, p) => { const c = acc[p.car_model_id] || { total: 0, visible: 0 }; return { ...acc, [p.car_model_id]: { total: c.total + 1, visible: c.visible + (p.is_hidden ? 0 : 1) } }; }, {}), ), ) .catch(() => {}); } }; useEffect(load, []); // eslint-disable-line react-hooks/exhaustive-deps // Gewaehlte Marke steht in der Adresse (?marke=…), "alle" = alle Marken. Ohne Angabe die // erste Marke - eine Liste mit allen (evtl. ueber 1.000) Modellen hilft im Alltag nicht. const brandParam = searchParams.get('marke'); const brandSel = brandParam === 'alle' ? 'all' : Number(brandParam) || Number(brands[0]?.id) || null; const activeBrand = brands.find((b) => Number(b.id) === brandSel) || null; const canSort = brandSel !== 'all' && !search.trim(); const selectBrand = (id) => { setSearch(''); setSearchParams(id === 'all' ? { marke: 'alle' } : { marke: String(id) }); }; const brandStats = useMemo(() => { const stats = {}; (models || []).forEach((m) => { const s = (stats[m.brand_id] ||= { count: 0, empty: 0 }); s.count += 1; if (packageCounts && !packageCounts[m.id]?.visible) s.empty += 1; }); return stats; }, [models, packageCounts]); const visible = useMemo(() => { const list = brandSel === 'all' ? models || [] : (models || []).filter((m) => Number(m.brand_id) === brandSel); const tokens = normalize(search).split(/\s+/).filter(Boolean); if (!tokens.length) return list; return list.filter((m) => tokens.every((t) => normalize(`${m.brand_name} ${m.name}`).includes(t))); }, [models, brandSel, search]); const openPanel = (model) => { const next = model ? { name: model.name, brand_id: model.brand_id, image_path: model.image_path || '', sort_order: model.sort_order } : { ...emptyForm, brand_id: activeBrand?.id ?? '' }; setEditing(model ? model.id : 'new'); setForm(next); setInitialForm(next); setError(''); }; const closePanel = () => { if (dirty && !window.confirm('Ungespeicherte Änderungen verwerfen?')) return; setEditing(null); setForm(emptyForm); setInitialForm(emptyForm); }; const handleSubmit = async (e) => { e.preventDefault(); setError(''); setSaving(true); const payload = { ...form, brand_id: Number(form.brand_id) }; try { if (editing !== 'new') { await api.put(`/models/${editing}`, payload); } else { const sort = (models || []) .filter((m) => Number(m.brand_id) === payload.brand_id) .reduce((max, m) => Math.max(max, Number(m.sort_order) || 0), 0) + 10; await api.post('/models', { ...payload, sort_order: sort }); } toast.success(editing !== 'new' ? 'Modell gespeichert.' : 'Modell angelegt.'); setInitialForm(form); setEditing(null); load(); } catch (err) { setError(err.message); } finally { setSaving(false); } }; // Das KI-Bild speichert der Server direkt am Modell - Formular und Liste nur nachziehen, // sonst wuerde "Speichern" das alte Bild zuruecksetzen. const handleAiImage = (path) => { setForm((f) => ({ ...f, image_path: path })); setInitialForm((f) => ({ ...f, image_path: path })); setModels((list) => list.map((m) => (m.id === editing ? { ...m, image_path: path, ai_request_id: null } : m))); toast.success('KI-Bild als Modellbild übernommen.'); }; const handleDelete = async (model) => { const count = packageCounts?.[model.id]?.total || 0; const detail = count > 0 ? ` und ${count} Paket${count === 1 ? '' : 'e'} mit allen Produkten` : ''; if (!window.confirm(`„${model.brand_name} ${model.name}“${detail} wirklich löschen?`)) return; try { await api.delete(`/models/${model.id}`); if (editing === model.id) setEditing(null); toast.success('Modell gelöscht.'); load(); } catch (err) { toast.error(`Löschen fehlgeschlagen: ${err.message}`); } }; // Die Modelle einer Marke in neuer Reihenfolge an ihre bisherigen Plaetze in der // Gesamtliste zuruecksetzen. const mergeIntoModels = (all, reordered) => { const queue = [...reordered]; return all.map((m) => (Number(m.brand_id) === brandSel ? queue.shift() : m)); }; const handleReorder = async (reordered) => { const previous = models; setModels(mergeIntoModels(models, reordered)); try { const saved = await saveReorder('models', reordered); setModels((current) => mergeIntoModels(current, saved)); toast.success('Reihenfolge gespeichert.'); } catch (err) { setModels(previous); toast.error(`Reihenfolge konnte nicht gespeichert werden: ${err.message}`); } }; const packageInfo = (model) => { if (!packageCounts) return null; const c = packageCounts[model.id]; if (!c?.visible) { return {c?.total ? 'Alle Pakete ausgeblendet' : 'Noch keine Pakete'}; } return `${c.visible} Paket${c.visible === 1 ? '' : 'e'}${c.total > c.visible ? ` · ${c.total - c.visible} ausgeblendet` : ''}`; }; const brandButton = (id, label, stats) => { const active = brandSel === (id === 'all' ? 'all' : Number(id)); return ( ); }; return (
} /> {models !== null && brands.length === 0 ? ( } /> ) : (
{/* Marken: am Desktop als Liste, am Handy als Auswahlfeld. */}
{brands.map((b) => brandButton(b.id, b.name, brandStats[b.id]))}
{brandButton('all', 'Alle Marken', { count: models?.length ?? 0 })}
setSearch(e.target.value)} placeholder={brandSel === 'all' ? 'Alle Modelle durchsuchen …' : `In ${activeBrand?.name || 'Marke'} suchen …`} className="h-9 pl-9" />
{visible.length} Modell{visible.length === 1 ? '' : 'e'} {brandSel === 'all' && ' · zum Sortieren eine Marke wählen'}
{models === null ? (
    {[0, 1, 2, 3].map((i) => (
  • ))}
) : visible.length === 0 ? ( search.trim() ? (

Kein Modell passt zu „{search}“.

) : ( } /> ) ) : ( {(model, handle) => (
{canSort && {handle}}
{canPackages && ( )} {canPackages && } openPanel(model)} /> handleDelete(model)} />
)}
)}
)} {editing !== 'new' && editing !== null && canPackages && ( )} } > setForm({ ...form, name: e.target.value })} /> {editing !== 'new' && editing !== null && ( )} setForm({ ...form, image_path: path })} label="Bild (optional)" /> {editing !== 'new' && editing !== null && ( setModels((list) => list.map((m) => (m.id === editing ? { ...m, ai_request_id: requestId } : m)))} /> )} setCatalogOpen(false)} onImported={load} />
); }