'use client';

import { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Shield, Download, Upload, Clock, AlertTriangle, CheckCircle,
  XCircle, RefreshCw, Trash2, ChevronDown, ChevronRight,
  Database, Archive, Settings, Play, Eye, RotateCcw,
  Calendar, HardDrive, FileText, AlertOctagon
} from 'lucide-react';

interface BackupRecord {
  id: string;
  name: string;
  type: string;
  status: string;
  trigger: string;
  entityTypes: string[];
  entityCounts: Record<string, number>;
  totalItems: number;
  sizeEstimateKb: number;
  errorMessage?: string;
  createdById?: string;
  createdByAgent?: string;
  notes?: string;
  createdAt: string;
  expiresAt?: string;
}

interface BackupScheduleConfig {
  id: string;
  name: string;
  frequency: string;
  retentionDays: number;
  entityTypes: string[];
  enabled: boolean;
  lastRunAt?: string;
  nextRunAt?: string;
}

interface BackupStats {
  total: number;
  completed: number;
  failed: number;
  latestBackup: BackupRecord | null;
  totalItems: number;
  schedules: BackupScheduleConfig[];
  entityGroups: Record<string, string[]>;
  allEntityTypes: string[];
}

interface ItemSummary {
  entityType: string;
  count: number;
}

type RestoreStep = 0 | 1 | 2 | 3; // 0 = not started, 1-3 = confirmation steps

