import React, { useEffect, useRef, useState } from 'react' import { Package } from 'lucide-react' import { packingApi } from '../../api/client' import { useTripStore } from '../../store/tripStore' import { useToast } from '../shared/Toast' import { useTranslation } from '../../i18n' interface Template { id: number name: string item_count: number } interface ApplyTemplateButtonProps { tripId: number style: React.CSSProperties className?: string } // Dropdown-Button um ein Packing-Template auf den aktuellen Trip anzuwenden. // Rendert nichts wenn keine Templates existieren. export default function ApplyTemplateButton({ tripId, style, className }: ApplyTemplateButtonProps): React.ReactElement | null { const [templates, setTemplates] = useState([]) const [open, setOpen] = useState(false) const [applying, setApplying] = useState(false) const dropRef = useRef(null) const toast = useToast() const { t } = useTranslation() useEffect(() => { packingApi.listTemplates(tripId).then(d => setTemplates(d.templates || [])).catch(() => {}) }, [tripId]) useEffect(() => { if (!open) return const handler = (e: MouseEvent) => { if (dropRef.current && !dropRef.current.contains(e.target as Node)) setOpen(false) } document.addEventListener('mousedown', handler) return () => document.removeEventListener('mousedown', handler) }, [open]) const handleApply = async (templateId: number) => { setApplying(true) try { const data = await packingApi.applyTemplate(tripId, templateId) useTripStore.setState(s => ({ packingItems: [...s.packingItems, ...(data.items || [])] })) toast.success(t('packing.templateApplied', { count: data.count })) setOpen(false) } catch { toast.error(t('packing.templateError')) } finally { setApplying(false) } } if (templates.length === 0) return null return (
{open && (
{templates.map(tmpl => ( ))}
)}
) }