// ABOUTME: Backup management screen for exporting and importing health data
// ABOUTME: Provides complete backup functionality with file management, progress tracking, and error handling
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';
import '../services/export_service.dart';
import '../services/import_service.dart';
import '../services/database_service.dart';
import '../models/weight_entry.dart';
import '../models/blood_pressure_entry.dart';
import '../models/mood_entry.dart';
import '../models/mood_type.dart';
import '../models/backup/export_options.dart';
import '../models/backup/backup_metadata.dart';
import '../models/backup/import_result.dart';
import '../widgets/backup/export_dialog.dart';
import '../widgets/backup/import_dialog.dart';
import '../widgets/backup/file_info_display.dart';
import '../widgets/backup/import_result_display.dart';
import '../utils/file_utils.dart';

class BackupScreen extends StatefulWidget {
  const BackupScreen({super.key});

  @override
  State<BackupScreen> createState() => _BackupScreenState();
}

class _BackupScreenState extends State<BackupScreen> {
  final ExportService _exportService = ExportService.instance;
  final ImportService _importService = ImportService.instance;
  final DatabaseService _databaseService = DatabaseService.instance;
  
  List<File> _localBackups = [];
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _loadLocalBackups();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Backup & Restore'),
        elevation: 0,
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Export section
                  _buildExportSection(context),
                  
                  const SizedBox(height: 32),
                  
                  // Import section
                  _buildImportSection(context),
                  
                  const SizedBox(height: 32),
                  
                  // Local backups section
                  _buildLocalBackupsSection(context),
                  
                  const SizedBox(height: 24),
                  
