All files / src/components RestoreModal.tsx

0% Statements 0/284
0% Branches 0/1
0% Functions 0/1
0% Lines 0/284

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { useState, useRef, useEffect } from 'react';
import { Upload, X, AlertTriangle, CheckCircle, SkipForward, RefreshCw, Loader2, ChevronDown, ChevronUp } from 'lucide-react';
import { Card, CardContent } from './Card';
import { Button } from './Button';
import { Toggle } from './Toggle';
 
interface RestoreResult {
  success: boolean;
  message: string;
  restored?: Record<string, number>;
  skipped?: Record<string, number>;
  skipped_details?: Record<string, string[]>;
  files_restored?: number;
  total_skipped?: number;
}
 
interface RestoreModalProps {
  onClose: () => void;
  onRestore: (file: File, overwrite: boolean) => Promise<RestoreResult>;
  onSuccess: () => void;
}
 
type ModalState = 'options' | 'restoring' | 'result';
 
const CATEGORY_LABELS: Record<string, string> = {
  settings: 'Settings',
  notification_providers: 'Notification Providers',
  notification_templates: 'Notification Templates',
  smart_plugs: 'Smart Plugs',
  printers: 'Printers',
  filaments: 'Filaments',
  maintenance_types: 'Maintenance Types',
  archives: 'Archives',
};
 
