'use client';
import { useEffect, useState, useCallback } from 'react';
import { backupService } from '@/services/backup.service';
import type { BackupHistoryItem, RestoreResult } from '@/types/backup.types';

function formatBytes(bytesStr?: string): string {
  if (!bytesStr) return '0 B';
  const bytes = Number(bytesStr);
  if (bytes === 0) return '0 B';
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${units[i]}`;
}

export default function BackupRestorePage() {
  const [backups, setBackups] = useState<BackupHistoryItem[]>([]);
  const [selectedId, setSelectedId] = useState('');
  const [restoreDatabase, setRestoreDatabase] = useState(true);
  const [restoreFiles, setRestoreFiles] = useState(true);
  const [targetDatabase, setTargetDatabase] = useState('');
  const [restoring, setRestoring] = useState(false);
  const [result, setResult] = useState<RestoreResult | null>(null);
  const [error, setError] = useState<string | null>(null);

  const fetchBackups = useCallback(async () => {
    try {
      const res = await backupService.getHistory({ limit: 50 });
      // Only completed backups can be restored
      setBackups(res.items.filter((b) => b.status === 'COMPLETED'));
    } catch (e: any) {
      setError(e?.message ?? 'Failed to load backups');
    }
  }, []);

  useEffect(() => {
    fetchBackups();
  }, [fetchBackups]);

  const handleRestore = async () => {
    if (!selectedId) {
      setError('Please select a backup to restore');
      return;
    }
    if (!window.confirm('WARNING: Restoring will overwrite current data. Continue?')) return;

    setRestoring(true);
    setError(null);
    setResult(null);
    try {
const res = await backupService.restoreBackup({
        backupId: selectedId,
        restoreDatabase,
        restoreFiles,
        targetDatabase: targetDatabase || undefined,
      });
      setResult(res);
    } catch (e: any) {
      setError(e?.message ?? 'Restore failed');
    } finally {
      setRestoring(false);
    }
  };

  return (
    <div className="max-w-3xl space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-white">Restore Backup</h1>
        <p className="mt-1 text-sm text-white/50">
          Verify checksum is performed automatically before restore. Database is restored first, then files.
        </p>
      </div>

      {error && (
        <div className="rounded-xl border border-red-500/20 bg-red-500/10 p-4 text-sm text-red-300">{error}</div>
      )}
      {result && (
        <div className="rounded-xl border border-emerald-500/20 bg-emerald-500/10 p-4 text-sm text-emerald-300">
          <p className="font-medium">Restore completed</p>
          <p>Status: {result.restoreStatus}</p>
          <p>Database: {result.restoredDatabase ? 'Yes' : 'No'} · Files: {result.restoredFiles ? 'Yes' : 'No'}</p>
          <p className="font-mono text-[10px]">{result.completedAt}</p>
        </div>
      )}

      <div className="rounded-xl border border-white/5 bg-white/[0.02] p-5 space-y-4">
        <div>
          <label className="mb-1 block text-xs font-medium text-white/70">Select Backup</label>
          <select
            value={selectedId}
            onChange={(e) => setSelectedId(e.target.value)}
            className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-white/80"
          >
            <option value="">Select a completed backup…</option>
            {backups.map((b) => (
              <option key={b.id} value={b.id}>
                {b.type} · {b.scope} · {formatBytes(b.fileSizeBytes)} · {new Date(b.createdAt).toLocaleString()}
              </option>
            ))}
          </select>
        </div>

        <div className="flex items-center gap-2">
          <input
            type="checkbox"
            checked={restoreDatabase}
            onChange={(e) => setRestoreDatabase(e.target.checked)}
            className="h-4 w-4"
          />
          <label className="text-sm text-white/70">Restore database</label>
        </div>

        <div className="flex items-center gap-2">
          <input
            type="checkbox"
            checked={restoreFiles}
            onChange={(e) => setRestoreFiles(e.target.checked)}
            className="h-4 w-4"
          />
          <label className="text-sm text-white/70">Restore uploaded files</label>
        </div>

        <div>
          <label className="mb-1 block text-xs font-medium text-white/70">Target Database (optional)</label>
          <input
            type="text"
            value={targetDatabase}
            onChange={(e) => setTargetDatabase(e.target.value)}
            placeholder="Leave blank to restore to original database"
            className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-white/80 placeholder:text-white/30"
          />
        </div>

        <button
          onClick={handleRestore}
          disabled={restoring || !selectedId}
          className="w-full rounded-lg bg-red-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-red-500 disabled:opacity-50 transition-colors"
        >
          {restoring ? 'Restoring…' : 'Restore Backup'}
        </button>
      </div>

      <p className="text-[10px] text-slate-600">
        SECURITY: Restore is restricted to Super Admin only. Every restore operation is logged to the audit trail.
      </p>
    </div>
  );
}
