import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { History, RotateCcw, Undo, ChevronDown, ChevronRight } from 'lucide-react';
import { useEntityHistory, useRestoreFromHistory, useUndoLastAction } 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 HistoryViewerProps {
  entityType: string;
  entityId: string;
}

const actionConfig = {
  create: { variant: 'success' as const, label: 'Erstellt' },
  update: { variant: 'primary' as const, label: 'Aktualisiert' },
  delete: { variant: 'danger' as const, label: 'Gelöscht' },
};

export function HistoryViewer({ entityType, entityId }: HistoryViewerProps) {
  const { t, i18n } = useTranslation();
  const toast = useToast();
  const { data: history, isLoading } = useEntityHistory(entityType, entityId);
  const restoreMutation = useRestoreFromHistory();
  const undoMutation = useUndoLastAction();
  const [expandedId, setExpandedId] = useState<string | null>(null);

  const dateLocale = i18n.language === 'de' ? de : enUS;

  const handleUndo = async () => {
    try {
      await undoMutation.mutateAsync({ entityType, entityId });
      toast.success(t('history.undone', 'Aktion rückgängig gemacht'));
    } catch {
      toast.error(t('history.undoError', 'Rückgängig machen fehlgeschlagen'));
    }
  };

  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 (
      <div className="space-y-3">
        <Skeleton className="h-8 w-32" />
        <Skeleton className="h-16 w-full" />
        <Skeleton className="h-16 w-full" />
      </div>
    );
  }

  const entries = history?.items ?? [];

  if (entries.length === 0) {
    return (
      <div className="text-center py-8 text-secondary-400">
        <History className="w-8 h-8 mx-auto mb-2 opacity-50" aria-hidden="true" />
        <p className="text-sm">{t('history.empty', 'Keine Änderungshistorie vorhanden')}</p>
      </div>
    );
  }

  return (
    <div className="space-y-4" data-testid="history-viewer">
      {/* Undo button */}
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold text-secondary-900 flex items-center gap-2">
          <History className="w-5 h-5" aria-hidden="true" />
          {t('history.title', 'Änderungshistorie')}
        </h3>
        <Button
          variant="secondary"
          size="sm"
          onClick={handleUndo}
          isLoading={undoMutation.isPending}
          icon={<Undo className="w-4 h-4" />}
        >
          {t('history.undo', 'Rückgängig')}
        </Button>
      </div>

      {/* History entries */}
      <div className="space-y-2">
        {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 (
            <div
              key={entry.id}
              className="border border-secondary-200 rounded-lg overflow-hidden"
            >
              <button
                onClick={() => setExpandedId(isExpanded ? null : entry.id)}
                className="w-full flex items-center justify-between p-3 hover:bg-secondary-50 transition-colors text-left"
                aria-expanded={isExpanded}
              >
                <div className="flex items-center gap-3">
                  {isExpanded ? (
                    <ChevronDown className="w-4 h-4 text-secondary-400" aria-hidden="true" />
                  ) : (
                    <ChevronRight className="w-4 h-4 text-secondary-400" aria-hidden="true" />
                  )}
                  <Badge variant={config.variant}>{config.label}</Badge>
                  <span className="text-sm text-secondary-500">
                    {formatDistanceToNow(new Date(entry.created_at), { addSuffix: true, locale: dateLocale })}
                  </span>
                </div>
                {changeKeys.length > 0 && (
                  <span className="text-xs text-secondary-400">
                    {changeKeys.length} {t('history.fieldsChanged', 'Felder geändert')}
                  </span>
                )}
              </button>

              {isExpanded && (
                <div className="px-4 pb-3 border-t border-secondary-100">
                  {/* Changes diff */}
                  {changeKeys.length > 0 && (
                    <div className="mt-3 space-y-1">
                      <p className="text-xs font-medium text-secondary-500 mb-2">{t('history.changes', 'Änderungen')}:</p>
                      {changeKeys.map((key) => (
                        <div key={key} className="flex items-start gap-2 text-sm">
                          <span className="font-mono text-secondary-600 min-w-[120px]">{key}:</span>
                          <span className="text-danger-600 line-through">
                            {String(changes[key].old ?? '—')}
                          </span>
                          <span className="text-secondary-400">→</span>
                          <span className="text-success-600">
                            {String(changes[key].new ?? '—')}
                          </span>
                        </div>
                      ))}
                    </div>
                  )}

                  {/* Restore button */}
                  <div className="mt-3 flex justify-end">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleRestore(entry.id)}
                      isLoading={restoreMutation.isPending}
                      icon={<RotateCcw className="w-3.5 h-3.5" />}
                    >
                      {t('history.restore', 'Diese Version wiederherstellen')}
                    </Button>
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}