export function RestoreModal({ onClose, onRestore, onSuccess }: RestoreModalProps) {
  const [state, setState] = useState<ModalState>('options');
  const [overwrite, setOverwrite] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [result, setResult] = useState<RestoreResult | null>(null);
  const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set());
  const fileInputRef = useRef<HTMLInputElement>(null);
 
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && state !== 'restoring') onClose();
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [onClose, state]);
 
  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setSelectedFile(file);
    }
  };
 
  const handleRestore = async () => {
    if (!selectedFile) return;
 
    setState('restoring');
    try {
      const restoreResult = await onRestore(selectedFile, overwrite);
      setResult(restoreResult);
      setState('result');
      if (restoreResult.success) {
        onSuccess();
      }
    } catch {
      setResult({
        success: false,
        message: 'Failed to restore backup. Please check the file format.',
      });
      setState('result');
    }
  };
 
  const toggleCategory = (category: string) => {
    setExpandedCategories(prev => {
      const next = new Set(prev);
      if (next.has(category)) {
        next.delete(category);
      } else {
        next.add(category);
      }
      return next;
    });
  };
 
  const totalRestored = result?.restored
    ? Object.values(result.restored).reduce((a, b) => a + b, 0) + (result.files_restored || 0)
    : 0;
  const totalSkipped = result?.total_skipped || 0;
 
  return (
    <div
      className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
      onMouseDown={(e) => {
        // Only close if clicking directly on the backdrop, not on children
        if (e.target === e.currentTarget && state !== 'restoring') {
          onClose();
        }
      }}
    >
      <Card className="w-full max-w-lg">
        <CardContent className="p-0">
          {/* Header */}
          <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
            <div className="flex items-center gap-3">
              <div className={`p-2 rounded-full ${
                state === 'result' && result?.success
                  ? 'bg-bambu-green/20 text-bambu-green'
                  : state === 'result' && !result?.success
                  ? 'bg-red-500/20 text-red-500'
                  : 'bg-blue-500/20 text-blue-500'
              }`}>
                {state === 'result' && result?.success ? (
                  <CheckCircle className="w-5 h-5" />
                ) : state === 'result' && !result?.success ? (
                  <AlertTriangle className="w-5 h-5" />
                ) : (
                  <Upload className="w-5 h-5" />
                )}
              </div>
              <div>
                <h3 className="text-lg font-semibold text-white">
                  {state === 'options' && 'Restore Backup'}
                  {state === 'restoring' && 'Restoring...'}
                  {state === 'result' && (result?.success ? 'Restore Complete' : 'Restore Failed')}
                </h3>
                <p className="text-sm text-bambu-gray">
                  {state === 'options' && 'Import settings from a backup file'}
                  {state === 'restoring' && 'Please wait while your data is being restored'}
                  {state === 'result' && result?.message}
                </p>
              </div>
            </div>
            {state !== 'restoring' && (
              <button
                onClick={onClose}
                className="p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            )}
          </div>
 
          {/* Options State */}
          {state === 'options' && (
            <>
              <div className="p-4 space-y-4">
                {/* File Selection */}
                <div>
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept=".json,.zip"
                    className="hidden"
                    onChange={handleFileSelect}
                  />
                  <button
                    type="button"
                    onClick={() => fileInputRef.current?.click()}
                    className={`w-full p-4 border-2 border-dashed rounded-lg transition-colors ${
                      selectedFile
                        ? 'border-bambu-green bg-bambu-green/10'
                        : 'border-bambu-dark-tertiary hover:border-bambu-gray'
                    }`}
                  >
                    {selectedFile ? (
                      <div className="flex items-center justify-center gap-2 text-bambu-green">
                        <CheckCircle className="w-5 h-5" />
                        <span className="font-medium">{selectedFile.name}</span>
                      </div>
                    ) : (
                      <div className="flex flex-col items-center gap-2 text-bambu-gray">
                        <Upload className="w-8 h-8" />
                        <span>Click to select backup file (.json or .zip)</span>
                      </div>
                    )}
                  </button>
                </div>
 
                {/* Info Box */}
                <div className="p-3 rounded-lg bg-blue-500/10 border border-blue-500/30">
                  <div className="flex items-start gap-2 text-sm">
                    <AlertTriangle className="w-4 h-4 text-blue-500 dark:text-blue-400 mt-0.5 flex-shrink-0" />
                    <div className="text-blue-700 dark:text-blue-200">
                      <p className="font-medium mb-1">How duplicate handling works:</p>
                      <ul className="text-blue-600 dark:text-blue-200/80 space-y-1 text-xs">
                        <li><strong>Printers</strong> - matched by serial number</li>
                        <li><strong>Smart Plugs</strong> - matched by IP address</li>
                        <li><strong>Notification Providers</strong> - matched by name</li>
                        <li><strong>Filaments</strong> - matched by name + type + brand</li>
                        <li><strong>Archives</strong> - matched by content hash (always skipped)</li>
                        <li><strong>Settings & Templates</strong> - always overwritten</li>
                      </ul>
                    </div>
                  </div>
                </div>
 
                {/* Overwrite Toggle */}
                <div className="p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-white font-medium flex items-center gap-2">
                        {overwrite ? (
                          <RefreshCw className="w-4 h-4 text-orange-400" />
                        ) : (
                          <SkipForward className="w-4 h-4 text-bambu-gray" />
                        )}
                        {overwrite ? 'Replace existing data' : 'Keep existing data'}
                      </p>
                      <p className="text-sm text-bambu-gray mt-1">
                        {overwrite
                          ? 'Overwrite items that already exist with backup data'
                          : 'Only restore items that don\'t already exist'}
                      </p>
                    </div>
                    <Toggle checked={overwrite} onChange={setOverwrite} />
                  </div>
                </div>
 
                {overwrite && (
                  <div className="p-3 rounded-lg bg-orange-500/10 border border-orange-500/30">
                    <div className="flex items-start gap-2 text-sm">
                      <AlertTriangle className="w-4 h-4 text-orange-500 dark:text-orange-400 mt-0.5 flex-shrink-0" />
                      <div className="text-orange-700 dark:text-orange-200">
                        <span className="font-medium">Caution:</span> Overwriting will replace your current configurations with data from the backup. Printer access codes are never overwritten for security.
                      </div>
                    </div>
                  </div>
                )}
              </div>
 
              {/* Footer */}
              <div className="flex items-center justify-end gap-3 p-4 border-t border-bambu-dark-tertiary">
                <Button type="button" variant="secondary" onClick={onClose}>
                  Cancel
                </Button>
                <Button
                  type="button"
                  onClick={handleRestore}
                  disabled={!selectedFile}
                  className="bg-bambu-green hover:bg-bambu-green-dark disabled:opacity-50"
                >
                  <Upload className="w-4 h-4 mr-2" />
                  Restore
                </Button>
              </div>
            </>
          )}
 
          {/* Restoring State */}
          {state === 'restoring' && (
            <div className="p-8 flex flex-col items-center gap-4">
              <Loader2 className="w-12 h-12 text-bambu-green animate-spin" />
              <p className="text-bambu-gray">Processing backup file...</p>
            </div>
          )}
 
          {/* Result State */}
          {state === 'result' && result && (
            <>
              <div className="p-4 space-y-4 max-h-[400px] overflow-y-auto">
                {/* Summary */}
                <div className="grid grid-cols-2 gap-3">
                  <div className="p-3 rounded-lg bg-bambu-green/10 border border-bambu-green/30">
                    <div className="text-2xl font-bold text-bambu-green">{totalRestored}</div>
                    <div className="text-sm text-bambu-gray">Items Restored</div>
                  </div>
                  <div className="p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30">
                    <div className="text-2xl font-bold text-yellow-500">{totalSkipped}</div>
                    <div className="text-sm text-bambu-gray">Items Skipped</div>
                  </div>
                </div>
 
                {/* Restored Details */}
                {result.restored && Object.entries(result.restored).some(([, count]) => count > 0) && (
                  <div className="space-y-2">
                    <h4 className="text-sm font-medium text-bambu-gray flex items-center gap-2">
                      <CheckCircle className="w-4 h-4 text-bambu-green" />
                      Restored
                    </h4>
                    <div className="space-y-1">
                      {Object.entries(result.restored)
                        .filter(([, count]) => count > 0)
                        .map(([key, count]) => (
                          <div key={key} className="flex items-center justify-between text-sm p-2 rounded bg-bambu-dark">
                            <span className="text-white">{CATEGORY_LABELS[key] || key}</span>
                            <span className="text-bambu-green font-medium">{count}</span>
                          </div>
                        ))}
                      {(result.files_restored || 0) > 0 && (
                        <div className="flex items-center justify-between text-sm p-2 rounded bg-bambu-dark">
                          <span className="text-white">Files (3MF, thumbnails, etc.)</span>
                          <span className="text-bambu-green font-medium">{result.files_restored}</span>
                        </div>
                      )}
                    </div>
                  </div>
                )}
 
                {/* Skipped Details */}
                {result.skipped && Object.entries(result.skipped).some(([, count]) => count > 0) && (
                  <div className="space-y-2">
                    <h4 className="text-sm font-medium text-bambu-gray flex items-center gap-2">
                      <SkipForward className="w-4 h-4 text-yellow-500" />
                      Skipped (already exist)
                    </h4>
                    <div className="space-y-1">
                      {Object.entries(result.skipped)
                        .filter(([, count]) => count > 0)
                        .map(([key, count]) => {
                          const details = result.skipped_details?.[key] || [];
                          const isExpanded = expandedCategories.has(key);
                          return (
                            <div key={key}>
                              <button
                                onClick={() => details.length > 0 && toggleCategory(key)}
                                className={`w-full flex items-center justify-between text-sm p-2 rounded bg-bambu-dark ${
                                  details.length > 0 ? 'hover:bg-bambu-dark-tertiary cursor-pointer' : ''
                                }`}
                              >
                                <span className="text-white flex items-center gap-2">
                                  {CATEGORY_LABELS[key] || key}
                                  {details.length > 0 && (
                                    isExpanded ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />
                                  )}
                                </span>
                                <span className="text-yellow-500 font-medium">{count}</span>
                              </button>
                              {isExpanded && details.length > 0 && (
                                <div className="mt-1 ml-4 p-2 rounded bg-bambu-dark-tertiary text-xs text-bambu-gray space-y-1">
                                  {details.slice(0, 10).map((item, i) => (
                                    <div key={i}>{item}</div>
                                  ))}
                                  {details.length > 10 && (
                                    <div className="text-bambu-gray/60">...and {details.length - 10} more</div>
                                  )}
                                </div>
                              )}
                            </div>
                          );
                        })}
                    </div>
                  </div>
                )}
 
                {totalRestored === 0 && totalSkipped === 0 && (
                  <div className="p-4 text-center text-bambu-gray">
                    No data was found to restore in the backup file.
                  </div>
                )}
              </div>
 
              {/* Footer */}
              <div className="flex items-center justify-end gap-3 p-4 border-t border-bambu-dark-tertiary">
                <Button onClick={onClose}>
                  Close
                </Button>
              </div>
            </>
          )}
        </CardContent>
      </Card>
    </div>
  );
}