                  // Support Development Footer
                  _buildSupportFooter(context),
                ],
              ),
            ),
    );
  }

  Widget _buildExportSection(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  Icons.upload_file,
                  color: Theme.of(context).colorScheme.primary,
                ),
                const SizedBox(width: 8),
                Text(
                  'Export Data',
                  style: Theme.of(context).textTheme.titleMedium,
                ),
              ],
            ),
            const SizedBox(height: 12),
            const Text(
              'Create a backup of your health data to save locally or share with other devices.',
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: FilledButton.icon(
                    onPressed: _showExportDialog,
                    icon: const Icon(Icons.backup),
                    label: const Text('Create Backup'),
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: _exportToCsv,
                    icon: const Icon(Icons.table_chart),
                    label: const Text('Export CSV'),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildImportSection(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  Icons.file_download,
                  color: Theme.of(context).colorScheme.primary,
                ),
                const SizedBox(width: 8),
                Text(
                  'Import CSV Data',
                  style: Theme.of(context).textTheme.titleMedium,
                ),
              ],
            ),
            const SizedBox(height: 12),
            const Text(
              'Import health data from a CSV file exported from this app. To restore from a local backup, see Local Backups below.',
            ),
            const SizedBox(height: 16),
            SizedBox(
              width: double.infinity,
              child: FilledButton.icon(
                onPressed: _showCsvImportDialog,
                icon: const Icon(Icons.table_chart),
                label: const Text('Import CSV File'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLocalBackupsSection(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(
                          Icons.folder,
                          color: Theme.of(context).colorScheme.primary,
                        ),
                        const SizedBox(width: 8),
                        Text(
                          'Local Backups',
                          style: Theme.of(context).textTheme.titleMedium,
                        ),
                      ],
                    ),
                    const SizedBox(height: 4),
                    Text(
                      'Tap a backup for options',
                      style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        color: Colors.grey.shade600,
                      ),
                    ),
                  ],
                ),
                IconButton(
                  onPressed: _loadLocalBackups,
                  icon: const Icon(Icons.refresh),
                  tooltip: 'Refresh',
                ),
              ],
            ),
            const SizedBox(height: 12),
            
            if (_localBackups.isEmpty)
              const Padding(
                padding: EdgeInsets.symmetric(vertical: 24.0),
                child: Center(
                  child: Column(
                    children: [
                      Icon(Icons.folder_open, size: 48, color: Colors.grey),
                      SizedBox(height: 8),
                      Text('No local backups found'),
                      Text(
                        'Create a backup to get started',
                        style: TextStyle(color: Colors.grey),
                      ),
                    ],
                  ),
                ),
              )
            else
              Column(
                children: _localBackups.map((file) => 
                  FutureBuilder<BackupMetadata?>(
                    future: _loadBackupMetadata(file),
                    builder: (context, snapshot) {
                      return CompactFileInfo(
                        file: file,
                        metadata: snapshot.data,
                        onTap: () => _showFileDetails(file, snapshot.data),
                      );
                    },
                  ),
                ).toList(),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildSupportFooter(BuildContext context) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 16.0),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.coffee,
              color: Colors.brown,
              size: 16,
            ),
            const SizedBox(width: 8),
            Text(
              'Enjoying the app?',
              style: Theme.of(context).textTheme.bodySmall?.copyWith(
                color: Theme.of(context).colorScheme.onSurfaceVariant,
              ),
            ),
            const SizedBox(width: 8),
            GestureDetector(
              onTap: _launchDonationUrl,
              child: Text(
                'Support development',
                style: Theme.of(context).textTheme.bodySmall?.copyWith(
                  color: Theme.of(context).colorScheme.primary,
                  decoration: TextDecoration.underline,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _launchDonationUrl() async {
    final Uri donationUri = Uri.parse('https://buymeacoffee.com/privatebydesign');
    try {
      if (!await launchUrl(donationUri, mode: LaunchMode.externalApplication)) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('Could not open donation link'),
              backgroundColor: Colors.red,
            ),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Could not open donation link'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  Future<void> _showExportDialog() async {
    final options = await showExportDialog(
      context: context,
      initialOptions: ExportOptions.fullBackup(),
    );
    
    if (options != null) {
      await _performExport(options);
    }
  }

  Future<void> _exportToCsv() async {
    final options = await showExportDialog(
      context: context,
      initialOptions: ExportOptions.csvExport(),
    );
    
    if (options != null) {
      await _performExport(options);
    }
  }

  Future<void> _performExport(ExportOptions options) async {
    try {
      setState(() => _isLoading = true);
      
      // Show progress dialog without waiting for result
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const AlertDialog(
          title: Text('Exporting Data'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 16),
              Text('Creating backup file...'),
            ],
          ),
        ),
      );
      
      try {
        // Perform export and wait for completion
        final file = options.format == ExportFormat.csv 
            ? await _exportService.exportToCsv(options)
            : await _exportService.exportData(options);
        
        if (mounted) {
          // Close progress dialog
          Navigator.of(context).pop();
          
          // Show success dialog automatically
          _showExportSuccess(file);
          
          // Refresh local backups
          _loadLocalBackups();
        }
      } catch (error) {
        if (mounted) {
          // Close progress dialog
          Navigator.of(context).pop();
          
          // Handle user cancellation gracefully
          if (error.toString().contains('Export cancelled by user')) {
            // User cancelled the save dialog - just return silently
            return;
          }
          
          // Show error for other failures
          _showError('Export Failed', error.toString());
        }
      }
      
    } catch (e) {
      if (mounted) {
        _showError('Export Error', e.toString());
      }
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  Future<void> _showCsvImportDialog() async {
    try {
      // Pick CSV file to import
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['csv'],
        allowMultiple: false,
      );

      if (result != null && result.files.single.path != null) {
        final file = File(result.files.single.path!);
        
        // Validate it's a CSV file
        if (!file.path.toLowerCase().endsWith('.csv')) {
          _showError('Invalid File Type', 'Please select a CSV file.');
          return;
        }
        
        // Show CSV import configuration dialog
        final conflictResolution = await _showCsvImportConfigDialog();
        if (conflictResolution != null) {
          await _performCsvImport(file, conflictResolution);
        }
      }
    } catch (e) {
      _showError('CSV Import Error', e.toString());
    }
  }

  Future<void> _showImportDialog() async {
    try {
      // Pick file to import
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['json'],
        allowMultiple: false,
      );

      if (result != null && result.files.single.path != null) {
        final file = File(result.files.single.path!);
        
        // Load and validate backup metadata
        BackupMetadata? metadata;
        try {
          metadata = await _importService.previewBackup(file);
        } catch (e) {
          _showError('Invalid Backup File', 
            'Unable to read backup file. Please ensure it\'s a valid backup created by this app.');
          return;
        }
        
        // Show import configuration dialog
        final importConfig = await showImportDialog(
          context: context,
          metadata: metadata,
        );
        
        if (importConfig != null) {
          await _performImport(
            file,
            importConfig['conflictResolution'] as ConflictResolution,
            importConfig['includeSettings'] as bool,
          );
        }
      }
    } catch (e) {
      _showError('Import Error', e.toString());
    }
  }

  Future<ConflictResolution?> _showCsvImportConfigDialog() async {
    return await showDialog<ConflictResolution>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('CSV Import Options'),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('How should duplicate entries be handled?'),
            SizedBox(height: 8),
            Text('Duplicates are detected by matching timestamps (within the same minute).'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(ConflictResolution.keepExisting),
            child: const Text('Skip Duplicates'),
          ),
          FilledButton(
            onPressed: () => Navigator.of(context).pop(ConflictResolution.replaceWithImported),
            child: const Text('Replace Existing'),
          ),
        ],
      ),
    );
  }

  Future<void> _performCsvImport(File file, ConflictResolution conflictResolution) async {
    try {
      setState(() => _isLoading = true);
      
      // Show progress dialog
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const AlertDialog(
          title: Text('Importing CSV Data'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 16),
              Text('Processing CSV file...'),
            ],
          ),
        ),
      );
      
      try {
        // Read and validate CSV file
        final csvContent = await file.readAsString();
        final lines = csvContent.split('\n').where((line) => line.trim().isNotEmpty).toList();
        
        if (lines.isEmpty) {
          throw Exception('CSV file is empty');
        }
        
        // Validate header
        final header = lines[0].trim();
        if (header != 'Type,Date,Time,Value1,Value2,Unit,Category,Notes') {
          throw Exception('Invalid CSV format. Expected header: Type,Date,Time,Value1,Value2,Unit,Category,Notes\nFound: $header');
        }
        
        // Get existing entries for duplicate detection
        final existingWeightEntries = await _databaseService.getWeightEntries();
        final existingBloodPressureEntries = await _databaseService.getBloodPressureEntries();
        final existingMoodEntries = await _databaseService.getMoodEntries();
        
        final existingWeightKeys = <String>{};
        final existingBloodPressureKeys = <String>{};
        final existingMoodKeys = <String>{};
        
        for (final entry in existingWeightEntries) {
          existingWeightKeys.add(_generateEntryKey(entry.timestamp));
        }
        
        for (final entry in existingBloodPressureEntries) {
          existingBloodPressureKeys.add(_generateEntryKey(entry.timestamp));
        }
        
        for (final entry in existingMoodEntries) {
          existingMoodKeys.add(_generateEntryKey(entry.timestamp));
        }
        
        // Parse data rows
        int imported = 0;
        int skipped = 0;
        int failed = 0;
        final errors = <String>[];
        
        for (int i = 1; i < lines.length; i++) {
          try {
            final parts = _parseCsvLine(lines[i]);
            if (parts.length >= 8) {
              final type = parts[0].trim();
              final date = parts[1].trim();
              final time = parts[2].trim();
              final value1 = parts[3].trim();
              final value2 = parts[4].trim();
              final unit = parts[5].trim();
              final notes = parts[7].trim();
              

              
              final timestamp = DateTime.parse('${date}T$time');
              
              if (type == 'Weight' && value1.isNotEmpty && value1.trim().isNotEmpty) {
                final weight = double.tryParse(value1.trim());
                if (weight != null) {
                  final entry = WeightEntry(
                    id: 0,
                    timestamp: timestamp,
                    weightKg: weight,
                    originalUnit: unit.isEmpty ? 'kg' : unit,
                    notes: notes.isEmpty ? null : notes,
                  );
                  
                  final key = _generateEntryKey(timestamp);
                  if (existingWeightKeys.contains(key)) {
                    if (conflictResolution == ConflictResolution.replaceWithImported) {
                      await _databaseService.updateWeightEntry(entry);
                      imported++;
                    } else {
                      skipped++;
                    }
                  } else {
                    await _databaseService.insertWeightEntry(entry);
                    imported++;
                  }
                }
              } else if (type == 'Blood Pressure' && value1.isNotEmpty && value2.isNotEmpty && value1.trim().isNotEmpty && value2.trim().isNotEmpty) {
                final systolic = double.tryParse(value1.trim())?.round();
                final diastolic = double.tryParse(value2.trim())?.round();
                if (systolic != null && diastolic != null) {
                  final entry = BloodPressureEntry(
                    id: 0,
                    timestamp: timestamp,
                    systolic: systolic,
                    diastolic: diastolic,
                    notes: notes.isEmpty ? null : notes,
                  );
                  
                  final key = _generateEntryKey(timestamp);
                  if (existingBloodPressureKeys.contains(key)) {
                    if (conflictResolution == ConflictResolution.replaceWithImported) {
                      await _databaseService.updateBloodPressureEntry(entry);
                      imported++;
                    } else {
                      skipped++;
                    }
                  } else {
                    await _databaseService.insertBloodPressureEntry(entry);
                    imported++;
                  }
                }
              } else if (type == 'Mood' && value1.isNotEmpty && value1.trim().isNotEmpty) {
                final moodType = MoodType.values.firstWhere(
                  (m) => m.name == value1,
                  orElse: () => MoodType.neutral,
                );
                final entry = MoodEntry(
                  id: 0,
                  timestamp: timestamp,
                  mood: moodType,
                  notes: notes.isEmpty ? null : notes,
                );
                
                final key = _generateEntryKey(timestamp);
                if (existingMoodKeys.contains(key)) {
                  if (conflictResolution == ConflictResolution.replaceWithImported) {
                    await _databaseService.updateMoodEntry(entry);
                    imported++;
                  } else {
                    skipped++;
                  }
                } else {
                  await _databaseService.insertMoodEntry(entry);
                  imported++;
                }
              }
            }
          } catch (e) {
            failed++;
            errors.add('Line ${i + 1}: $e');
          }
        }
        
        if (mounted) {
          Navigator.of(context).pop(); // Close progress dialog
          
          // Show result
          showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: const Text('CSV Import Complete'),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('Imported: $imported entries'),
                  if (skipped > 0) Text('Skipped: $skipped duplicates'),
                  if (failed > 0) Text('Failed: $failed entries'),
                  if (errors.isNotEmpty) ...[
                    const SizedBox(height: 8),
                    const Text('Errors:', style: TextStyle(fontWeight: FontWeight.bold)),
                    ...errors.take(5).map((e) => Text('• $e', style: const TextStyle(fontSize: 12))),
                    if (errors.length > 5) Text('... and ${errors.length - 5} more'),
                  ],
                ],
              ),
              actions: [
                FilledButton(
                  onPressed: () => Navigator.of(context).pop(),
                  child: const Text('OK'),
                ),
              ],
            ),
          );
        }
      } catch (error) {
        if (mounted) {
          Navigator.of(context).pop(); // Close progress dialog
          _showError('CSV Import Failed', error.toString());
        }
      }
    } catch (e) {
      if (mounted) {
        _showError('CSV Import Error', e.toString());
      }
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }
  
  String _generateEntryKey(DateTime timestamp) {
    // Round to the nearest minute to detect close duplicates
    final rounded = DateTime(
      timestamp.year,
      timestamp.month,
      timestamp.day,
      timestamp.hour,
      timestamp.minute,
    );
    return rounded.toIso8601String();
  }

  List<String> _parseCsvLine(String line) {
    final result = <String>[];
    bool inQuotes = false;
    String current = '';
    
    for (int i = 0; i < line.length; i++) {
      final char = line[i];
      
      if (char == '"') {
        inQuotes = !inQuotes;
      } else if (char == ',' && !inQuotes) {
        result.add(current);
        current = '';
      } else {
        current += char;
      }
    }
    result.add(current);
    
    return result;
  }

  Future<void> _performImport(
    File file,
    ConflictResolution conflictResolution,
    bool includeSettings,
  ) async {
    try {
      setState(() => _isLoading = true);
      
      // Show progress dialog without waiting for result
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const AlertDialog(
          title: Text('Importing Data'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 16),
              Text('Restoring backup data...'),
            ],
          ),
        ),
      );
      
      try {
        // Perform import and wait for completion
        final importResult = await _importService.importData(
          file: file,
          conflictResolution: conflictResolution,
          importSettings: includeSettings,
        );
        
        if (mounted) {
          // Close progress dialog
          Navigator.of(context).pop();
          
          // Show import result dialog automatically
          _showImportResult(importResult);
        }
      } catch (error) {
        if (mounted) {
          // Close progress dialog
          Navigator.of(context).pop();
          
          // Show error
          _showError('Import Failed', error.toString());
        }
      }
      
    } catch (e) {
      if (mounted) {
        _showError('Import Error', e.toString());
      }
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  Future<void> _loadLocalBackups() async {
    try {
      setState(() => _isLoading = true);
      final backups = await FileUtils.listBackupFiles();
      setState(() {
        _localBackups = backups;
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      _showError('Error Loading Backups', e.toString());
    }
  }

  Future<BackupMetadata?> _loadBackupMetadata(File file) async {
    try {
      // Skip metadata loading for CSV files
      if (file.path.toLowerCase().endsWith('.csv')) {
        return null;
      }
      return await _importService.previewBackup(file);
    } catch (e) {
      return null;
    }
  }

  void _showFileDetails(File file, BackupMetadata? metadata) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Backup Details'),
        content: SizedBox(
          width: double.maxFinite,
          child: FileInfoDisplay(
            file: file,
            metadata: metadata,
            onShare: () => _shareFile(file),
            onDelete: () => _deleteFile(file),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Close'),
          ),
          if (file.path.toLowerCase().endsWith('.json'))
            FilledButton(
              onPressed: () {
                Navigator.of(context).pop();
                _importFromFile(file);
              },
              child: const Text('Import'),
            ),
        ],
      ),
    );
  }

  Future<void> _importFromFile(File file) async {
    try {
      BackupMetadata? metadata;
      try {
        metadata = await _importService.previewBackup(file);
      } catch (e) {
        // If metadata preview fails, still allow import with default settings
        debugPrint('Failed to preview backup metadata: $e');
      }
      
      final importConfig = await showImportDialog(
        context: context,
        metadata: metadata,
      );
      
      if (importConfig != null) {
        await _performImport(
          file,
          importConfig['conflictResolution'] as ConflictResolution,
          importConfig['includeSettings'] as bool,
        );
      }
    } catch (e) {
      _showError('Import Error', e.toString());
    }
  }

  Future<void> _shareFile(File file) async {
    try {
      await FileUtils.shareFile(file);
    } catch (e) {
      _showError('Share Error', 'Unable to share file: ${e.toString()}');
    }
  }

  Future<void> _deleteFile(File file) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Delete Backup'),
        content: Text(
          'Are you sure you want to delete "${FileUtils.getFileName(file.path)}"?\n\nThis action cannot be undone.',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('Cancel'),
          ),
          FilledButton(
            onPressed: () => Navigator.of(context).pop(true),
            style: FilledButton.styleFrom(
              backgroundColor: Theme.of(context).colorScheme.error,
            ),
            child: const Text('Delete'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      try {
        await file.delete();
        await _loadLocalBackups();
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Backup deleted successfully')),
          );
        }
      } catch (e) {
        _showError('Delete Error', 'Unable to delete file: ${e.toString()}');
      }
    }
  }

  void _showExportSuccess(File file) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Row(
          children: [
            Icon(Icons.check_circle, color: Colors.green),
            SizedBox(width: 8),
            Text('Export Successful'),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('Your data has been successfully exported.'),
            const SizedBox(height: 16),
            Text(
              'File: ${FileUtils.getFileName(file.path)}',
              style: const TextStyle(fontWeight: FontWeight.w500),
            ),
            Text('Size: ${_formatFileSize(file.lengthSync())}'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Close'),
          ),
          FilledButton.icon(
            onPressed: () {
              Navigator.of(context).pop();
              _shareFile(file);
            },
            icon: const Icon(Icons.share),
            label: const Text('Share'),
          ),
        ],
      ),
    );
  }

  void _showImportResult(ImportResult result) {
    showImportResult(
      context: context,
      result: result,
      onViewData: () {
        Navigator.of(context).pop(); // Close backup screen
        Navigator.of(context).pop(); // Go back to main app
      },
    );
  }

  void _showError(String title, String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            const Icon(Icons.error, color: Colors.red),
            const SizedBox(width: 8),
            Text(title),
          ],
        ),
        content: Text(message),
        actions: [
          FilledButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('OK'),
          ),
        ],
      ),
    );
  }

  String _formatFileSize(int bytes) {
    if (bytes < 1024) return '$bytes B';
    if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
    return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
  }
}
