'use client';

import { useEffect, useState } from 'react';
import { History, RotateCcw, Save, Sparkles, Send, Wand2, X } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { VersionSummary, VersionMilestone } from '@/lib/db/version-repo';

/**
 * Slide-In-Panel rechts neben der Sidebar mit der Versions-Historie eines Drafts.
 *
 *  - Liste der Versionen, neueste oben.
 *  - Pro Version: Source-Badge (manual/milestone/auto), Label, Zeitstempel, Restore-Button.
 *  - Footer: Input für manuellen Snapshot mit Label.
 *
 * Animation: translate-x-Slide + Backdrop-Fade.
 */
export function VersionHistoryPanel({
  open,
  draftId,
  draftName,
  onClose,
  onAfterRestore,
}: {
  open: boolean;
  draftId: string | null;
  draftName: string;
  onClose: () => void;
  onAfterRestore: () => void;
}) {
  const [versions, setVersions] = useState<VersionSummary[]>([]);
  const [loading, setLoading] = useState(false);
  const [restoring, setRestoring] = useState<string | null>(null);
  const [snapshotLabel, setSnapshotLabel] = useState('');
  const [creating, setCreating] = useState(false);

  // Lade Versionen wenn Panel geöffnet wird oder draftId wechselt
  useEffect(() => {
    if (!open || !draftId) return;
    setLoading(true);
    fetch(`/api/drafts/${draftId}/versions`)
      .then((r) => r.json())
      .then((d) => setVersions(d.versions ?? []))
      .catch(() => setVersions([]))
      .finally(() => setLoading(false));
  }, [open, draftId]);

  // ESC schließt
  useEffect(() => {
    if (!open) return;
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [open, onClose]);

  const handleRestore = async (versionId: string, version: VersionSummary) => {
    if (!draftId) return;
    const label = formatVersionTitle(version);
    if (!confirm(`Diese Version wiederherstellen?\n\n${label}\n\nDer aktuelle Stand wird automatisch als "Vor Restore" gesichert.`)) return;
    setRestoring(versionId);
    try {
      const res = await fetch(`/api/drafts/${draftId}/versions/${versionId}/restore`, { method: 'POST' });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        alert(`Restore fehlgeschlagen: ${data.error ?? res.status}`);
        return;
      }
      onAfterRestore();
      // Liste neu holen — Pre-Restore-Snapshot ist jetzt drin
      const fresh = await fetch(`/api/drafts/${draftId}/versions`).then((r) => r.json());
      setVersions(fresh.versions ?? []);
    } finally {
      setRestoring(null);
    }
  };

  const handleCreateSnapshot = async () => {
    if (!draftId) return;
    setCreating(true);
    try {
      const res = await fetch(`/api/drafts/${draftId}/versions`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          source: 'manual',
          label: snapshotLabel.trim() || `Snapshot ${new Date().toLocaleString('de-DE')}`,
        }),
      });
      if (res.ok) {
        setSnapshotLabel('');
        const fresh = await fetch(`/api/drafts/${draftId}/versions`).then((r) => r.json());
        setVersions(fresh.versions ?? []);
      }
    } finally {
      setCreating(false);
    }
  };

  return (
    <>
      {/* Backdrop */}
      <div
        onClick={onClose}
        className={cn(
          'fixed inset-0 z-30 bg-black/20 backdrop-blur-[1px] transition-opacity duration-200',
          open ? 'opacity-100' : 'pointer-events-none opacity-0',
        )}
      />
      {/* Panel — sitzt rechts neben der Sidebar. Liest die effektive Sidebar-Width
          aus der CSS-Variable `--mf-sidebar-x` (gesetzt von Sidebar.tsx), damit es
          sich pinned-open vs. pinned-collapsed automatisch anpasst. */}
      <aside
        aria-hidden={!open}
        style={{
          transform: open ? 'translateX(var(--mf-sidebar-x, 280px))' : 'translateX(-100%)',
          transition: 'transform 240ms cubic-bezier(0.32, 0.72, 0, 1)',
        }}
        className="fixed left-0 top-0 z-40 flex h-full w-[340px] flex-col border-r border-zinc-200 bg-white shadow-2xl dark:border-zinc-800 dark:bg-zinc-950"
      >
        <div className="flex items-center gap-2 border-b border-zinc-200 px-4 py-3 dark:border-zinc-800">
          <History className="h-4 w-4 text-zinc-500" />
          <div className="min-w-0 flex-1">
            <div className="text-sm font-semibold leading-tight">Versions-Historie</div>
            <div className="truncate text-[11px] text-zinc-500">{draftName}</div>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="flex h-7 w-7 items-center justify-center rounded text-zinc-500 transition-colors hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-zinc-800 dark:hover:text-zinc-100"
            title="Schließen (Esc)"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        <div className="flex-1 overflow-y-auto">
          {loading ? (
            <div className="px-4 py-6 text-center text-sm text-zinc-500">Lade Versionen…</div>
          ) : versions.length === 0 ? (
            <div className="px-4 py-6 text-center text-sm text-zinc-500">
              Noch keine Versionen.<br />
              Auto-Snapshots entstehen bei Generate, Render und Send — manuelle Snapshots kannst du unten erstellen.
            </div>
          ) : (
            <ol className="relative">
              {versions.map((v) => (
                <li key={v.id} className="border-b border-zinc-100 px-4 py-3 transition-colors hover:bg-zinc-50 dark:border-zinc-900 dark:hover:bg-zinc-900/50">
                  <div className="flex items-start gap-2">
                    <SourceBadge source={v.source} milestone={v.milestone} />
                    <div className="min-w-0 flex-1">
                      <div className="text-xs font-medium text-zinc-800 dark:text-zinc-200">
                        {formatVersionTitle(v)}
                      </div>
                      <div className="text-[10px] text-zinc-500">
                        {new Date(v.createdAt).toLocaleString('de-DE')}
                      </div>
                    </div>
                    <button
                      type="button"
                      disabled={restoring === v.id}
                      onClick={() => handleRestore(v.id, v)}
                      className="inline-flex shrink-0 items-center gap-1 rounded-md border border-zinc-200 px-2 py-1 text-[11px] font-medium text-zinc-700 transition hover:bg-zinc-100 hover:text-zinc-900 disabled:opacity-50 dark:border-zinc-700 dark:text-zinc-300 dark:hover:bg-zinc-800 dark:hover:text-zinc-100"
                      title="Diese Version wiederherstellen"
                    >
                      <RotateCcw className={cn('h-3 w-3', restoring === v.id && 'animate-spin')} />
                      {restoring === v.id ? 'Lade…' : 'Restore'}
                    </button>
                  </div>
                </li>
              ))}
            </ol>
          )}
        </div>

        {/* Manueller Snapshot */}
        <div className="border-t border-zinc-200 px-4 py-3 dark:border-zinc-800">
          <div className="mb-1.5 text-[10px] font-semibold uppercase tracking-wider text-zinc-500">
            Manueller Snapshot
          </div>
          <div className="flex gap-2">
            <input
              type="text"
              value={snapshotLabel}
              onChange={(e) => setSnapshotLabel(e.target.value)}
              placeholder="Label (optional)"
              onKeyDown={(e) => { if (e.key === 'Enter') void handleCreateSnapshot(); }}
              className="flex-1 rounded-md border border-zinc-200 bg-white px-2 py-1.5 text-xs transition focus:border-zinc-900 focus:outline-none dark:border-zinc-700 dark:bg-zinc-900"
            />
            <button
              type="button"
              onClick={handleCreateSnapshot}
              disabled={creating || !draftId}
              className="inline-flex items-center gap-1 rounded-md bg-zinc-900 px-3 py-1.5 text-xs font-medium text-white transition hover:bg-zinc-800 disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-zinc-200"
            >
              <Save className="h-3 w-3" />
              {creating ? '…' : 'Speichern'}
            </button>
          </div>
        </div>
      </aside>
    </>
  );
}