export function BackupRestorePanel() {
  const [stats, setStats] = useState<BackupStats | null>(null);
  const [backups, setBackups] = useState<BackupRecord[]>([]);
  const [schedule, setSchedule] = useState<BackupScheduleConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [restoring, setRestoring] = useState(false);
  const [expandedBackup, setExpandedBackup] = useState<string | null>(null);
  const [backupDetail, setBackupDetail] = useState<{ backup: BackupRecord; itemSummary: ItemSummary[] } | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  // Restore verification state
  const [restoreTarget, setRestoreTarget] = useState<string | null>(null);
  const [restoreStep, setRestoreStep] = useState<RestoreStep>(0);
  const [confirmations, setConfirmations] = useState<{ confirmed: boolean; timestamp: string; reason: string }[]>([]);
  const [restoreReason, setRestoreReason] = useState('');

  // Create backup form
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [newBackupName, setNewBackupName] = useState('');
  const [newBackupNotes, setNewBackupNotes] = useState('');
  const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);

  // Schedule editing
  const [editingSchedule, setEditingSchedule] = useState(false);
  const [scheduleForm, setScheduleForm] = useState({
    frequency: 'DAILY',
    retentionDays: 30,
    enabled: false,
  });

  const fetchStats = useCallback(async () => {
    try {
      const res = await fetch('/api/backups?stats=true');
      if (res.ok) {
        const data = await res.json();
        setStats(data);
      }
    } catch (err) {
      console.error('Failed to fetch stats:', err);
    }
  }, []);

  const fetchBackups = useCallback(async () => {
    try {
      const res = await fetch('/api/backups?limit=50');
      if (res.ok) {
        const data = await res.json();
        setBackups(data.backups);
      }
    } catch (err) {
      console.error('Failed to fetch backups:', err);
    }
  }, []);

  const fetchSchedule = useCallback(async () => {
    try {
      const res = await fetch('/api/backups/schedule');
      if (res.ok) {
        const data = await res.json();
        setSchedule(data.schedule);
        setScheduleForm({
          frequency: data.schedule.frequency,
          retentionDays: data.schedule.retentionDays,
          enabled: data.schedule.enabled,
        });
      }
    } catch (err) {
      console.error('Failed to fetch schedule:', err);
    }
  }, []);

  useEffect(() => {
    Promise.all([fetchStats(), fetchBackups(), fetchSchedule()]).then(() => setLoading(false));
  }, [fetchStats, fetchBackups, fetchSchedule]);

  const handleCreateBackup = async () => {
    if (!newBackupName.trim()) {
      setError('Backup name is required');
      return;
    }
    setCreating(true);
    setError(null);
    setSuccess(null);
    try {
      const res = await fetch('/api/backups', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: newBackupName.trim(),
          type: selectedEntityTypes.length > 0 ? 'SELECTIVE' : 'SNAPSHOT',
          entityTypes: selectedEntityTypes.length > 0 ? selectedEntityTypes : undefined,
          notes: newBackupNotes.trim() || undefined,
        }),
      });
      const data = await res.json();
      if (data.success) {
        setSuccess(`Backup "${newBackupName}" created — ${data.backup.totalItems} items captured`);
        setNewBackupName('');
        setNewBackupNotes('');
        setSelectedEntityTypes([]);
        setShowCreateForm(false);
        await Promise.all([fetchStats(), fetchBackups()]);
      } else {
        setError(data.error || 'Backup creation failed');
      }
    } catch (err: any) {
      setError(err.message);
    } finally {
      setCreating(false);
    }
  };

  const handleExpandBackup = async (backupId: string) => {
    if (expandedBackup === backupId) {
      setExpandedBackup(null);
      setBackupDetail(null);
      return;
    }
    setExpandedBackup(backupId);
    try {
      const res = await fetch(`/api/backups/${backupId}`);
      if (res.ok) {
        setBackupDetail(await res.json());
      }
    } catch (err) {
      console.error('Failed to fetch backup detail:', err);
    }
  };

  const handleDeleteBackup = async (backupId: string) => {
    if (!confirm('Delete this backup? This cannot be undone.')) return;
    try {
      const res = await fetch(`/api/backups/${backupId}`, { method: 'DELETE' });
      if (res.ok) {
        setSuccess('Backup deleted');
        await Promise.all([fetchStats(), fetchBackups()]);
      }
    } catch (err: any) {
      setError(err.message);
    }
  };

  // 3x Verification Restore Flow
  const startRestore = (backupId: string) => {
    setRestoreTarget(backupId);
    setRestoreStep(1);
    setConfirmations([]);
    setRestoreReason('');
    setError(null);
    setSuccess(null);
  };

  const confirmStep = () => {
    const step = restoreStep as number;
    setConfirmations(prev => [
      ...prev,
      { confirmed: true, timestamp: new Date().toISOString(), reason: restoreReason || `Confirmation ${step}` },
    ]);
    setRestoreReason('');
    if (step < 3) {
      setRestoreStep((step + 1) as RestoreStep);
    }
  };

  const cancelRestore = () => {
    setRestoreTarget(null);
    setRestoreStep(0);
    setConfirmations([]);
    setRestoreReason('');
  };

  const executeRestore = async () => {
    if (!restoreTarget || confirmations.length !== 3) return;
    setRestoring(true);
    setError(null);
    try {
      const res = await fetch(`/api/backups/${restoreTarget}/restore`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ confirmations }),
      });
      const data = await res.json();
      if (res.ok) {
        setSuccess(`Restore complete: ${data.restored} entities restored, ${data.failed} failed`);
        cancelRestore();
      } else {
        setError(data.error || 'Restore failed');
      }
    } catch (err: any) {
      setError(err.message);
    } finally {
      setRestoring(false);
    }
  };

  const handleSaveSchedule = async () => {
    try {
      const res = await fetch('/api/backups/schedule', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(scheduleForm),
      });
      if (res.ok) {
        const data = await res.json();
        setSchedule(data.schedule);
        setEditingSchedule(false);
        setSuccess('Backup schedule updated');
      }
    } catch (err: any) {
      setError(err.message);
    }
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleString('en-US', {
      month: 'short', day: 'numeric', year: 'numeric',
      hour: '2-digit', minute: '2-digit',
    });
  };

  const formatSize = (kb: number) => {
    if (kb < 1024) return `${kb} KB`;
    return `${(kb / 1024).toFixed(1)} MB`;
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-48">
        <RefreshCw className="w-5 h-5 text-brand animate-spin" />
        <span className="ml-2 text-gray-400">Loading backup system...</span>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Status Messages */}
      <AnimatePresence>
        {error && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="flex items-center gap-2 p-3 rounded-lg bg-red-500/10 border border-red-500/30 text-red-300 text-sm"
          >
            <XCircle className="w-4 h-4 shrink-0" />
            <span>{error}</span>
            <button onClick={() => setError(null)} className="ml-auto text-red-400 hover:text-red-300">
              <XCircle className="w-3.5 h-3.5" />
            </button>
          </motion.div>
        )}
        {success && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="flex items-center gap-2 p-3 rounded-lg bg-emerald-500/10 border border-emerald-500/30 text-emerald-300 text-sm"
          >
            <CheckCircle className="w-4 h-4 shrink-0" />
            <span>{success}</span>
            <button onClick={() => setSuccess(null)} className="ml-auto text-emerald-400 hover:text-emerald-300">
              <XCircle className="w-3.5 h-3.5" />
            </button>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Stats Overview */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {[
          { label: 'Total Backups', value: stats?.completed ?? 0, icon: Archive, color: 'cyan' },
          { label: 'Total Items Stored', value: stats?.totalItems ?? 0, icon: Database, color: 'purple' },
          { label: 'Failed Backups', value: stats?.failed ?? 0, icon: AlertTriangle, color: stats?.failed ? 'red' : 'gray' },
          {
            label: 'Last Backup',
            value: stats?.latestBackup ? formatDate(stats.latestBackup.createdAt) : 'Never',
            icon: Clock,
            color: 'emerald',
            isText: true,
          },
        ].map((stat, i) => (
          <div key={i} className="rounded-xl border border-slate-700 bg-slate-900 p-4">
            <div className="flex items-center gap-2 mb-1">
              <stat.icon className={`w-4 h-4 text-${stat.color}-400`} />
              <span className="text-xs text-gray-400">{stat.label}</span>
            </div>
            <p className={`text-${stat.isText ? 'sm' : 'xl'} font-bold text-white`}>
              {typeof stat.value === 'number' ? stat.value.toLocaleString() : stat.value}
            </p>
          </div>
        ))}
      </div>

      {/* Actions Bar */}
      <div className="flex flex-wrap items-center gap-3">
        <button
          onClick={() => setShowCreateForm(!showCreateForm)}
          className="flex items-center gap-2 px-4 py-2 rounded-lg bg-brand-deep/20 text-brand-light border border-brand-deep/30 hover:bg-brand-deep/30 transition-colors text-sm font-medium"
        >
          <Download className="w-4 h-4" />
          Create Backup
        </button>
        <button
          onClick={() => { fetchStats(); fetchBackups(); }}
          className="flex items-center gap-2 px-4 py-2 rounded-lg bg-slate-800 text-gray-300 border border-slate-700 hover:bg-slate-700 transition-colors text-sm"
        >
          <RefreshCw className="w-4 h-4" />
          Refresh
        </button>
        <button
          onClick={() => setEditingSchedule(!editingSchedule)}
          className="flex items-center gap-2 px-4 py-2 rounded-lg bg-brand-secondary/20 text-brand-secondary-light border border-brand-secondary/30 hover:bg-brand-secondary/30 transition-colors text-sm"
        >
          <Calendar className="w-4 h-4" />
          Schedule Settings
        </button>
      </div>

      {/* Create Backup Form */}
      <AnimatePresence>
        {showCreateForm && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            className="rounded-xl border border-brand-deep/30 bg-slate-900/80 p-5 space-y-4"
          >
            <h4 className="text-sm font-semibold text-brand flex items-center gap-2">
              <Archive className="w-4 h-4" /> New Backup
            </h4>
            <div>
              <label className="block text-xs text-gray-400 mb-1">Backup Name *</label>
              <input
                type="text"
                value={newBackupName}
                onChange={e => setNewBackupName(e.target.value)}
                placeholder="e.g. Pre-deployment snapshot"
                className="w-full px-3 py-2 rounded-lg bg-slate-800 border border-slate-700 text-white text-sm focus:border-brand-deep focus:outline-none"
              />
            </div>
            <div>
              <label className="block text-xs text-gray-400 mb-1">Notes (optional)</label>
              <textarea
                value={newBackupNotes}
                onChange={e => setNewBackupNotes(e.target.value)}
                placeholder="Why are you creating this backup?"
                rows={2}
                className="w-full px-3 py-2 rounded-lg bg-slate-800 border border-slate-700 text-white text-sm focus:border-brand-deep focus:outline-none resize-none"
              />
            </div>
            <div>
              <label className="block text-xs text-gray-400 mb-2">Entity Types (leave empty for full snapshot)</label>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
                {stats?.entityGroups && Object.entries(stats.entityGroups).map(([group, types]) => (
                  <div key={group} className="space-y-1">
                    <p className="text-xs font-medium text-brand-secondary-light">{group}</p>
                    {types.map(type => (
                      <label key={type} className="flex items-center gap-1.5 text-xs text-gray-300 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={selectedEntityTypes.includes(type)}
                          onChange={e => {
                            setSelectedEntityTypes(prev =>
                              e.target.checked ? [...prev, type] : prev.filter(t => t !== type)
                            );
                          }}
                          className="rounded border-slate-600 bg-slate-800 text-brand-deep"
                        />
                        {type}
                      </label>
                    ))}
                  </div>
                ))}
              </div>
            </div>
            <div className="flex items-center gap-3">
              <button
                onClick={handleCreateBackup}
                disabled={creating}
                className="flex items-center gap-2 px-4 py-2 rounded-lg bg-brand-deep text-black font-medium text-sm hover:bg-brand transition-colors disabled:opacity-50"
              >
                {creating ? <RefreshCw className="w-4 h-4 animate-spin" /> : <Download className="w-4 h-4" />}
                {creating ? 'Creating...' : 'Create Backup'}
              </button>
              <button
                onClick={() => setShowCreateForm(false)}
                className="px-4 py-2 rounded-lg text-gray-400 hover:text-white text-sm transition-colors"
              >
                Cancel
              </button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Schedule Settings */}
      <AnimatePresence>
        {editingSchedule && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            className="rounded-xl border border-brand-secondary/30 bg-slate-900/80 p-5 space-y-4"
          >
            <h4 className="text-sm font-semibold text-brand-secondary-light flex items-center gap-2">
              <Calendar className="w-4 h-4" /> Automated Backup Schedule
            </h4>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <label className="block text-xs text-gray-400 mb-1">Frequency</label>
                <select
                  value={scheduleForm.frequency}
                  onChange={e => setScheduleForm(p => ({ ...p, frequency: e.target.value }))}
                  className="w-full px-3 py-2 rounded-lg bg-slate-800 border border-slate-700 text-white text-sm focus:border-brand-secondary focus:outline-none"
                >
                  <option value="HOURLY">Hourly</option>
                  <option value="DAILY">Daily</option>
                  <option value="WEEKLY">Weekly</option>
                </select>
              </div>
              <div>
                <label className="block text-xs text-gray-400 mb-1">Retention (days)</label>
                <input
                  type="number"
                  value={scheduleForm.retentionDays}
                  onChange={e => setScheduleForm(p => ({ ...p, retentionDays: parseInt(e.target.value) || 30 }))}
                  min={1}
                  max={365}
                  className="w-full px-3 py-2 rounded-lg bg-slate-800 border border-slate-700 text-white text-sm focus:border-brand-secondary focus:outline-none"
                />
              </div>
              <div>
                <label className="block text-xs text-gray-400 mb-1">Enabled</label>
                <button
                  onClick={() => setScheduleForm(p => ({ ...p, enabled: !p.enabled }))}
                  className={`w-full px-3 py-2 rounded-lg border text-sm font-medium transition-colors ${
                    scheduleForm.enabled
                      ? 'bg-emerald-500/20 border-emerald-500/30 text-emerald-300'
                      : 'bg-slate-800 border-slate-700 text-gray-400'
                  }`}
                >
                  {scheduleForm.enabled ? '✓ Enabled' : 'Disabled'}
                </button>
              </div>
            </div>
            {schedule && (
              <div className="text-xs text-gray-500 space-y-1">
                {schedule.lastRunAt && <p>Last run: {formatDate(schedule.lastRunAt)}</p>}
                {schedule.nextRunAt && schedule.enabled && <p>Next run: {formatDate(schedule.nextRunAt)}</p>}
              </div>
            )}
            <div className="flex items-center gap-3">
              <button
                onClick={handleSaveSchedule}
                className="flex items-center gap-2 px-4 py-2 rounded-lg bg-brand-secondary text-white font-medium text-sm hover:bg-brand-secondary-light transition-colors"
              >
                <Settings className="w-4 h-4" /> Save Schedule
              </button>
              <button
                onClick={() => setEditingSchedule(false)}
                className="px-4 py-2 rounded-lg text-gray-400 hover:text-white text-sm transition-colors"
              >
                Cancel
              </button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* 3x Verification Restore Modal */}
      <AnimatePresence>
        {restoreTarget && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4"
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              className="w-full max-w-lg rounded-2xl border border-red-500/40 bg-slate-900 p-6 space-y-5"
            >
              <div className="flex items-center gap-3">
                <div className="p-2 rounded-xl bg-red-500/20">
                  <AlertOctagon className="w-6 h-6 text-red-400" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-white">Restore Verification</h3>
                  <p className="text-xs text-red-300">This action will overwrite current data. 3 confirmations required.</p>
                </div>
              </div>

              {/* Progress indicator */}
              <div className="flex items-center gap-2">
                {[1, 2, 3].map(step => (
                  <div
                    key={step}
                    className={`flex-1 h-2 rounded-full transition-colors ${
                      confirmations.length >= step
                        ? 'bg-red-500'
                        : restoreStep === step
                        ? 'bg-red-500/40 animate-pulse'
                        : 'bg-slate-700'
                    }`}
                  />
                ))}
              </div>

              {/* Current step */}
              {restoreStep <= 3 && confirmations.length < 3 && (
                <div className="space-y-3">
                  <p className="text-sm text-gray-300">
                    {restoreStep === 1 && 'Step 1 of 3: Are you sure you want to restore this backup? This will overwrite existing data for all included entity types.'}
                    {restoreStep === 2 && 'Step 2 of 3: This is your second confirmation. Please provide a reason for this restore.'}
                    {restoreStep === 3 && 'Step 3 of 3: FINAL CONFIRMATION. This action will be executed immediately and logged. There is no undo.'}
                  </p>
                  {restoreStep >= 2 && (
                    <input
                      type="text"
                      value={restoreReason}
                      onChange={e => setRestoreReason(e.target.value)}
                      placeholder={restoreStep === 2 ? 'Reason for restore...' : 'Type RESTORE to confirm'}
                      className="w-full px-3 py-2 rounded-lg bg-slate-800 border border-red-500/30 text-white text-sm focus:border-red-500 focus:outline-none"
                    />
                  )}
                  <div className="flex items-center gap-3">
                    <button
                      onClick={confirmStep}
                      disabled={restoreStep === 3 && restoreReason.toUpperCase() !== 'RESTORE'}
                      className="flex items-center gap-2 px-4 py-2 rounded-lg bg-red-500/20 text-red-300 border border-red-500/30 hover:bg-red-500/30 transition-colors text-sm font-medium disabled:opacity-30 disabled:cursor-not-allowed"
                    >
                      <AlertTriangle className="w-4 h-4" />
                      {restoreStep === 3 ? 'Final Confirm' : `Confirm Step ${restoreStep}`}
                    </button>
                    <button
                      onClick={cancelRestore}
                      className="px-4 py-2 rounded-lg text-gray-400 hover:text-white text-sm transition-colors"
                    >
                      Cancel
                    </button>
                  </div>
                </div>
              )}

              {/* Execute */}
              {confirmations.length === 3 && (
                <div className="space-y-3">
                  <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/20">
                    <p className="text-sm text-red-300 font-medium">All 3 confirmations received. Ready to execute restore.</p>
                    <ul className="mt-2 space-y-1">
                      {confirmations.map((c, i) => (
                        <li key={i} className="text-xs text-gray-400 flex items-center gap-1.5">
                          <CheckCircle className="w-3 h-3 text-red-400" />
                          Step {i + 1}: {c.reason} — {new Date(c.timestamp).toLocaleTimeString()}
                        </li>
                      ))}
                    </ul>
                  </div>
                  <div className="flex items-center gap-3">
                    <button
                      onClick={executeRestore}
                      disabled={restoring}
                      className="flex items-center gap-2 px-5 py-2.5 rounded-lg bg-red-600 text-white font-bold text-sm hover:bg-red-500 transition-colors disabled:opacity-50"
                    >
                      {restoring ? <RefreshCw className="w-4 h-4 animate-spin" /> : <RotateCcw className="w-4 h-4" />}
                      {restoring ? 'Restoring...' : 'Execute Restore'}
                    </button>
                    <button
                      onClick={cancelRestore}
                      className="px-4 py-2 rounded-lg text-gray-400 hover:text-white text-sm transition-colors"
                    >
                      Cancel
                    </button>
                  </div>
                </div>
              )}
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Backup List */}
      <div className="space-y-3">
        <h4 className="text-sm font-semibold text-gray-300 flex items-center gap-2">
          <HardDrive className="w-4 h-4 text-brand" />
          Backup History
        </h4>
        {backups.length === 0 ? (
          <div className="text-center py-12 rounded-xl border border-slate-700 bg-slate-900/50">
            <Archive className="w-8 h-8 mx-auto mb-2 text-gray-600" />
            <p className="text-gray-500 text-sm">No backups yet. Create your first snapshot above.</p>
          </div>
        ) : (
          <div className="space-y-2">
            {backups.map(backup => (
              <div key={backup.id} className="rounded-xl border border-slate-700 bg-slate-900 overflow-hidden">
                {/* Header Row */}
                <div
                  className="flex items-center gap-3 p-4 cursor-pointer hover:bg-slate-800/50 transition-colors"
                  onClick={() => handleExpandBackup(backup.id)}
                >
                  <div className="shrink-0">
                    {backup.status === 'COMPLETED' ? (
                      <CheckCircle className="w-5 h-5 text-emerald-400" />
                    ) : backup.status === 'FAILED' ? (
                      <XCircle className="w-5 h-5 text-red-400" />
                    ) : (
                      <RefreshCw className="w-5 h-5 text-yellow-400 animate-spin" />
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-white truncate">{backup.name}</p>
                    <p className="text-xs text-gray-400">
                      {formatDate(backup.createdAt)} · {backup.totalItems} items · {formatSize(backup.sizeEstimateKb)} · {backup.type} · {backup.trigger}
                    </p>
                  </div>
                  <div className="flex items-center gap-2">
                    {backup.status === 'COMPLETED' && (
                      <button
                        onClick={e => { e.stopPropagation(); startRestore(backup.id); }}
                        className="flex items-center gap-1 px-2.5 py-1 rounded-lg bg-amber-500/10 text-amber-300 border border-amber-500/20 hover:bg-amber-500/20 transition-colors text-xs"
                      >
                        <RotateCcw className="w-3 h-3" /> Restore
                      </button>
                    )}
                    <button
                      onClick={e => { e.stopPropagation(); handleDeleteBackup(backup.id); }}
                      className="p-1.5 rounded-lg text-gray-500 hover:text-red-400 hover:bg-red-500/10 transition-colors"
                    >
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                    {expandedBackup === backup.id ? (
                      <ChevronDown className="w-4 h-4 text-gray-500" />
                    ) : (
                      <ChevronRight className="w-4 h-4 text-gray-500" />
                    )}
                  </div>
                </div>

                {/* Expanded Detail */}
                <AnimatePresence>
                  {expandedBackup === backup.id && backupDetail && (
                    <motion.div
                      initial={{ opacity: 0, height: 0 }}
                      animate={{ opacity: 1, height: 'auto' }}
                      exit={{ opacity: 0, height: 0 }}
                      className="border-t border-slate-700 bg-slate-900/50 p-4"
                    >
                      {backup.notes && (
                        <p className="text-xs text-gray-400 mb-3 italic">"{backup.notes}"</p>
                      )}
                      {backup.errorMessage && (
                        <p className="text-xs text-red-400 mb-3">Error: {backup.errorMessage}</p>
                      )}
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
                        {backupDetail.itemSummary.map(item => (
                          <div key={item.entityType} className="flex items-center gap-2 px-3 py-2 rounded-lg bg-slate-800 border border-slate-700">
                            <FileText className="w-3 h-3 text-brand-secondary-light shrink-0" />
                            <div className="min-w-0">
                              <p className="text-xs text-white truncate">{item.entityType}</p>
                              <p className="text-xs text-gray-500">{item.count} records</p>
                            </div>
                          </div>
                        ))}
                      </div>
                      {backup.expiresAt && (
                        <p className="text-xs text-gray-500 mt-3">Expires: {formatDate(backup.expiresAt)}</p>
                      )}
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
