// ABOUTME: Security settings screen for managing encryption, authentication, and data protection
// ABOUTME: Provides controls for enabling/disabling encryption, migration, and security preferences

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../bloc/security/security_bloc.dart';
import '../bloc/security/security_event.dart';
import '../bloc/security/security_state.dart';
import '../services/encrypted_database_service.dart';
import '../services/preferences_service.dart';
import '../widgets/settings/setting_section.dart';
import '../widgets/settings/setting_switch.dart';
import '../widgets/settings/setting_info_tile.dart';
import '../utils/constants.dart';

class SecuritySettingsScreen extends StatefulWidget {
  const SecuritySettingsScreen({Key? key}) : super(key: key);

  @override
  State<SecuritySettingsScreen> createState() => _SecuritySettingsScreenState();
}

class _SecuritySettingsScreenState extends State<SecuritySettingsScreen> {
  final _passwordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();
  bool _isPasswordVisible = false;
  bool _isConfirmPasswordVisible = false;

  @override
  void dispose() {
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Security Settings'),
        elevation: 0,
      ),
      body: BlocBuilder<SecurityBloc, SecurityState>(
        builder: (context, state) {
          return SingleChildScrollView(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildEncryptionSection(context, state),
                const SizedBox(height: 24),
                _buildAuthenticationSection(context, state),
                const SizedBox(height: 24),
                _buildDataProtectionSection(context, state),
                const SizedBox(height: 24),
                _buildSecurityStatusSection(context, state),
                const SizedBox(height: 24),
                _buildAdvancedSection(context, state),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildEncryptionSection(BuildContext context, SecurityState state) {
    final encryptionEnabled = state is SecurityAuthenticated && 
        EncryptedDatabaseService.instance.isEncryptionEnabled;

    return SettingSection(
      title: 'Data Encryption',
      icon: Icons.lock,
      children: [
        SettingSwitch(
          title: 'Enable Local Encryption',
          subtitle: 'Encrypt health data stored on device',
          value: encryptionEnabled,
          onChanged: (value) => _handleEncryptionToggle(context, value),
        ),
        if (!encryptionEnabled) ...[
          const SizedBox(height: 8),
          _buildEncryptionSetupCard(context, state),
        ] else ...[
          const SizedBox(height: 8),
          _buildEncryptionStatusCard(context, state),
        ],
      ],
    );
  }

  Widget _buildEncryptionSetupCard(BuildContext context, SecurityState state) {
    return Card(
      color: Theme.of(context).colorScheme.surfaceVariant,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  Icons.info_outline,
                  color: Theme.of(context).colorScheme.primary,
                ),
                const SizedBox(width: 8),
                Text(
                  'Encryption Setup',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    color: Theme.of(context).colorScheme.primary,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Text(
              'Encrypt your health data to protect it even if your device is compromised. '
              'You\'ll need to create a password that will be required to access your data.',
              style: Theme.of(context).textTheme.bodyMedium,
            ),
            const SizedBox(height: 16),
            _buildPasswordFields(context, state),
            const SizedBox(height: 16),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton.icon(
                onPressed: state is SecurityLoading ? null : () => _setupEncryption(context),
                icon: state is SecurityLoading
                    ? const SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      )
                    : const Icon(Icons.shield),
                label: Text(state is SecurityLoading ? 'Setting up...' : 'Enable Encryption'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPasswordFields(BuildContext context, SecurityState state) {
    return Column(
      children: [
        TextField(
          controller: _passwordController,
          obscureText: !_isPasswordVisible,
          decoration: InputDecoration(
            labelText: 'Encryption Password',
            hintText: 'Create a strong password',
            border: const OutlineInputBorder(),
            suffixIcon: IconButton(
              onPressed: () {
                setState(() {
                  _isPasswordVisible = !_isPasswordVisible;
                });
              },
              icon: Icon(_isPasswordVisible ? Icons.visibility_off : Icons.visibility),
            ),
          ),
        ),
        const SizedBox(height: 12),
        TextField(
          controller: _confirmPasswordController,
          obscureText: !_isConfirmPasswordVisible,
          decoration: InputDecoration(
            labelText: 'Confirm Password',
            hintText: 'Re-enter your password',
            border: const OutlineInputBorder(),
            suffixIcon: IconButton(
              onPressed: () {
                setState(() {
                  _isConfirmPasswordVisible = !_isConfirmPasswordVisible;
                });
              },
              icon: Icon(_isConfirmPasswordVisible ? Icons.visibility_off : Icons.visibility),
            ),
          ),
        ),
        const SizedBox(height: 8),
        Row(
          children: [
            Icon(
              Icons.warning,
              size: 16,
              color: Theme.of(context).colorScheme.onSurfaceVariant,
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Text(
                'Important: If you forget this password, your data cannot be recovered.',
                style: Theme.of(context).textTheme.bodySmall?.copyWith(
                  color: Theme.of(context).colorScheme.onSurfaceVariant,
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildEncryptionStatusCard(BuildContext context, SecurityState state) {
    return Card(
      color: Theme.of(context).colorScheme.secondaryContainer,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  Icons.verified,
                  color: Theme.of(context).colorScheme.onSecondaryContainer,
                ),
                const SizedBox(width: 8),
                Text(
                  'Encryption Active',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    color: Theme.of(context).colorScheme.onSecondaryContainer,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Text(
              'Your health data is encrypted and protected with AES-256 encryption.',
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Theme.of(context).colorScheme.onSecondaryContainer,
              ),
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: () => _showEncryptionStatistics(context),
                    icon: const Icon(Icons.analytics),
                    label: const Text('View Statistics'),
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: () => _showChangePasswordDialog(context),
                    icon: const Icon(Icons.password),
                    label: const Text('Change Password'),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAuthenticationSection(BuildContext context, SecurityState state) {
    return SettingSection(
      title: 'Authentication',
      icon: Icons.fingerprint,
      children: [
        SettingInfoTile(
          title: 'Biometric Authentication',
          subtitle: state is SecurityAuthenticated && state.authMethod.supportsBiometrics
              ? 'Available and configured'
              : 'Not available on this device',
          trailing: state is SecurityAuthenticated && state.authMethod.supportsBiometrics
              ? Icon(Icons.check_circle, color: Theme.of(context).colorScheme.primary)
              : Icon(Icons.cancel, color: Theme.of(context).colorScheme.onSurfaceVariant),
        ),
        SettingInfoTile(
          title: 'Session Timeout',
          subtitle: 'Auto-lock after 15 minutes of inactivity',
          trailing: TextButton(
            onPressed: () => _showSessionTimeoutDialog(context),
            child: const Text('Configure'),
          ),
        ),
      ],
    );
  }

  Widget _buildDataProtectionSection(BuildContext context, SecurityState state) {
    return SettingSection(
      title: 'Data Protection',
      icon: Icons.security,
      children: [
        SettingSwitch(
          title: 'Secure App in Background',
          subtitle: 'Hide app content when switching between apps',
          value: true, // This would come from settings
          onChanged: (value) {
            // Handle secure background setting
          },
        ),
        SettingSwitch(
          title: 'Screenshot Protection',
          subtitle: 'Prevent screenshots of sensitive data',
          value: true, // This would come from settings
          onChanged: (value) {
            // Handle screenshot protection setting
          },
        ),
        SettingInfoTile(
          title: 'Data Retention',
          subtitle: 'Keep data indefinitely',
          trailing: TextButton(
            onPressed: () => _showDataRetentionDialog(context),
            child: const Text('Configure'),
          ),
        ),
      ],
    );
  }

  Widget _buildSecurityStatusSection(BuildContext context, SecurityState state) {
    final securityLevel = _calculateSecurityLevel(state);
    final securityColor = _getSecurityColor(context, securityLevel);
    
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(Icons.shield, color: securityColor),
                const SizedBox(width: 8),
                Text(
                  'Security Status',
                  style: Theme.of(context).textTheme.titleMedium,
                ),
              ],
            ),
            const SizedBox(height: 12),
            LinearProgressIndicator(
              value: securityLevel / 100,
              backgroundColor: Theme.of(context).colorScheme.surfaceVariant,
              valueColor: AlwaysStoppedAnimation<Color>(securityColor),
            ),
            const SizedBox(height: 8),
            Text(
              'Security Level: $securityLevel% ${_getSecurityLevelText(securityLevel)}',
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: securityColor,
                fontWeight: FontWeight.medium,
              ),
            ),
            const SizedBox(height: 12),
            _buildSecurityChecklist(context, state),
          ],
        ),
      ),
    );
  }

  Widget _buildSecurityChecklist(BuildContext context, SecurityState state) {
    final isEncrypted = state is SecurityAuthenticated && 
        EncryptedDatabaseService.instance.isEncryptionEnabled;
    final hasBiometrics = state is SecurityAuthenticated && state.authMethod.supportsBiometrics;

    return Column(
      children: [
        _buildChecklistItem(
          context,
          'Local data encryption enabled',
          isEncrypted,
        ),
        _buildChecklistItem(
          context,
          'Biometric authentication available',
          hasBiometrics,
        ),
        _buildChecklistItem(
          context,
          'Secure storage configured',
          state is SecurityAuthenticated,
        ),
        _buildChecklistItem(
          context,
          'Session management active',
          state is SecurityAuthenticated,
        ),
      ],
    );
  }

  Widget _buildChecklistItem(BuildContext context, String title, bool completed) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        children: [
          Icon(
            completed ? Icons.check_circle : Icons.radio_button_unchecked,
            size: 16,
            color: completed 
                ? Theme.of(context).colorScheme.primary
                : Theme.of(context).colorScheme.onSurfaceVariant,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              title,
              style: Theme.of(context).textTheme.bodySmall,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAdvancedSection(BuildContext context, SecurityState state) {
    return SettingSection(
      title: 'Advanced',
      icon: Icons.engineering,
      children: [
        ListTile(
          title: const Text('Security Audit Log'),
          subtitle: const Text('View authentication and access logs'),
          leading: const Icon(Icons.history),
          trailing: const Icon(Icons.chevron_right),
          onTap: () => _showSecurityAuditLog(context),
        ),
        ListTile(
          title: const Text('Verify Data Integrity'),
          subtitle: const Text('Check encrypted data for corruption'),
          leading: const Icon(Icons.verified_user),
          trailing: const Icon(Icons.chevron_right),
          onTap: () => _verifyDataIntegrity(context),
        ),
        if (EncryptedDatabaseService.instance.isEncryptionEnabled) ...[
          ListTile(
            title: const Text('Disable Encryption'),
            subtitle: const Text('Remove encryption from all data'),
            leading: Icon(Icons.lock_open, color: Theme.of(context).colorScheme.error),
            trailing: const Icon(Icons.chevron_right),
            onTap: () => _showDisableEncryptionDialog(context),
          ),
        ],
      ],
    );
  }

  void _handleEncryptionToggle(BuildContext context, bool value) {
    if (value) {
      _showPasswordSetupDialog(context);
    } else {
      _showDisableEncryptionDialog(context);
    }
  }

  void _showPasswordSetupDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: const Text('Setup Encryption'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text(
              'Create a password to encrypt your health data. This password will be required to access your data.',
            ),
            const SizedBox(height: 16),
            TextField(
              controller: _passwordController,
              obscureText: !_isPasswordVisible,
              decoration: InputDecoration(
                labelText: 'Encryption Password',
                hintText: 'Enter a strong password',
                border: const OutlineInputBorder(),
                suffixIcon: IconButton(
                  icon: Icon(_isPasswordVisible ? Icons.visibility_off : Icons.visibility),
                  onPressed: () => setState(() => _isPasswordVisible = !_isPasswordVisible),
                ),
              ),
            ),
            const SizedBox(height: 12),
            TextField(
              controller: _confirmPasswordController,
              obscureText: !_isConfirmPasswordVisible,
              decoration: InputDecoration(
                labelText: 'Confirm Password',
                hintText: 'Re-enter your password',
                border: const OutlineInputBorder(),
                suffixIcon: IconButton(
                  icon: Icon(_isConfirmPasswordVisible ? Icons.visibility_off : Icons.visibility),
                  onPressed: () => setState(() => _isConfirmPasswordVisible = !_isConfirmPasswordVisible),
                ),
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              _clearPasswordFields();
              Navigator.of(context).pop();
            },
            child: const Text('Cancel'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              _setupEncryption(context);
            },
            child: const Text('Enable Encryption'),
          ),
        ],
      ),
    );
  }

  void _setupEncryption(BuildContext context) {
    final password = _passwordController.text;
    final confirmPassword = _confirmPasswordController.text;

    if (password.isEmpty || confirmPassword.isEmpty) {
      _showError(context, 'Please enter a password in both fields.');
      return;
    }

    if (password != confirmPassword) {
      _showError(context, 'Passwords do not match.');
      return;
    }

    if (password.length < 8) {
      _showError(context, 'Password must be at least 8 characters long.');
      return;
    }

    // Show migration dialog
    _showEncryptionMigrationDialog(context, password);
  }

  void _showEncryptionMigrationDialog(BuildContext context, String password) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: const Text('Enable Encryption'),
        content: const Text(
          'This will encrypt all your existing health data. The process may take a few minutes depending on how much data you have.\n\n'
          'During this process, please keep the app open and don\'t switch to other apps.',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Cancel'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              _performEncryptionMigration(context, password);
            },
            child: const Text('Start Encryption'),
          ),
        ],
      ),
    );
  }

  void _performEncryptionMigration(BuildContext context, String password) async {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const _EncryptionMigrationDialog(),
    );

    try {
      final result = await EncryptedDatabaseService.instance.migrateToEncrypted(
        password: password,
        onProgress: (processed, total) {
          // Progress updates would be handled here
        },
      );

      Navigator.of(context).pop(); // Close progress dialog

      if (result.success) {
        // Mark encryption as enabled in preferences
        await PreferencesService.instance.setEncryptionEnabled(true);
        
        _clearPasswordFields();
        context.read<SecurityBloc>().add(SecurityInitialize());
        _showSuccess(context, 'Encryption enabled successfully! ${result.totalMigrated} entries encrypted.');
      } else {
        _showError(context, 'Failed to enable encryption: ${result.error}');
      }
    } catch (e) {
      Navigator.of(context).pop(); // Close progress dialog
      _showError(context, 'Failed to enable encryption: $e');
    }
  }

  void _clearPasswordFields() {
    _passwordController.clear();
    _confirmPasswordController.clear();
  }

  void _showEncryptionStatistics(BuildContext context) async {
    final stats = await EncryptedDatabaseService.instance.getEncryptionStatistics();
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Encryption Statistics'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildStatRow('Encrypted Entries:', '${stats.totalEncryptedEntries}'),
            _buildStatRow('Encryption Ratio:', '${(stats.encryptionRatio * 100).toStringAsFixed(1)}%'),
            _buildStatRow('Average Encryption Time:', '${stats.averageEncryptionTime.inMilliseconds}ms'),
            _buildStatRow('Compression Ratio:', '${(stats.averageCompressionRatio * 100).toStringAsFixed(1)}%'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Close'),
          ),
        ],
      ),
    );
  }

  Widget _buildStatRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label),
          Text(value, style: const TextStyle(fontWeight: FontWeight.bold)),
        ],
      ),
    );
  }

  void _showChangePasswordDialog(BuildContext context) {
    // Implement change password dialog
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Change password feature coming soon')),
    );
  }

  void _showSessionTimeoutDialog(BuildContext context) {
    // Implement session timeout configuration
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Session timeout configuration coming soon')),
    );
  }

  void _showDataRetentionDialog(BuildContext context) {
    // Implement data retention configuration
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Data retention configuration coming soon')),
    );
  }

  void _showSecurityAuditLog(BuildContext context) {
    // Implement security audit log viewer
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Security audit log coming soon')),
    );
  }

  void _verifyDataIntegrity(BuildContext context) async {
    if (!EncryptedDatabaseService.instance.isEncryptionEnabled) {
      _showError(context, 'Encryption is not enabled.');
      return;
    }

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const AlertDialog(
        content: Row(
          children: [
            CircularProgressIndicator(),
            SizedBox(width: 16),
            Text('Verifying data integrity...'),
          ],
        ),
      ),
    );

    try {
      final result = await EncryptedDatabaseService.instance.verifyDataIntegrity();
      Navigator.of(context).pop();

      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Text(result.success ? 'Verification Complete' : 'Issues Found'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Total entries: ${result.totalEntries}'),
              Text('Valid entries: ${result.validEntries}'),
              Text('Corrupted entries: ${result.corruptedEntries}'),
              Text('Integrity ratio: ${(result.integrityRatio * 100).toStringAsFixed(1)}%'),
              if (result.errors.isNotEmpty) ...[
                const SizedBox(height: 12),
                const Text('Errors found:', style: TextStyle(fontWeight: FontWeight.bold)),
                ...result.errors.take(3).map((error) => Text('• $error')),
                if (result.errors.length > 3)
                  Text('... and ${result.errors.length - 3} more'),
              ],
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('Close'),
            ),
          ],
        ),
      );
    } catch (e) {
      Navigator.of(context).pop();
      _showError(context, 'Failed to verify data integrity: $e');
    }
  }

  void _showDisableEncryptionDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Disable Encryption'),
        content: const Text(
          'Are you sure you want to disable encryption? This will decrypt all your health data and store it in plain text.\n\n'
          'This action cannot be undone and your data will be less secure.',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Cancel'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              _disableEncryption(context);
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Theme.of(context).colorScheme.error,
            ),
            child: const Text('Disable Encryption'),
          ),
        ],
      ),
    );
  }

  void _disableEncryption(BuildContext context) {
    // This would involve decrypting all data and moving it back to regular tables
    // For now, just disable encryption
    EncryptedDatabaseService.instance.disableEncryption();
    context.read<SecurityBloc>().add(SecurityInitialize());
    _showSuccess(context, 'Encryption has been disabled.');
  }

  int _calculateSecurityLevel(SecurityState state) {
    int score = 0;
    
    if (state is SecurityAuthenticated) {
      score += 25; // Basic authentication
      
      if (state.authMethod.supportsBiometrics) {
        score += 25; // Biometric support
      }
      
      if (EncryptedDatabaseService.instance.isEncryptionEnabled) {
        score += 40; // Encryption enabled
      }
      
      score += 10; // Secure storage
    }
    
    return score;
  }

  Color _getSecurityColor(BuildContext context, int level) {
    if (level >= 80) return Colors.green;
    if (level >= 50) return Colors.orange;
    return Theme.of(context).colorScheme.error;
  }

  String _getSecurityLevelText(int level) {
    if (level >= 80) return 'Excellent';
    if (level >= 60) return 'Good';
    if (level >= 40) return 'Fair';
    return 'Needs Improvement';
  }

  void _showError(BuildContext context, String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Theme.of(context).colorScheme.error,
      ),
    );
  }

  void _showSuccess(BuildContext context, String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
      ),
    );
  }
}

class _EncryptionMigrationDialog extends StatefulWidget {
  const _EncryptionMigrationDialog({Key? key}) : super(key: key);

  @override
  State<_EncryptionMigrationDialog> createState() => _EncryptionMigrationDialogState();
}

class _EncryptionMigrationDialogState extends State<_EncryptionMigrationDialog>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat();
    _animation = Tween<double>(begin: 0, end: 1).animate(_controller);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          AnimatedBuilder(
            animation: _animation,
            builder: (context, child) {
              return CircularProgressIndicator(
                value: _animation.value,
              );
            },
          ),
          const SizedBox(height: 16),
          const Text(
            'Encrypting your health data...',
            style: TextStyle(fontSize: 16),
          ),
          const SizedBox(height: 8),
          Text(
            'This may take a few minutes.\nPlease keep the app open.',
            textAlign: TextAlign.center,
            style: Theme.of(context).textTheme.bodyMedium?.copyWith(
              color: Theme.of(context).colorScheme.onSurfaceVariant,
            ),
          ),
        ],
      ),
    );
  }
}