function SourceBadge({ source, milestone }: { source: VersionSummary['source']; milestone: VersionMilestone | null }) {
  if (source === 'milestone' && milestone === 'generate') {
    return <span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded bg-violet-100 text-violet-700 dark:bg-violet-900/40 dark:text-violet-300" title="Generate"><Sparkles className="h-3 w-3" /></span>;
  }
  if (source === 'milestone' && milestone === 'render') {
    return <span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300" title="Re-Render"><Wand2 className="h-3 w-3" /></span>;
  }
  if (source === 'milestone' && milestone === 'send') {
    return <span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300" title="Versand"><Send className="h-3 w-3" /></span>;
  }
  if (source === 'manual') {
    return <span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300" title="Manuell"><Save className="h-3 w-3" /></span>;
  }
  // auto / pre_restore / fallback
  return <span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded bg-zinc-100 text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400" title="Auto"><History className="h-3 w-3" /></span>;
}

function formatVersionTitle(v: VersionSummary): string {
  if (v.label) return v.label;
  if (v.milestone === 'generate') return 'Generate-Run';
  if (v.milestone === 'render') return 'Re-Render';
  if (v.milestone === 'send') return 'Vor Versand';
  if (v.milestone === 'pre_restore') return 'Vor Restore';
  if (v.source === 'auto') return 'Auto-Snapshot';
  return v.name || 'Unbenannte Version';
}
