import React, { useState } from 'react'; import { useTranslation } from 'react-i18next'; import { History, RotateCcw, ChevronDown, ChevronRight, User } from 'lucide-react'; import { useEntityHistory, useRestoreFromHistory } from '@/api/entityHistory'; import { Button } from '@/components/ui/Button'; import { Badge } from '@/components/ui/Badge'; import { Skeleton } from '@/components/ui/Skeleton'; import { useToast } from '@/components/ui/Toast'; import { formatDistanceToNow } from 'date-fns'; import { de, enUS } from 'date-fns/locale'; interface HistoryPanelProps { entityType: string; entityId: string; limit?: number; } const actionConfig = { create: { variant: 'success' as const, labelKey: 'history.actionCreate' }, update: { variant: 'primary' as const, labelKey: 'history.actionUpdate' }, delete: { variant: 'danger' as const, labelKey: 'history.actionDelete' }, }; export function HistoryPanel({ entityType, entityId, limit = 50 }: HistoryPanelProps) { const { t, i18n } = useTranslation(); const toast = useToast(); const { data: history, isLoading } = useEntityHistory(entityType, entityId, limit); const restoreMutation = useRestoreFromHistory(); const [expandedId, setExpandedId] = useState(null); const dateLocale = i18n.language === 'de' ? de : enUS; const handleRestore = async (historyId: string) => { try { await restoreMutation.mutateAsync(historyId); toast.success(t('history.restored', 'Version wiederhergestellt')); } catch { toast.error(t('history.restoreError', 'Wiederherstellung fehlgeschlagen')); } }; if (isLoading) { return (
); } const entries = history?.items ?? []; if (entries.length === 0) { return (
); } return (

    {entries.map((entry) => { const config = actionConfig[entry.action] || actionConfig.update; const isExpanded = expandedId === entry.id; const changes = entry.changes || {}; const changeKeys = Object.keys(changes); return (
  1. {isExpanded && (
    {changeKeys.length > 0 && (

    {t('history.changes', 'Änderungen')}:

    {changeKeys.map((key) => (
    {key}: {String(changes[key].old ?? '—')} {String(changes[key].new ?? '—')}
    ))}
    )}
    )}
  2. ); })}
); }