'use client';

import { Check, CloudOff, Loader2, Cloud } from 'lucide-react';
import { useEffect, useState } from 'react';
import { cn } from '@/lib/utils';
import type { AutoSaveStatus } from '@/hooks/useAutoSave';

/**
 * Status-Badge für den Auto-Save. Drei Varianten:
 *  - default:  Icon + "Gespeichert vor 3s"-Text
 *  - collapsed: Icon + Text der per max-width:0 ausgeblendet ist (gleiche DOM-Struktur,
 *    kann animiert öffnen/schließen)
 *  - iconOnly:  Nur das Icon, mit data-tooltip für den vollen Status. Pro-Form für den
 *    Rail — kein eigenes Layout-Padding.
 *
 * Tickt 1×/Sekunde damit das relative Zeit-Format ("vor 3s") aktuell bleibt.
 */
export function AutoSaveIndicator({
  status,
  lastSavedAt,
  error,
  collapsed = false,
  iconOnly = false,
}: {
  status: AutoSaveStatus;
  lastSavedAt: Date | null;
  error?: string | null;
  collapsed?: boolean;
  iconOnly?: boolean;
}) {
  const [, setTick] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setTick((n) => n + 1), 1000);
    return () => clearInterval(t);
  }, []);

  const { Icon, text, tone } = render(status, lastSavedAt, error);

  if (iconOnly) {
    return (
      <div
        title={text}
        aria-label={text}
        className={cn('flex h-7 w-7 items-center justify-center rounded-md', tone)}
      >
        <Icon className={cn('h-4 w-4', status === 'saving' && 'animate-spin')} />
      </div>
    );
  }

  return (
    <div
      title={error ?? text}
      className={cn(
        'flex items-center gap-1.5 rounded-md px-2 py-1 text-[11px] font-medium transition-colors',
        tone,
      )}
    >
      <Icon className={cn('h-3.5 w-3.5 shrink-0', status === 'saving' && 'animate-spin')} />
      <span
        className={cn(
          'whitespace-nowrap transition-[max-width,opacity] duration-200 overflow-hidden',
          collapsed ? 'max-w-0 opacity-0' : 'max-w-[180px] opacity-100',
        )}
      >
        {text}
      </span>
    </div>
  );
}

function render(status: AutoSaveStatus, lastSavedAt: Date | null, error?: string | null) {
  if (status === 'saving') {
    return { Icon: Loader2, text: 'Speichere…', tone: 'text-zinc-500 dark:text-zinc-400' };
  }
  if (status === 'error') {
    return { Icon: CloudOff, text: error ? `Fehler: ${error}` : 'Speicher-Fehler', tone: 'text-red-600 dark:text-red-400' };
  }
  if (status === 'saved' && lastSavedAt) {
    return { Icon: Check, text: `Gespeichert ${formatRelative(lastSavedAt)}`, tone: 'text-emerald-600 dark:text-emerald-400' };
  }
  return { Icon: Cloud, text: 'Auto-Save bereit', tone: 'text-zinc-400 dark:text-zinc-500' };
}

function formatRelative(d: Date): string {
  const ms = Date.now() - d.getTime();
  const s = Math.floor(ms / 1000);
  if (s < 5) return 'gerade eben';
  if (s < 60) return `vor ${s}s`;
  const m = Math.floor(s / 60);
  if (m < 60) return `vor ${m}min`;
  const h = Math.floor(m / 60);
  return `vor ${h}h`;
}
