import React, { useCallback, useMemo, useState } from 'react'; // TODO: P2-F24 — Replace hardcoded ENTITY_TYPES with dynamic config import { useTranslation } from 'react-i18next'; import { Trash2, RotateCcw } from 'lucide-react'; import { Button } from '@/components/ui/Button'; import { Card } from '@/components/ui/Card'; import { Select } from '@/components/ui/Select'; import { Pagination } from '@/components/ui/Pagination'; import { EmptyState } from '@/components/ui/EmptyState'; import { Skeleton } from '@/components/ui/Skeleton'; import { Badge } from '@/components/ui/Badge'; import { useToast } from '@/components/ui/Toast'; import { useTrashList, useRestoreFromHistory, useBulkRestore, type TrashItem } from '@/api/entityHistory'; import { formatDateShort } from '@/utils/date'; const PAGE_SIZE = 50; const ENTITY_TYPES = ['contact', 'task', 'calendar_entry', 'dms_file', 'mail'] as const; type EntityType = (typeof ENTITY_TYPES)[number]; /** Coerce an unknown snapshot value to a string, or '' when null/undefined. */ function str(value: unknown): string { return value === null || value === undefined ? '' : String(value); } /** Extract a display name/subject from the snapshot_before payload per entity type. */ function getDisplayName(item: TrashItem): string { const snap = item.snapshot_before ?? {}; switch (item.entity_type) { case 'contact': { const first = str(snap.first_name); const last = str(snap.last_name); const company = str(snap.company_name); const full = [first, last].filter(Boolean).join(' '); return full || company || str(snap.name) || '—'; } case 'task': case 'calendar_entry': return str(snap.title) || str(snap.subject) || str(snap.name) || '—'; case 'dms_file': return str(snap.name) || str(snap.filename) || str(snap.original_name) || '—'; case 'mail': return str(snap.subject) || str(snap.name) || '—'; default: return str(snap.name) || str(snap.title) || str(snap.subject) || '—'; } } export function TrashPage() { const { t } = useTranslation(); const toast = useToast(); const [entityType, setEntityType] = useState(''); const [page, setPage] = useState(1); const [selected, setSelected] = useState>(new Set()); const offset = (page - 1) * PAGE_SIZE; const { data, isLoading, isFetching } = useTrashList(entityType || undefined, PAGE_SIZE, offset); const restoreMutation = useRestoreFromHistory(); const bulkRestoreMutation = useBulkRestore(); const items = data?.items ?? []; const total = data?.total ?? 0; const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE)); const entityTypeOptions = useMemo( () => [ { value: '', label: t('trash.allTypes', 'Alle Typen') }, ...ENTITY_TYPES.map((type) => ({ value: type, label: t(`trash.types.${type}`) })), ], [t] ); const handleFilterChange = useCallback((value: string) => { setEntityType(value); setPage(1); setSelected(new Set()); }, []); const toggleSelect = useCallback((historyId: string) => { setSelected((prev) => { const next = new Set(prev); if (next.has(historyId)) { next.delete(historyId); } else { next.add(historyId); } return next; }); }, []); const toggleSelectAll = useCallback(() => { setSelected((prev) => { if (prev.size === items.length && items.length > 0) { return new Set(); } return new Set(items.map((item) => item.history_id)); }); }, [items]); const handleSingleRestore = useCallback( async (historyId: string) => { try { await restoreMutation.mutateAsync(historyId); toast.success(t('trash.restored', 'Wiederhergestellt')); setSelected((prev) => { const next = new Set(prev); next.delete(historyId); return next; }); } catch { toast.error(t('trash.restoreError', 'Wiederherstellung fehlgeschlagen')); } }, [restoreMutation, toast, t] ); const handleBulkRestore = useCallback(async () => { if (selected.size === 0) return; try { const result = await bulkRestoreMutation.mutateAsync(Array.from(selected)); if (result.failed > 0) { toast.warning( t('trash.bulkPartial', '{{succeeded}} wiederhergestellt, {{failed}} fehlgeschlagen', { succeeded: result.succeeded, failed: result.failed, }) ); } else { toast.success(t('trash.bulkRestored', '{{count}} Einträge wiederhergestellt', { count: result.succeeded })); } setSelected(new Set()); } catch { toast.error(t('trash.bulkRestoreError', 'Massen-Wiederherstellung fehlgeschlagen')); } }, [selected, bulkRestoreMutation, toast, t]); const handlePageChange = useCallback((nextPage: number) => { setPage(nextPage); setSelected(new Set()); }, []); return (
0} onChange={toggleSelectAll} className="h-5 w-5 rounded border-secondary-300 text-primary-600 focus:ring-primary-500" aria-label={t('trash.selectAll', 'Alle auswählen')} /> {t('trash.entityType', 'Typ')} {t('trash.name', 'Name')} {t('trash.deletedAt', 'Gelöscht am')} {t('trash.actions', 'Aktionen')} {items.map((item) => { const isSelected = selected.has(item.history_id); return ( toggleSelect(item.history_id)} className="h-5 w-5 rounded border-secondary-300 text-primary-600 focus:ring-primary-500" aria-label={t('trash.selectItem', 'Eintrag auswählen')} /> {t(`trash.types.${item.entity_type}`)} {getDisplayName(item)} {item.deleted_at ? formatDateShort(item.deleted_at) || '—' : '—'} ); })}
)}
); }